@clipform/mcp-server 5.20.0 → 5.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../config/features.js","../../config/help-links.js","../../config/draw-presets.js","../../config/logic-types.js","../../config/variables.js","../../config/node-types.js","../../config/recall.js","../../config/validate.js","../../config/form-types.js","../../config/anon-mcp-limits.js","../../config/logic-chain.js","../../config/guide.js","../../config/index.js","../src/lib/api-client.ts"],"sourcesContent":["/**\n * Feature registry - single source of truth for what Clipform can and cannot do.\n *\n * enabled: runtime gate - does the dashboard/viewer expose this feature?\n * status:\n * 'live' - shipped and working in production\n * 'beta' - available but not fully polished\n * 'planned' - on the roadmap, not yet usable\n *\n * Rules:\n * - Marketing copy, blog posts, and landing pages must only claim features with status 'live'\n * - 'planned' features can be mentioned as \"coming soon\" but never as current capability\n * - When a feature ships: set enabled to true, status to 'live', and stamp wentLiveAt\n * - Everything else derives from this file (PRODUCT.features, FEATURE_FLAGS, content claims)\n *\n * wentLiveAt (optional, 'YYYY-MM-DD'): the date a feature flipped planned -> live. It is\n * the dated capability event the What's New changelog renders (getWhatsNew) and the SEO/GTM\n * skills key off (\"live-but-uncovered -> content backlog\"). Best-effort: features that were\n * already live at this registry's baseline have no known date and stay undated - they're\n * simply absent from the dated timeline until backfilled, never stamped with a wrong date.\n *\n * announce (optional): the dashboard \"What's new\" pop-up slide ({ headline, benefit, href?,\n * palette?, media? }). Benefit-first, sentence case, no em dashes. href is a workspace-relative\n * dashboard path (no leading slash or protocol); without it the action falls back to the\n * feature's help link. palette names an ANNOUNCE_PALETTES entry (default: step colour, then\n * category). media is a real screenshot or clip under apps/dashboard/public/whats-new/ with its\n * pixel width/height. Needs wentLiveAt.\n *\n * @type {Record<string, { name: string, description: string, enabled: boolean, status: 'live' | 'beta' | 'planned', category: string, wentLiveAt?: string, announce?: { headline: string, benefit: string, href?: string, palette?: string, media?: { kind: 'image' | 'video', src: string, width: number, height: number, poster?: string } } }>}\n */\nexport const FEATURES = {\n // -- Builder --\n visual_form_builder: {\n name: 'Visual form builder',\n description: 'Drag-and-drop node-based form builder powered by React Flow',\n enabled: true,\n status: 'live',\n category: 'builder',\n },\n form_themes: {\n name: 'Form themes',\n description: 'Customise primary colour, background colour, and font',\n enabled: true,\n status: 'live',\n category: 'builder',\n },\n media_prompts: {\n name: 'Media prompts',\n description: 'Attach video, audio, or images to any question node',\n enabled: true,\n status: 'live',\n category: 'builder',\n },\n consent_documents: {\n name: 'Agreement documents',\n description: 'Attach a PDF agreement to a consent item, read inline in the viewer with scroll-to-accept',\n enabled: true,\n status: 'live',\n category: 'builder',\n wentLiveAt: '2026-10-02',\n announce: {\n headline: 'Attach a PDF agreement to consent',\n benefit: 'Respondents read it inline and scroll to accept before they continue.',\n },\n },\n node_logic: {\n name: 'Node routing logic',\n description: 'Define the order nodes appear in - currently supports linear paths (A to B to C)',\n enabled: true,\n status: 'live',\n category: 'builder',\n },\n // Backfilled (#4338): apps/viewer/components/FormViewer.tsx renders exactly\n // one node at a time (`currentNode = nodes[currentIndex]`, single\n // `AnimatePresence` block gating on `currentNode`) and transitions to the\n // next on answer - never a scrollable list of every question. No\n // enabled/status change (this has always been the viewer's shape), so no\n // wentLiveAt.\n one_question_at_a_time: {\n name: 'One question at a time',\n description: 'The viewer shows a single question and transitions to the next, never a scrollable list of every question',\n enabled: true,\n status: 'live',\n category: 'builder',\n },\n branching: {\n name: 'Conditional branching',\n description: 'Choice nodes route to different destinations based on which option is picked',\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-06-25',\n category: 'builder',\n },\n funnel: {\n name: 'Lead qualification funnels',\n description: 'Multi-step funnels with conditional routing built on branching',\n enabled: false,\n status: 'planned',\n category: 'builder',\n },\n custom_scores: {\n name: 'Custom scoring',\n description: 'Assign scores to choice options for quizzes and assessments',\n enabled: false,\n status: 'planned',\n category: 'builder',\n },\n text_response: {\n name: 'Text response option',\n description: 'Allow free-text input alongside choice options',\n enabled: false,\n status: 'planned',\n category: 'builder',\n },\n multi_select: {\n name: 'Multi-select choices',\n description: 'Pick-all-that-apply choice questions (checkbox-style selection)',\n // Dogfood-only (#151): invisible beta - enabled:false, never 'live'/'planned' so\n // no public surface lists it. Available to FEATURE_COMPANY_ALLOWLIST.multi_select\n // via companyHasMultiSelect; the global flip (+ wentLiveAt) is the launch step.\n enabled: false,\n status: 'beta',\n category: 'builder',\n },\n variables: {\n name: 'Custom variables',\n description: 'Save answers to named number or text variables and use them in logic and results',\n // Dogfood-only (#5242): invisible beta - enabled:false, never 'live'/'planned' so\n // no public surface lists it. Available to FEATURE_COMPANY_ALLOWLIST.variables\n // via companyHasVariables; the global flip (+ wentLiveAt) is the launch step.\n enabled: false,\n status: 'beta',\n category: 'builder',\n },\n response_trash: {\n name: 'Response trash',\n description: 'Move responses to the trash and restore them from the Responses tab',\n // Dogfood-only (#2862): invisible beta - enabled:false, never 'live'/'planned' so\n // no public surface lists it. Available to FEATURE_COMPANY_ALLOWLIST.response_trash\n // via companyHasResponseTrash; the global flip (+ wentLiveAt) is the launch step.\n enabled: false,\n status: 'beta',\n category: 'builder',\n },\n staged_video_upload: {\n name: 'Large video uploads',\n description: 'Upload long videos and iPhone HDR clips to Clipform storage so they start fast for respondents',\n // Dogfood-only (#6197): invisible beta - enabled:false, never 'live'/'planned' so\n // no public surface lists it. Available to FEATURE_COMPANY_ALLOWLIST.staged_video_upload\n // via getFeatureAccess (the API's upload handshake, apps/api/src/lib/staged-video.ts,\n // and the dashboard's on-device compression). Everyone else keeps the stream route.\n // The flip waits for the media worker host (#5980).\n enabled: false,\n status: 'beta',\n category: 'builder',\n },\n template_walkthrough: {\n name: 'Template walkthrough',\n description: 'A walkthrough written for a company, shown when someone opens their copy of a template in the builder',\n // Dogfood-only (#6269): invisible beta - enabled:false, never 'live'/'planned' so\n // no public surface lists it. Gates AUTHORING only (writing node.config.guide through\n // the API and the MCP's clipform_set_node_guide), via getFeatureAccess for\n // FEATURE_COMPANY_ALLOWLIST.template_walkthrough. Display needs no flag: only copies of\n // a Clipform Public form show a walkthrough.\n enabled: false,\n status: 'beta',\n category: 'builder',\n },\n custom_fonts: {\n name: 'Custom fonts',\n description: 'Upload and use custom fonts in forms',\n enabled: false,\n status: 'planned',\n category: 'builder',\n },\n brand_name: {\n name: 'Custom brand name',\n description: 'Replace Clipform branding with your own brand name',\n enabled: false,\n status: 'planned',\n category: 'builder',\n },\n allow_resume: {\n name: 'Session resume',\n description: 'Respondents can continue a form where they left off',\n enabled: true,\n status: 'live',\n category: 'builder',\n },\n anonymous_builder: {\n name: 'Anonymous builder',\n description: 'Try the builder without an account via /try - an anonymous Supabase session, converted to a real account at publish time',\n // Desktop v1 (#2979) shipped flag-dark: the entry route, publish wall, and\n // conversion modal all land behind this flag. Enabled at launch rollout -\n // the prod Supabase Anonymous Sign-Ins toggle must stay on for /try guest\n // sessions to mint (dev first, then prod after #3016).\n enabled: true,\n status: 'beta',\n category: 'builder',\n },\n try_cohort_landing: {\n name: 'Cohort landing on /try',\n description: 'A UTM-tagged /try visit holds on a cohort-specific landing with a click-to-proceed CTA instead of going straight into the builder',\n // Flagged off (#4816): the landing (#4296) isn't finished, and the viewer's\n // Powered-by link carries utm_* params, so signed-in owners were landing\n // on it too. Off -> a UTM-tagged /try behaves exactly like the no-UTM path.\n enabled: false,\n status: 'planned',\n category: 'builder',\n },\n // Built in #5148 (PR #5155), shipped dark. When off: no builder switch, viewer ignores\n // stored allow_skip, and the MCP hides/drops allow_skip via the config_schema `feature` marker.\n optional_questions: {\n name: 'Optional questions',\n description: 'Builders can mark a draw, camera or booking question optional so respondents can skip it',\n enabled: false,\n status: 'planned',\n category: 'builder',\n },\n draw_target_shape: {\n name: 'Draw target shape',\n description: 'Score a drawing against a builder-drawn target outline (match-to-shape game)',\n // Flagged off for the Draw GA pass (#5052/#5060): existing config.game data\n // is left in place and returns when the flag flips.\n enabled: false,\n status: 'beta',\n category: 'builder',\n },\n\n // -- Node types --\n node_start: {\n name: 'Start node',\n description: 'Entry point for every form',\n enabled: true,\n status: 'live',\n category: 'node-types',\n },\n node_choice: {\n name: 'Multiple choice',\n description: 'Single-select questions with configurable options (multi-select is gated by the multi_select feature)',\n enabled: true,\n status: 'live',\n category: 'node-types',\n },\n node_open: {\n name: 'Open-ended questions',\n description: 'Free-form responses via text, audio, or video',\n enabled: true,\n status: 'live',\n category: 'node-types',\n },\n node_details: {\n name: 'Details',\n // Widened (#4338): the checkbox items are typed 'consent' (required,\n // blocks submission until checked) or 'opt_in' (optional) - see\n // CONSENT_TYPES in node-types.js and the viewer's Contact.tsx. Both are\n // plain text checkboxes available to every creator with no gate. Attaching\n // a PDF agreement document is the separate consent_documents feature (live).\n description: 'Structured fields (name, email, phone, company) with consent and opt-in checkboxes',\n enabled: true,\n status: 'live',\n category: 'node-types',\n },\n node_button: {\n name: 'Button',\n description: 'Simple navigation or statement node',\n enabled: true,\n status: 'live',\n category: 'node-types',\n },\n node_redirect: {\n name: 'Redirect',\n description: 'Terminal node that sends respondents to an external URL',\n enabled: true,\n status: 'live',\n category: 'node-types',\n },\n node_end_screen: {\n name: 'End screen',\n description: 'Configurable thank-you screen with messaging, CTAs, and share button',\n enabled: true,\n status: 'live',\n category: 'node-types',\n },\n node_scale: {\n name: 'Scale / rating',\n description: 'Numerical rating questions (1-10, stars, etc.)',\n enabled: false,\n status: 'planned',\n category: 'node-types',\n },\n node_file_upload: {\n name: 'File upload',\n description: 'Collect files from respondents',\n enabled: false,\n status: 'planned',\n category: 'node-types',\n },\n node_booking: {\n name: 'Booking',\n description: 'Calendly scheduling inside the form',\n // GA 2026-11-08 with Calendly only (#5310). Google Meet stays dark behind\n // integration_google_calendar until #5308/#5309 ship. The\n // NODE_COMPANY_ALLOWLIST.node_booking entry below stays as a safety valve:\n // flip enabled back to false to pull it behind the allowlist again.\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-11-08',\n category: 'node-types',\n announce: {\n headline: 'Let people book a call right in your form',\n benefit: 'Add a Booking step and respondents pick a Calendly time slot without leaving the form.',\n },\n },\n node_draw: {\n name: 'Drawing',\n description: 'Drawing canvas; respondents draw and it is saved as a PNG image',\n // First GA 2026-06-27 (#1012), pulled back behind the allowlist 2026-07-20\n // (#2289), back to GA 2026-10-26 (#5052). The NODE_COMPANY_ALLOWLIST.node_draw\n // entry below stays as a safety valve: flip enabled back to false to pull it\n // behind the allowlist again (creation-gated only - existing nodes render).\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-10-26',\n category: 'node-types',\n announce: {\n headline: 'Let respondents draw their answer',\n benefit: 'Add a Drawing step and each sketch is saved as an image you can view in Responses.',\n },\n },\n node_camera: {\n name: 'Camera',\n // Description mirrors NODE_TYPES.camera.description (the node SSOT) - the\n // node captures photo OR video (allowed_capture, #2759), not photo only.\n description: 'Capture a photo or video from the device camera',\n // GA 2026-10-26 (#5017). The NODE_COMPANY_ALLOWLIST.node_camera entry\n // below stays as a safety valve: flip enabled back to false to pull it\n // behind the allowlist again (draw precedent).\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-10-26',\n category: 'node-types',\n announce: {\n headline: 'Ask for a photo or video from the camera',\n benefit: 'Respondents capture it on their device and it lands with their answers.',\n },\n },\n node_conditional: {\n name: 'If / then',\n description: 'Route the flow to different branches based on a score, max score, or category variable.',\n // Scaffolded disabled (#4105, phase 1 of the #4104 variables engine): code\n // lands ready, but node.type's DB check constraint doesn't accept\n // 'conditional' yet - that's a separate parked holds-migration PR. Flip\n // once the migration has merged (= applied to prod) and the apps have\n // deployed (camera precedent, #2097).\n enabled: false,\n status: 'planned',\n category: 'node-types',\n },\n node_payment: {\n name: 'Payment',\n description: 'Collect payments via Stripe or Paddle inline',\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-09-07',\n category: 'node-types',\n },\n node_binary: {\n name: 'Binary choice',\n description: 'Two-option choice node (yes/no, this/that)',\n enabled: false,\n status: 'planned',\n category: 'node-types',\n },\n node_link_list: {\n name: 'Link list',\n description: 'Terminal node showing a list of links to choose from',\n enabled: false,\n status: 'planned',\n category: 'node-types',\n },\n node_file_download: {\n name: 'File download',\n description: 'Provide files for respondents to download',\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-07-12',\n category: 'node-types',\n },\n node_shopping: {\n name: 'Shopping',\n description: 'Product recommendations with direct checkout',\n enabled: false,\n status: 'planned',\n category: 'node-types',\n },\n\n // -- Response formats --\n text_responses: {\n name: 'Text responses',\n description: 'Respondents type free-form text answers',\n enabled: true,\n status: 'live',\n category: 'responses',\n },\n audio_responses: {\n name: 'Audio responses',\n description: 'Respondents record audio directly in the browser',\n enabled: true,\n status: 'live',\n category: 'responses',\n },\n video_responses: {\n name: 'Video responses',\n description: 'Respondents record video directly in the browser',\n enabled: true,\n status: 'live',\n category: 'responses',\n },\n transcription: {\n name: 'Auto-transcription',\n description: 'Whisper-powered transcription for audio and video responses',\n enabled: true,\n status: 'live',\n category: 'responses',\n },\n // Backfilled (#4338): the respondent-facing recorder (packages/media-recorder)\n // already device-detects and adapts - mobile-first cover framing by default,\n // front/back camera flip control shown only on mobile, iOS Safari getUserMedia\n // quirks handled (browser-detection.ts) - so recording on a phone has always\n // worked and been tuned for it. No enabled/status change, so no wentLiveAt.\n mobile_recording: {\n name: 'Mobile-optimized recording',\n description: 'Respondents recording audio/video/photo on a phone get a mobile-first layout and a front/back camera flip control',\n enabled: true,\n status: 'live',\n category: 'responses',\n },\n\n // -- Analytics --\n analytics_overview: {\n name: 'Analytics dashboard',\n // Widened #4338: views/starts/completions update live (useInsightRealtime,\n // apps/dashboard's analytics page) and NodeResultCard computes a per-node\n // drop-off count (`total_views - answeredCount`, \"N people dropped off\"),\n // not just an aggregate form-level funnel.\n description: 'Real-time views, starts, and completions with daily time series, plus per-question drop-off',\n enabled: true,\n status: 'live',\n category: 'analytics',\n },\n analytics_demographics: {\n name: 'Demographic breakdown',\n description: 'Country, browser, device, and referrer source analytics',\n enabled: true,\n status: 'live',\n category: 'analytics',\n },\n utm_tracking: {\n name: 'UTM parameter tracking',\n description: 'Track utm_source, utm_medium, utm_campaign on form views',\n enabled: false,\n status: 'planned',\n category: 'analytics',\n },\n csv_export: {\n name: 'CSV export',\n description: 'Export response data to CSV, including transcriptions and media links',\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-06-07',\n category: 'analytics',\n },\n excel_export: {\n name: 'Excel export',\n description: 'Export response data to an Excel file, with the same columns as the CSV export',\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-11-05',\n category: 'analytics',\n announce: {\n headline: 'Download responses as an Excel file',\n benefit: 'Get the same columns as the CSV export, ready to open in Excel.',\n },\n },\n // Backfilled (#4338): the Responses table's search box (DataSpreadsheet's\n // globalFilter, TanStack default `includesString` across every visible\n // column) already searches every node-response column's displayed value -\n // for audio/video answers that value falls back to the transcription text\n // (list_form_submissions / get_latest_responses_for_session's\n // response_data->'transcription'->>'text', supabase/migrations\n // 20260920190000_submission_grain_per_completion.sql) before the generic\n // \"Video/Audio response\" label. So a transcribed response is genuinely\n // full-text searchable today - this key just gives that existing behaviour\n // a name marketing can cite. No enabled/status change (search has always\n // been on), so deliberately no wentLiveAt.\n //\n // Scoped honestly (review follow-up, #4338): this is ONE form's Responses\n // table, filtered client-side (TanStack's globalFilter over the rows\n // already loaded for that form) - never cross-form, and a video/audio\n // answer's transcript only becomes searchable once transcription finishes\n // (checked: no write path ever sets response_data.display or .text on a\n // media answer at submit time - only the async transcription pipeline\n // adds `transcription.text` later, so nothing hides the transcript once it\n // lands; transcription itself is not plan-gated, it runs on every\n // audio/video response regardless of plan). It also never jumps playback\n // to the matched moment in the recording - it only surfaces the row.\n response_search: {\n name: 'Response search',\n description: 'Filter one form\\'s responses table by keyword, including transcript text once transcription finishes - not cross-form, and does not jump to a moment in the recording',\n enabled: true,\n status: 'live',\n category: 'analytics',\n },\n tracked_links: {\n name: 'Tracked links',\n description: 'URL tracking and click-through analytics for shared form links',\n enabled: false,\n status: 'planned',\n category: 'analytics',\n },\n\n // -- Sharing & embedding --\n public_share_links: {\n name: 'Public share links',\n description: 'Share forms via a public URL',\n enabled: true,\n status: 'live',\n category: 'sharing',\n },\n share_node: {\n name: 'Share individual nodes',\n description: 'Share a direct link to a specific node within a form',\n // Pulled back 2026-09-30 (#3791): hides the node-menu Share (copy\n // ?node_id= link) item. Re-enable by flipping back to enabled true +\n // status 'live', and restore the per-step share paragraph in\n // apps/docs/content/docs/help/sharing.mdx.\n enabled: false,\n status: 'beta',\n wentLiveAt: '2026-07-17',\n category: 'sharing',\n },\n public_results: {\n name: 'Public results portal',\n description: 'Share a live, read-only results page with anyone via a link',\n // Ships dark (#2129): code lands ready, gated server-side (apps/api) on\n // this flag OR the FEATURE_COMPANY_ALLOWLIST.public_results company\n // allowlist below (companyHasPublicResults) for per-company dogfood ahead\n // of the global flip - same flag-or-allowlist pattern as node_camera /\n // companyHasNodeType. Flip enabled/status together for GA - the API\n // re-checks this flag on every enable/rotate/read, so flipping it on/off\n // (or editing the allowlist) takes effect immediately, no redeploy needed.\n enabled: false,\n status: 'planned',\n category: 'sharing',\n },\n embed_inline: {\n name: 'Inline embed',\n description: 'Embed forms on external websites via script tag or JavaScript API',\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-05-27',\n category: 'sharing',\n },\n embed_widget: {\n name: 'Embed widget',\n description: 'Floating button that opens a form in a modal overlay',\n enabled: false,\n status: 'planned',\n category: 'sharing',\n },\n dynamic_link: {\n name: 'Dynamic links',\n description: 'A named link that points at a form, so the target can be swapped from the dashboard without changing the embed code or printed link',\n enabled: true,\n status: 'live',\n category: 'sharing',\n wentLiveAt: '2026-08-27',\n },\n custom_domains: {\n name: 'Custom domains',\n description: 'Serve your forms on your own subdomain (forms.yourbrand.com) with vanity paths, instead of a clipform.io link',\n enabled: false,\n status: 'planned',\n category: 'sharing',\n },\n branded_qr: {\n name: 'Branded QR codes',\n description: \"Render a form's share QR in its theme color with the logo centered, instead of plain black\",\n enabled: false,\n status: 'planned',\n category: 'sharing',\n },\n email_share: {\n name: 'Add to an email',\n description: 'Copy-paste image + link snippet for pasting a Clipform into an email campaign',\n enabled: false,\n status: 'planned',\n category: 'sharing',\n },\n remove_branding: {\n name: 'Remove branding',\n description: 'Hide Clipform watermark (Pro plan)',\n enabled: true,\n status: 'live',\n category: 'sharing',\n },\n // Backfilled (#4338): the public /templates gallery (apps/marketing/src/app/templates,\n // apps/marketing/src/components/template-gallery) lets anyone browse and start\n // from a real, live Clipform template - a curated core set, plus the rest\n // (project_template_gallery_curated_core6). No enabled/status change, no wentLiveAt.\n templates_gallery: {\n name: 'Template gallery',\n description: 'Browse and start a form from a real, prebuilt template',\n enabled: true,\n status: 'live',\n category: 'sharing',\n },\n\n // -- AI --\n ai_form_generation: {\n name: 'AI form generation',\n // Corrected twice (#4338): not MCP-only (round 4 found the public\n // web AI builder). In practice this mostly means the ChatGPT/Claude\n // connector (chat_connectors) - leading with that per the user.\n description: 'Generate complete forms from a text prompt, primarily via the ChatGPT and Claude connectors (see chat_connectors); also the public web AI builder on marketing pages; no in-dashboard entry point',\n enabled: true,\n status: 'live',\n category: 'ai',\n },\n // Confirmed live by the user 2026-09-27: both the ChatGPT App Directory and\n // Claude Connectors Directory listings are live. Implementation is\n // packages/mcp-server (the same MCP server surfaced as a connector in both\n // directories - see #797 /\n // #3681). No enabled/status change\n // pending, so no wentLiveAt.\n chat_connectors: {\n name: 'ChatGPT and Claude connectors',\n description: 'Build and edit forms from ChatGPT and Claude via the Clipform connector, listed in both the ChatGPT App Directory and the Claude Connectors Directory',\n enabled: true,\n status: 'live',\n category: 'ai',\n },\n ai_tts: {\n name: 'AI text-to-speech',\n description: 'Generate voiceover audio for form prompts',\n enabled: true,\n status: 'live',\n category: 'ai',\n },\n ai_builder_chat: {\n name: 'AI builder chat',\n description: 'Chat beside the builder canvas to add, reword and branch questions on the open form',\n // Dogfood-only (#6139): invisible beta - enabled:false, never 'live'/'planned' so\n // no public surface lists it. Available to FEATURE_COMPANY_ALLOWLIST.ai_builder_chat\n // via getFeatureAccess (the builder toolbar toggle and POST /v1/ai/builder-chat).\n // Undo (#6161) and a monthly per-plan cap (#6162) land before the global flip.\n enabled: false,\n status: 'beta',\n category: 'ai',\n },\n\n // -- API --\n public_api: {\n name: 'Public API',\n description: 'REST API for form creation, node management, and response collection',\n enabled: true,\n status: 'live',\n category: 'api',\n },\n api_keys: {\n name: 'API key management',\n description: 'Self-service API key creation in the dashboard',\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-06-22',\n category: 'api',\n },\n\n // -- Integrations --\n webhooks: {\n name: 'Webhooks',\n description: 'Send response data to external URLs on form completion',\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-06-24',\n category: 'integrations',\n },\n // Per-integration lifecycle (split from the old coarse `integrations` flag so\n // each can ship independently). integration-catalog.js carries the metadata\n // and derives is_active from these. None are live yet.\n integration_stripe: {\n name: 'Stripe',\n description: 'Accept payments directly in your forms',\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-09-07',\n category: 'integrations',\n },\n // Hub-only gate (#5482): manage Stripe (connect/disconnect) from the\n // Integrations hub. NOT an `integration_*` key on purpose - integration_stripe\n // is globally live (payment node GA), so it cannot gate a hub card that is\n // internal-first. Referenced by the catalog's `hub_feature` on `stripe`.\n stripe_hub_management: {\n name: 'Stripe on the Integrations hub',\n description: 'Connect and disconnect Stripe from the Integrations hub',\n enabled: false,\n status: 'beta',\n category: 'integrations',\n },\n integration_paddle: {\n name: 'Paddle',\n description: 'Accept payments with Paddle',\n enabled: false,\n status: 'planned',\n category: 'integrations',\n },\n integration_square: {\n name: 'Square',\n description: 'Accept payments with Square',\n enabled: false,\n status: 'planned',\n category: 'integrations',\n },\n integration_calendly: {\n name: 'Calendly',\n description: 'Schedule meetings directly in your forms',\n // GA 2026-11-08 with the Booking node (#5310); the allowlist entry below\n // stays as the safety valve.\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-11-08',\n category: 'integrations',\n },\n integration_google_calendar: {\n name: 'Google Meet',\n description: 'Google Calendar scheduling with Google Meet links for the Booking node',\n enabled: false,\n status: 'planned',\n category: 'integrations',\n },\n integration_calcom: {\n name: 'Cal.com',\n description: 'Open-source scheduling platform for booking meetings',\n enabled: false,\n status: 'planned',\n category: 'integrations',\n },\n integration_docusign: {\n name: 'DocuSign',\n description: 'Collect signatures in your forms',\n enabled: false,\n status: 'planned',\n category: 'integrations',\n },\n integration_zapier: {\n name: 'Zapier',\n description: 'Connect to 5,000+ apps and automate workflows',\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-06-21',\n category: 'integrations',\n },\n integration_make: {\n name: 'Make',\n description: 'Advanced automation and integrations',\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-06-22',\n category: 'integrations',\n },\n integration_n8n: {\n name: 'n8n',\n description: 'Open-source workflow automation - trigger flows on form responses',\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-06-26',\n category: 'integrations',\n },\n integration_hubspot: {\n name: 'HubSpot',\n description: 'Sync responses to HubSpot CRM',\n enabled: false,\n status: 'planned',\n category: 'integrations',\n },\n integration_salesforce: {\n name: 'Salesforce',\n description: 'Sync responses to Salesforce CRM',\n enabled: false,\n status: 'planned',\n category: 'integrations',\n },\n integration_slack: {\n name: 'Slack',\n description: 'Post a summary of every completed response to a Slack channel',\n enabled: false,\n status: 'beta',\n category: 'integrations',\n },\n integration_klaviyo: {\n name: 'Klaviyo',\n description: \"Log a Form Completed event on the shopper's Klaviyo profile when they complete a form\",\n enabled: false,\n status: 'beta',\n category: 'integrations',\n },\n integration_kit: {\n name: 'Kit',\n description: \"Tag a subscriber in Kit when they complete a form they opened from a Kit email\",\n enabled: false,\n status: 'beta',\n category: 'integrations',\n },\n integration_shopify: {\n name: 'Shopify',\n description: 'Product recommendations from quiz results with direct checkout',\n enabled: false,\n status: 'planned',\n category: 'integrations',\n },\n integration_google_sheets: {\n name: 'Google Sheets',\n description: 'Sync form responses to a Google Sheet, one row per submission',\n enabled: false,\n status: 'beta',\n category: 'integrations',\n },\n notifications: {\n name: 'Response notifications',\n description: 'Email or webhook alerts when new responses arrive',\n enabled: false,\n status: 'planned',\n category: 'integrations',\n },\n // Intentionally undated: shipped incrementally (API import routes 2026-05-25,\n // /try paste lane #3409 2026-08-30), so it stays out of the What's New feed.\n import_google_forms: {\n name: 'Google Forms importer',\n description: 'Import forms from Google Forms into Clipform',\n enabled: true,\n status: 'live',\n category: 'integrations',\n },\n import_typeform: {\n name: 'Typeform importer',\n description: 'Import forms from Typeform into Clipform',\n enabled: true,\n status: 'live',\n category: 'integrations',\n wentLiveAt: '2026-11-12',\n announce: {\n headline: 'Import from Typeform and Tally',\n benefit: 'Paste a public Typeform or Tally link and get a Clipform you can add video to, no rebuilding.',\n },\n },\n import_tally: {\n name: 'Tally importer',\n description: 'Import forms from Tally into Clipform',\n enabled: true,\n status: 'live',\n category: 'integrations',\n wentLiveAt: '2026-11-12',\n },\n // Went live globally (#4929); gated in the dashboard via companyHasTranscriptCopy.\n transcript_copy: {\n name: 'Copy response transcripts',\n description: 'Copy a whole response transcript, or a single line, as plain text',\n enabled: true,\n status: 'live',\n category: 'responses',\n wentLiveAt: '2026-10-15',\n announce: {\n headline: 'Copy a transcript in one click',\n benefit: 'Copy a whole response transcript, or a single line, as plain text.',\n },\n },\n // Went live globally (#4920); gated in the dashboard via companyHasMediaPlayer\n // (kill switch: set enabled:false + status:'beta' - 'live' with enabled:false throws\n // at load - to fall back to the native audio/video controls).\n media_player: {\n name: 'Response media player',\n description: 'Play voice and video answers in the Responses view with playback speed, volume and seek controls',\n enabled: true,\n status: 'live',\n category: 'responses',\n wentLiveAt: '2026-10-16',\n announce: {\n headline: 'A better player for voice and video answers',\n benefit: 'Change the playback speed, adjust volume and seek through answers in Responses.',\n },\n },\n // -- Workspace --\n // Dashboard navigation, not a product capability: its own category keeps it\n // out of PRODUCT.features (#6211).\n settings_area: {\n name: 'One Settings area',\n description: 'Account, company and workspace settings in one place, each under the scope it applies to',\n enabled: true,\n status: 'live',\n category: 'workspace',\n wentLiveAt: '2026-11-21',\n announce: {\n headline: 'All your settings in one place',\n benefit: 'Account, company and workspace settings now sit together in Settings, and Esc takes you back to your forms.',\n // = DASHBOARD_SETTINGS_PAGES.workspace. index.js imports this file, so it\n // can't import the table back; test/dashboard-settings-paths.test.js pins it.\n href: 'settings/workspace',\n },\n },\n // Dashboard navigation too (#6241): the workspace category keeps it out of\n // PRODUCT.features. MCP itself is on every plan already.\n developers_page: {\n name: 'Developers page',\n description: 'Connect Claude, ChatGPT, Cursor or VS Code to Clipform, and manage API keys, webhooks and authorized apps, in one place',\n enabled: true,\n status: 'live',\n category: 'workspace',\n wentLiveAt: '2026-11-22',\n announce: {\n headline: 'Connect Clipform to Claude, ChatGPT, Cursor or VS Code',\n benefit: 'Add Clipform to your AI tool from the new Developers page, where API keys, webhooks and authorized apps now live too.',\n // = DASHBOARD_DEVELOPER_PAGES.developers, pinned by test/dashboard-settings-paths.test.js.\n href: 'developers',\n },\n },\n};\n\n/**\n * Mesh-gradient palettes for the dashboard What's new pop-up hero (#5763): three\n * stops blended as big blurred colour fields, plus the ink colour for text on\n * top. Named so an announcement can pick one (`announce.palette`); otherwise\n * `getAnnouncementPalette` (index.js) maps the feature by its step colour\n * family or its category. The dashboard never hardcodes these hexes.\n */\nexport const ANNOUNCE_PALETTES = {\n violet: { stops: ['#7C3AED', '#EC4899', '#60A5FA'], ink: '#2E1065' },\n lime: { stops: ['#84CC16', '#FACC15', '#22D3EE'], ink: '#1A2E05' },\n sky: { stops: ['#3B82F6', '#A78BFA', '#F9A8D4'], ink: '#172554' },\n peach: { stops: ['#FB923C', '#F43F5E', '#3B82F6'], ink: '#431407' },\n indigo: { stops: ['#4F46E5', '#A855F7', '#F472B6'], ink: '#1E1B4B' },\n};\n\n// `enabled` (runtime gate) and `status` (lifecycle) are two independent axes -\n// but two pairings are incoherent and almost always a dual-write slip:\n// - status 'live' with enabled:false -> shipped-but-hidden (marketing claims it, no one can use it)\n// - status 'planned' with enabled:true -> advertised as \"coming soon\" but actually exposed\n// 'beta' is intentionally free: enabled:true is a public beta, enabled:false a\n// dark beta (e.g. dynamic_link, #2552 - plumbing lands dark, exposed once the\n// share-surface rework #3104 ships). Catch the two bad pairings at module load\n// so a typo can't ship.\nfor (const [key, f] of Object.entries(FEATURES)) {\n if (f.status === 'live' && !f.enabled) {\n throw new Error(`FEATURES.${key}: status 'live' requires enabled:true (shipped features must be exposed)`);\n }\n if (f.status === 'planned' && f.enabled) {\n throw new Error(`FEATURES.${key}: status 'planned' requires enabled:false (planned features must not be exposed)`);\n }\n // wentLiveAt is the dated go-live event (see header). Only a shipped feature has\n // one, and it must be a real ISO date - a free-text slip would silently corrupt\n // the changelog sort order, so fail at load instead.\n if (f.wentLiveAt !== undefined) {\n if (f.status === 'planned') {\n throw new Error(`FEATURES.${key}: wentLiveAt set but status is 'planned' (only shipped features have a go-live date)`);\n }\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(f.wentLiveAt)) {\n throw new Error(`FEATURES.${key}: wentLiveAt must be 'YYYY-MM-DD' (got ${JSON.stringify(f.wentLiveAt)})`);\n }\n }\n // announce is the dashboard What's New copy: a malformed one would render a\n // blank row or a broken link, so fail at load.\n if (f.announce !== undefined) {\n const a = f.announce;\n if (!f.wentLiveAt) {\n throw new Error(`FEATURES.${key}: announce requires wentLiveAt (an announcement needs a go-live date)`);\n }\n for (const field of ['headline', 'benefit']) {\n if (typeof a?.[field] !== 'string' || !a[field].trim()) {\n throw new Error(`FEATURES.${key}: announce.${field} must be a non-empty string`);\n }\n if (/\\u2014/.test(a[field])) {\n throw new Error(`FEATURES.${key}: announce.${field} must not contain an em dash (use ' - ')`);\n }\n }\n if (a.palette !== undefined && !Object.prototype.hasOwnProperty.call(ANNOUNCE_PALETTES, a.palette)) {\n throw new Error(`FEATURES.${key}: announce.palette must be one of ${Object.keys(ANNOUNCE_PALETTES).join(', ')} (got ${JSON.stringify(a.palette)})`);\n }\n if (a.media !== undefined) {\n const m = a.media;\n if (!m || (m.kind !== 'image' && m.kind !== 'video')) {\n throw new Error(`FEATURES.${key}: announce.media.kind must be 'image' or 'video'`);\n }\n if (typeof m.src !== 'string' || !m.src.startsWith('/whats-new/')) {\n throw new Error(`FEATURES.${key}: announce.media.src must start with '/whats-new/'`);\n }\n // Media size rule: width/height are stored, never learned after load.\n if (!Number.isInteger(m.width) || m.width <= 0 || !Number.isInteger(m.height) || m.height <= 0) {\n throw new Error(`FEATURES.${key}: announce.media.width/height must be positive integers`);\n }\n if (m.poster !== undefined && (typeof m.poster !== 'string' || !m.poster.startsWith('/whats-new/'))) {\n throw new Error(`FEATURES.${key}: announce.media.poster must start with '/whats-new/'`);\n }\n }\n if (a.href !== undefined && (typeof a.href !== 'string' || !a.href || a.href.startsWith('/') || /^[a-z][a-z0-9+.-]*:/i.test(a.href))) {\n throw new Error(`FEATURES.${key}: announce.href must be a workspace-relative path (no leading slash or protocol)`);\n }\n }\n}\n\n/**\n * Backwards-compatible FEATURE_FLAGS object.\n * Maps the old flag names to FEATURES[key].enabled so existing dashboard code\n * keeps working without changes. Migrate consumers to FEATURES.x.enabled over time.\n */\nexport const FEATURE_FLAGS = {\n get ENABLE_BRANCHING() { return FEATURES.branching.enabled; },\n get ENABLE_CUSTOM_SCORES() { return FEATURES.custom_scores.enabled; },\n get ENABLE_TEXT_RESPONSE() { return FEATURES.text_response.enabled; },\n get ENABLE_MULTI_SELECT() { return FEATURES.multi_select.enabled; },\n get INLINE_EMBED() { return FEATURES.embed_inline.enabled; },\n get WIDGET_EMBED() { return FEATURES.embed_widget.enabled; },\n get WEBHOOKS() { return FEATURES.webhooks.enabled; },\n get INTEGRATIONS() { return Object.entries(FEATURES).some(([k, f]) => k.startsWith('integration_') && f.enabled); },\n get CUSTOM_FONTS() { return FEATURES.custom_fonts.enabled; },\n get TRACKED_LINKS() { return FEATURES.tracked_links.enabled; },\n get DYNAMIC_LINK() { return FEATURES.dynamic_link.enabled; },\n get CUSTOM_DOMAINS() { return FEATURES.custom_domains.enabled; },\n get BRANDED_QR() { return FEATURES.branded_qr.enabled; },\n get EMAIL_SHARE() { return FEATURES.email_share.enabled; },\n get SHARE_NODE() { return FEATURES.share_node.enabled; },\n get BRAND_NAME() { return FEATURES.brand_name.enabled; },\n get CSV_EXPORT() { return FEATURES.csv_export.enabled; },\n get ALLOW_RESUME() { return FEATURES.allow_resume.enabled; },\n get UTM_ANALYTICS() { return FEATURES.utm_tracking.enabled; },\n get API_KEYS() { return FEATURES.api_keys.enabled; },\n get NOTIFICATIONS() { return FEATURES.notifications.enabled; },\n get IMPORT_TYPEFORM() { return FEATURES.import_typeform.enabled; },\n get IMPORT_TALLY() { return FEATURES.import_tally.enabled; },\n get PUBLIC_RESULTS() { return FEATURES.public_results.enabled; },\n};\n\n/**\n * Per-integration limited-rollout allowlists - one entry per gated integration.\n * While an\n * integration's FEATURES flag is off, these companies get early access to test\n * it in live. Each integration switches on independently: flip its flag for\n * global GA, or allowlist a company to dogfood ahead of that. Dev + prod company\n * ids differ (separate Supabase projects).\n */\nexport const INTEGRATION_COMPANY_ALLOWLIST = {\n // Slack is built but not GA (#4141/#4154) - dogfood on the internal\n // \"Clipform Public\" company while FEATURES.integration_slack.enabled stays\n // off, so every other company sees the Coming Soon card until launch.\n integration_slack: ['00000000-0000-4000-b000-000000000001'],\n // Google Sheets is built but not GA (#848) - dogfood on the internal\n // \"Clipform Public\" company while FEATURES.integration_google_sheets.enabled\n // stays off, same as Slack above.\n integration_google_sheets: ['00000000-0000-4000-b000-000000000001'],\n // Klaviyo (#6148) ships dark: dogfood on Clipform Public while\n // FEATURES.integration_klaviyo.enabled stays off.\n integration_klaviyo: ['00000000-0000-4000-b000-000000000001'],\n // Kit (#6174) ships dark the same way: dogfood on Clipform Public while\n // FEATURES.integration_kit.enabled stays off.\n integration_kit: ['00000000-0000-4000-b000-000000000001'],\n // Calendly backs the Booking node (#5299) - dogfood on Clipform Public\n // (andy@clipform.io's company on dev + prod) alongside node_booking below.\n integration_calendly: ['00000000-0000-4000-b000-000000000001'],\n // Google Meet booking (#5308/#5309) - dogfood on Clipform Public while\n // FEATURES.integration_google_calendar stays off until Google verifies the\n // Calendar scopes (GA flip #5662).\n integration_google_calendar: ['00000000-0000-4000-b000-000000000001'],\n // integration_zapier + integration_make + integration_n8n removed - all\n // globally live (FEATURES.integration_*.enabled), so companyHasIntegration\n // short-circuits true for everyone; no allowlist needed. (n8n went live with\n // the published Clipform Trigger node, #976.)\n // integration_stripe removed - globally live (FEATURES.integration_stripe.enabled),\n // so companyHasIntegration short-circuits true for everyone; no allowlist needed\n // (payment node GA, #1438).\n};\n\n/**\n * Per-node-type limited-rollout allowlist - same pattern as\n * INTEGRATION_COMPANY_ALLOWLIST, one entry per gated node type (keyed by the\n * FEATURES key, e.g. 'node_payment'). While a node type's FEATURES flag is off,\n * these companies can build with it in live to dogfood ahead of the global flip.\n * Dev + prod company ids differ (separate Supabase projects).\n */\nexport const NODE_COMPANY_ALLOWLIST = {\n // node_payment removed - globally live (FEATURES.node_payment.enabled), so\n // companyHasNodeType short-circuits true for everyone; no allowlist needed\n // (payment node GA, #1438).\n // Camera node dogfood (#2097): build with it in live ahead of the global flip.\n // The node_type_check constraint already permits 'camera' in prod (migration\n // #2103 merged + applied 2026-07-17), so this is a pure app-config allowlist.\n node_camera: [\n '51aef9d0-b26d-4f17-bf6f-583dde728ac2', // prod - Andy's Company\n '00000000-0000-4000-b000-000000000001', // Clipform Public (system company; same id dev + prod)\n ],\n // Conditional node dogfood (#4105): build with it in live ahead of the\n // global flip. Creating a conditional node also needs the node_type_check\n // constraint widen (parked holds-migration PR) - applied on dev already,\n // prod at the next deploy.\n node_conditional: [\n '51aef9d0-b26d-4f17-bf6f-583dde728ac2', // prod - Andy's Company\n '00000000-0000-4000-b000-000000000001', // Clipform Public (system company; same id dev + prod)\n ],\n // File Upload node dogfood (#2905): the results/responses display now renders\n // uploaded files (PR #2907), so build with it in live ahead of the global flip.\n // The node_type_check constraint already permits 'file_upload' (added with the\n // camera migration), so no migration is needed - this is a pure app-config flip.\n node_file_upload: [\n '51aef9d0-b26d-4f17-bf6f-583dde728ac2', // prod - Andy's Company\n '00000000-0000-4000-b000-000000000001', // Clipform Public (system company; same id dev + prod)\n ],\n // Draw node: GA again 2026-10-26 (#5052), so this list is inert while\n // FEATURES.node_draw is enabled. Kept as the safety valve from the #2289\n // pull-back - it also carries the e2e auth user and a demo company so specs\n // and demo forms keep working if draw is ever pulled back again.\n node_draw: [\n '51aef9d0-b26d-4f17-bf6f-583dde728ac2', // prod - Andy's Company\n '00000000-0000-4000-b000-000000000001', // Clipform Public (system company; same id dev + prod)\n 'd9808c42-05ee-4830-9634-f0b1496bf484', // dev - andycsmith313@gmail.com's Company (e2e auth user; draw e2e specs create draw nodes)\n '9dcb32a1-b52f-4873-a099-ed44abd4959f', // dev - Clipform Zapier (demo company with a draw demo form)\n ],\n // Booking node dogfood (#5299): build with it in live ahead of the global\n // flip. node_type_check already permits 'booking' in prod, so this is a\n // pure app-config allowlist. Needs integration_calendly allowlisted too.\n node_booking: [\n '00000000-0000-4000-b000-000000000001', // Clipform Public (andy@clipform.io's company; same id dev + prod)\n ],\n};\n\n/**\n * General-purpose limited-rollout allowlist for a FEATURES-gated capability\n * that isn't a node type or an integration (same pattern as\n * NODE_COMPANY_ALLOWLIST / INTEGRATION_COMPANY_ALLOWLIST, keyed by the\n * FEATURES key). Dev + prod company ids differ (separate Supabase projects).\n */\nexport const FEATURE_COMPANY_ALLOWLIST = {\n // Stripe card + disconnect on the Integrations hub (#5482): internal first,\n // customers keep the \"Coming soon\" card until the launch flip.\n stripe_hub_management: [\n '51aef9d0-b26d-4f17-bf6f-583dde728ac2', // prod - Andy's Company\n '00000000-0000-4000-b000-000000000001', // Clipform Public (system company; same id dev + prod)\n ],\n // Public results portal dogfood (#2129): build with it in live ahead of the\n // global flip. Server-side gate only (apps/api) - see companyHasPublicResults.\n public_results: [\n '51aef9d0-b26d-4f17-bf6f-583dde728ac2', // prod - Andy's Company\n '00000000-0000-4000-b000-000000000001', // Clipform Public (system company; same id dev + prod)\n ],\n // Custom domains dogfood (#3443): build with it live ahead of the global\n // flip. Server-side gate only (apps/api) - see companyHasCustomDomains.\n custom_domains: [\n '51aef9d0-b26d-4f17-bf6f-583dde728ac2', // prod - Andy's Company\n '00000000-0000-4000-b000-000000000001', // Clipform Public (system company; same id dev + prod)\n ],\n // Agreement documents (#2760) went live globally (#4521); the allowlist is\n // intentionally empty and kept only so companyHasConsentDocuments stays valid.\n consent_documents: [],\n // AI answer summaries (#4678): dogfood-only until the benchmark + ZDR are\n // confirmed. Server-side gate only (apps/api) - see companyHasResponseSummary.\n response_summary: [\n '51aef9d0-b26d-4f17-bf6f-583dde728ac2', // prod - Andy's Company\n ],\n // Multi-select choice questions (#151): dogfood-only. Gate lives in\n // companyHasMultiSelect (builder control, API writes, every read that decides\n // behaviour from a stored selection_mode). Clipform Public holds Playground\n // and the templates (anonymous callers have their own companies since #4010):\n // a multi-select template previews as multi-select but copies as single into\n // a company off this list, until the launch flip (#5346).\n multi_select: [\n '51aef9d0-b26d-4f17-bf6f-583dde728ac2', // prod - Andy's Company\n '00000000-0000-4000-b000-000000000001', // Clipform Public (system company; same id dev + prod)\n ],\n // Custom variables (#5242): dogfood-only until the launch flip. Gate lives in\n // companyHasVariables (variables API writes now; viewer and builder later).\n variables: [\n '51aef9d0-b26d-4f17-bf6f-583dde728ac2', // prod - Andy's Company\n '00000000-0000-4000-b000-000000000001', // Clipform Public (system company; same id dev + prod)\n 'd9808c42-05ee-4830-9634-f0b1496bf484', // dev - andycsmith313@gmail.com's Company (e2e auth user)\n ],\n // Response trash (#2862): dogfood-only until the launch flip. Gate lives in\n // companyHasResponseTrash (Responses tab UI + the trash/restore POST routes and\n // the ?trashed reads). Clipform Public holds the dev dogfood logins.\n response_trash: [\n '51aef9d0-b26d-4f17-bf6f-583dde728ac2', // prod - Andy's Company\n '00000000-0000-4000-b000-000000000001', // Clipform Public (system company; same id dev + prod)\n ],\n // AI builder chat (#6139): dogfood-only until undo (#6161) and the per-plan cap\n // (#6162) land. Gate: getFeatureAccess('ai_builder_chat') in the builder toolbar\n // and POST /v1/ai/builder-chat. Clipform Public holds the dev dogfood logins;\n // the e2e auth user's company is Andy's dev login (and the e2e screenshots).\n ai_builder_chat: [\n '51aef9d0-b26d-4f17-bf6f-583dde728ac2', // prod - Andy's Company\n '00000000-0000-4000-b000-000000000001', // Clipform Public (system company; same id dev + prod)\n 'd9808c42-05ee-4830-9634-f0b1496bf484', // dev - andycsmith313@gmail.com's Company (e2e auth user)\n ],\n // Staged video upload (#6197): dogfood-only until the media worker host runs (#5980).\n // Gate: getFeatureAccess('staged_video_upload') in the API's upload handshake and the\n // dashboard's on-device compression. Clipform Public holds the dev dogfood logins;\n // the e2e auth user's company runs the dev e2e upload.\n staged_video_upload: [\n '00000000-0000-4000-b000-000000000001', // Clipform Public (system company; same id dev + prod)\n 'd9808c42-05ee-4830-9634-f0b1496bf484', // dev - e2e auth user's company\n ],\n // Template walkthrough (#6269): only the outbound templates can carry notes, and they\n // live in Clipform Public. Gate: getFeatureAccess('template_walkthrough') in the API's\n // guide writes and the MCP's clipform_set_node_guide registration.\n template_walkthrough: [\n '00000000-0000-4000-b000-000000000001', // Clipform Public (system company; same id dev + prod)\n ],\n // Copy response transcripts (#4890) went live globally (#4929); the allowlist is\n // intentionally empty and kept only so companyHasTranscriptCopy stays valid.\n transcript_copy: [],\n // Response media player (#4920) went live globally; the allowlist is\n // intentionally empty and kept only so companyHasMediaPlayer stays valid.\n media_player: [],\n};\n\n/**\n * Shared resolver for the flag-or-allowlist rollout pattern. Returns WHY a\n * capability is available: 'public' once its global FEATURES flag is on,\n * 'internal' while it is off but the company sits on the capability's\n * limited-rollout allowlist, else 'none'. Single source of truth for every\n * companyHas* helper and for the dashboard's \"Internal\" badge (#5132).\n */\nfunction resolveFeatureAccess(enabled, companyId, allowlist) {\n if (enabled) return 'public';\n return !!companyId && (allowlist || []).includes(companyId) ? 'internal' : 'none';\n}\n\n/**\n * Company ids allowlisted for a FEATURES-style key, routed by key prefix\n * (integration_* / node_* / else the feature allowlist). Empty when none.\n */\nexport function getFeatureAllowlist(featureKey) {\n if (featureKey.startsWith('integration_')) return INTEGRATION_COMPANY_ALLOWLIST[featureKey] || [];\n if (featureKey.startsWith('node_')) return NODE_COMPANY_ALLOWLIST[featureKey] || [];\n return FEATURE_COMPANY_ALLOWLIST[featureKey] || [];\n}\n\n/**\n * Access level of a FEATURES key for a company: 'public' | 'internal' | 'none'.\n * The allowlist is chosen by key prefix (integration_* / node_* / else the\n * feature allowlist).\n */\nexport function getFeatureAccess(featureKey, companyId) {\n return resolveFeatureAccess(!!FEATURES[featureKey]?.enabled, companyId, getFeatureAllowlist(featureKey));\n}\n\nconst ACCESS_RANK = { none: 0, internal: 1, public: 2 };\n\n/**\n * Combine access levels of a composite gate (e.g. a control shown when either\n * of two features is available): public > internal > none.\n */\nexport function combineFeatureAccess(...accesses) {\n return accesses.reduce((best, a) => (ACCESS_RANK[a] > ACCESS_RANK[best] ? a : best), 'none');\n}\n\nfunction gatedByFlagOrAllowlist(enabled, companyId, allowlist) {\n return resolveFeatureAccess(enabled, companyId, allowlist) !== 'none';\n}\n\n/**\n * Whether a company can use an integration: true once its FEATURES flag is\n * globally live, or while the company sits on that integration's allowlist\n * above. Keyed by the FEATURES key (e.g. 'integration_zapier').\n */\nexport function companyHasIntegration(companyId, integrationKey) {\n return gatedByFlagOrAllowlist(\n !!FEATURES[integrationKey]?.enabled,\n companyId,\n INTEGRATION_COMPANY_ALLOWLIST[integrationKey],\n );\n}\n\n/**\n * Whether a company can see the Integrations surface at all: true if ANY\n * integration is available to it (globally live or allowlisted). Gates the\n * Integrations nav tab - the bare\n * FEATURE_FLAGS.INTEGRATIONS getter ignores the per-integration allowlists, so\n * allowlisted companies would never see the tab while every flag is off.\n */\nexport function companyHasAnyIntegration(companyId) {\n return Object.keys(FEATURES)\n .filter((k) => k.startsWith('integration_'))\n .some((k) => companyHasIntegration(companyId, k));\n}\n\n/**\n * Whether a company can build with a node type: true once its FEATURES flag is\n * globally live, or while the company sits on that node type's allowlist above.\n * Takes the node type key (e.g. 'payment'); maps to the FEATURES key\n * `node_<type>`, the same mapping node-types.js uses to derive is_active.\n */\nexport function companyHasNodeType(companyId, nodeType) {\n const featureKey = `node_${nodeType}`;\n return gatedByFlagOrAllowlist(\n !!FEATURES[featureKey]?.enabled,\n companyId,\n NODE_COMPANY_ALLOWLIST[featureKey],\n );\n}\n\n/**\n * Whether a company can turn on the public results portal: true once the\n * FEATURES flag is globally live, or while the company sits on the\n * public_results allowlist above. Server-side gate only - see apps/api's\n * update-form / rotate-results-share / get-public-results routes.\n */\nexport function companyHasPublicResults(companyId) {\n return gatedByFlagOrAllowlist(\n !!FEATURES.public_results?.enabled,\n companyId,\n FEATURE_COMPANY_ALLOWLIST.public_results,\n );\n}\n\n/**\n * Whether a company can use custom domains: true once the FEATURES flag is\n * globally live, or while the company sits on the custom_domains allowlist\n * above. Server-side gate only - see apps/api's domains.ts customDomainsGate.\n */\nexport function companyHasCustomDomains(companyId) {\n return gatedByFlagOrAllowlist(\n !!FEATURES.custom_domains?.enabled,\n companyId,\n FEATURE_COMPANY_ALLOWLIST.custom_domains,\n );\n}\n\n/**\n * Whether a company can attach documents to consent agreements: true once the\n * FEATURES flag is globally live, or while the company sits on the\n * consent_documents allowlist above. Gates the builder's document-attach UI\n * (#2760) - see apps/dashboard ContactNode.\n */\nexport function companyHasConsentDocuments(companyId) {\n return gatedByFlagOrAllowlist(\n !!FEATURES.consent_documents?.enabled,\n companyId,\n FEATURE_COMPANY_ALLOWLIST.consent_documents,\n );\n}\n\n/**\n * Whether a company gets AI summaries of open answers (#4678): true once a\n * FEATURES.response_summary flag is globally live, or while the company sits on\n * the response_summary allowlist above. Server-side gate only - see apps/api's\n * answer-summary.ts.\n */\nexport function companyHasResponseSummary(companyId) {\n return gatedByFlagOrAllowlist(\n !!FEATURES.response_summary?.enabled,\n companyId,\n FEATURE_COMPANY_ALLOWLIST.response_summary,\n );\n}\n\n/**\n * Whether a company can use multi-select choice questions (#151): true once\n * FEATURES.multi_select is globally live, or while the company sits on the\n * multi_select allowlist above. A non-allowlisted company's stored\n * selection_mode 'multiple' must behave as single everywhere (see\n * gateSelectionMode in logic-types.js).\n */\nexport function companyHasMultiSelect(companyId) {\n return gatedByFlagOrAllowlist(\n !!FEATURES.multi_select?.enabled,\n companyId,\n FEATURE_COMPANY_ALLOWLIST.multi_select,\n );\n}\n\n/**\n * Whether a company can move responses to the trash and restore them (#2862):\n * true once FEATURES.response_trash is globally live, or while the company sits\n * on the response_trash allowlist above.\n */\nexport function companyHasResponseTrash(companyId) {\n return gatedByFlagOrAllowlist(\n !!FEATURES.response_trash?.enabled,\n companyId,\n FEATURE_COMPANY_ALLOWLIST.response_trash,\n );\n}\n\n/**\n * Whether a company gets the copy-transcript buttons on response transcripts\n * (#4890): true once FEATURES.transcript_copy is globally live, or while the\n * company sits on the transcript_copy allowlist above.\n */\nexport function companyHasTranscriptCopy(companyId) {\n return gatedByFlagOrAllowlist(\n !!FEATURES.transcript_copy?.enabled,\n companyId,\n FEATURE_COMPANY_ALLOWLIST.transcript_copy,\n );\n}\n\n/**\n * Whether a company gets the Video.js response media player (#4920) for audio\n * and video answers instead of the native controls: true once\n * FEATURES.media_player is globally live (flag off = kill switch), or while the\n * company sits on the media_player allowlist above.\n */\nexport function companyHasMediaPlayer(companyId) {\n return gatedByFlagOrAllowlist(\n !!FEATURES.media_player?.enabled,\n companyId,\n FEATURE_COMPANY_ALLOWLIST.media_player,\n );\n}\n\n/**\n * Whether a company can use custom variables (#5242): true once\n * FEATURES.variables is globally live, or while the company sits on the\n * variables allowlist above.\n */\nexport function companyHasVariables(companyId) {\n return gatedByFlagOrAllowlist(\n !!FEATURES.variables?.enabled,\n companyId,\n FEATURE_COMPANY_ALLOWLIST.variables,\n );\n}\n\nexport function getLiveFeatures() {\n return Object.values(FEATURES).filter(f => f.status === 'live');\n}\n\nexport function getPlannedFeatures() {\n return Object.values(FEATURES).filter(f => f.status === 'planned');\n}\n\nexport function getFeaturesByCategory(category) {\n return Object.values(FEATURES).filter(f => f.category === category);\n}\n\n/**\n * The What's New timeline: live features with a known go-live date, newest first.\n * The single machine-readable source for the user-facing changelog and the SEO/GTM\n * \"what shipped recently\" signal. Returns [key, feature] entries so consumers can\n * derive links/anchors from the key. Features live since the registry baseline have\n * no wentLiveAt and are intentionally excluded - a dated changelog never invents a date.\n */\nexport function getWhatsNew() {\n return Object.entries(FEATURES)\n .filter(([, f]) => f.status === 'live' && f.wentLiveAt)\n .sort(([, a], [, b]) => b.wentLiveAt.localeCompare(a.wentLiveAt));\n}\n\n/** Most launches the dashboard What's new pop-up carries (a carousel, one per slide). */\nexport const WHATS_NEW_POPUP_LIMIT = 5;\n\n/** Live features that carry dashboard announce copy, newest first, as [key, feature]. */\nexport function getAnnouncements() {\n return getWhatsNew().filter(([, f]) => f.announce);\n}\n\nfunction daysBetween(fromIso, now) {\n const from = Date.parse(`${fromIso}T00:00:00Z`);\n return Math.floor((now.getTime() - from) / 86400000);\n}\n\n/**\n * Announcements a user has not seen yet: within the window, live on or after\n * their signup date (new users never see launches from before they joined), and\n * not in their seen keys. Keys, not a timestamp: deploys are batched, so a\n * cursor would swallow a feature merged before the last look and deployed after.\n * Newest first.\n */\nexport function getUnreadAnnouncements({ seen = [], signedUpAt, now = new Date(), windowDays = 60 } = {}) {\n const signup = signedUpAt ? String(signedUpAt).slice(0, 10) : null;\n return getAnnouncements().filter(([key, f]) => {\n if (seen.includes(key)) return false;\n if (signup && f.wentLiveAt < signup) return false;\n const age = daysBetween(f.wentLiveAt, now);\n return age >= 0 && age <= windowDays;\n });\n}\n\n/** Every announcement still inside the window (the pop-up's recent mode), newest first. */\nexport function getRecentAnnouncements({ now = new Date(), windowDays = 60 } = {}) {\n return getAnnouncements().filter(([, f]) => {\n const age = daysBetween(f.wentLiveAt, now);\n return age >= 0 && age <= windowDays;\n });\n}\n\n/** True for a live feature that went live within `days` (drives the \"New\" pill). */\nexport function isNewFeature(key, now = new Date(), days = 30) {\n const f = FEATURES[key];\n if (!f || f.status !== 'live' || !f.wentLiveAt) return false;\n const age = daysBetween(f.wentLiveAt, now);\n return age >= 0 && age <= days;\n}\n","// @vid-master/config/help-links\n// Single source of truth for every in-product \"Learn more\" deep-link (#394).\n// In-product copy stays a short, actionable summary; the full explanation\n// lives in docs and we link to it, so the two can't drift.\n//\n// HELP_TOPICS is pure data (docs path + anchor, no base URL) so the docs\n// link-check script (apps/docs/scripts/check-help-links.mjs) can verify every\n// anchor resolves to a real heading without touching env. Consumers use\n// HELP_LINKS from the package root, which composes full URLs off\n// BUSINESS.urls.docs.\n\n/**\n * Keyed by concept. `path` is relative to the docs site root (which already\n * includes the /docs basePath); `anchor` must match a heading slug in the\n * target page (custom [#anchor] syntax or the auto-generated slug).\n */\nexport const HELP_TOPICS = {\n goLive: { path: '/help/sharing', anchor: 'go-live' },\n cantGoLive: { path: '/help/sharing', anchor: 'cant-go-live' },\n liveAndDraft: { path: '/help/managing-forms', anchor: 'live-and-draft' },\n publishingChanges: { path: '/help/managing-forms', anchor: 'publishing-changes' },\n embedding: { path: '/help/embed', anchor: null },\n embedTracking: { path: '/help/embed', anchor: 'track-form-events' },\n emailShare: { path: '/help/sharing', anchor: 'share-by-email' },\n publicResults: { path: '/help/public-results', anchor: null },\n trash: { path: '/help/managing-forms', anchor: 'trash' },\n customDomains: { path: '/help/domains', anchor: null },\n // Settings > Profile > Delete account (#6314): the 30-day processing time\n // and \"cancel Pro first\" live here, not on the card.\n deleteAccount: { path: '/help/account', anchor: 'delete-your-account' },\n customPath: { path: '/help/links', anchor: 'custom-path-on-your-domain' },\n // Per-node-type deep-links into help/node-types.mdx (#3963). Keyed\n // `node_<nodeType>` so nodeHelpLink() (index.js) can look one up straight\n // from a node's type id.\n node_choice: { path: '/help/node-types', anchor: 'choice' },\n node_open: { path: '/help/node-types', anchor: 'open-ended' },\n node_camera: { path: '/help/node-types', anchor: 'camera' },\n node_draw: { path: '/help/node-types', anchor: 'drawing' },\n node_details: { path: '/help/node-types', anchor: 'details' },\n node_button: { path: '/help/node-types', anchor: 'button' },\n node_end_screen: { path: '/help/node-types', anchor: 'end-screen' },\n node_redirect: { path: '/help/node-types', anchor: 'redirect' },\n node_file_download: { path: '/help/node-types', anchor: 'file-download' },\n node_booking: { path: '/help/node-types', anchor: 'booking' },\n node_payment: { path: '/help/node-types', anchor: 'payment' },\n // Keyed by FEATURES key so a non-node launch announcement (What's new, #3705) gets a\n // \"Learn more\" action: useWhatsNew falls back to HELP_LINKS[featureKey].\n import_typeform: { path: '/help/import-typeform', anchor: null },\n // The MCP setup guide (#6241): the Developers AI tab's one docs link. Claude\n // and ChatGPT's steps moved onto the tab itself (#6300), so their per-client\n // anchors went.\n mcp: { path: '/api/mcp', anchor: null },\n};\n\n/** Compose full HELP_LINKS URLs from a docs base URL (no trailing slash). */\nexport function buildHelpLinks(docsBaseUrl) {\n const links = {};\n for (const [key, { path, anchor }] of Object.entries(HELP_TOPICS)) {\n links[key] = `${docsBaseUrl}${path}${anchor ? `#${anchor}` : ''}`;\n }\n return links;\n}\n","// Built-in diagram presets for the draw node (#1828, #5051, #5263, #5331). A preset is a static\n// image shipped with the viewer and referenced BY NAME in node config\n// (`config.diagram.preset`), never a media asset - nothing is stored per workspace.\n// Files live in apps/viewer/public/viewer-static/draw-presets (the `viewer-static`\n// prefix is the apex-exclusion path: a root viewer path would 308 to www on clipform.io).\n\n/** Picker section order. A group with no presets renders nothing. */\nexport const DRAW_PRESET_GROUPS = [\n { id: 'body', label: 'Body' },\n { id: 'vehicle', label: 'Vehicle' },\n { id: 'animal', label: 'Animal' },\n];\n\n/** Public URL folder (relative to a viewer origin) the preset files are served from. */\nexport const DRAW_PRESET_PATH_PREFIX = '/viewer-static/draw-presets';\n\nexport const DRAW_PRESETS = [\n { id: 'body-front', label: 'Body diagram - front', shortLabel: 'Front', file: 'body-front.png', group: 'body' },\n { id: 'body-back', label: 'Body diagram - back', shortLabel: 'Back', file: 'body-back.png', group: 'body' },\n { id: 'hands-palms', label: 'Hands diagram - palms', shortLabel: 'Palms', file: 'hands-palms.png', group: 'body' },\n { id: 'hands-backs', label: 'Hands diagram - backs', shortLabel: 'Backs of hands', file: 'hands-backs.png', group: 'body' },\n { id: 'feet-soles', label: 'Feet diagram - soles', shortLabel: 'Soles', file: 'feet-soles.png', group: 'body' },\n { id: 'face-profile', label: 'Face diagram - profile', shortLabel: 'Face', file: 'face-profile.png', group: 'body' },\n { id: 'vehicle-sides', label: 'Vehicle diagram - sides', shortLabel: 'Sides', file: 'vehicle-sides.png', group: 'vehicle' },\n { id: 'vehicle-top', label: 'Vehicle diagram - top and ends', shortLabel: 'Top and ends', file: 'vehicle-top.png', group: 'vehicle' },\n { id: 'dog-sides', label: 'Dog diagram - sides', shortLabel: 'Dog', file: 'dog-sides.png', group: 'animal' },\n { id: 'cat-sides', label: 'Cat diagram - sides', shortLabel: 'Cat', file: 'cat-sides.png', group: 'animal' },\n];\n\nexport const DRAW_PRESET_IDS = DRAW_PRESETS.map((p) => p.id);\n\n/** The catalog entry for a preset id, or undefined for an absent/unknown id. */\nexport function getDrawPreset(id) {\n return typeof id === 'string' ? DRAW_PRESETS.find((p) => p.id === id) : undefined;\n}\n\n/** Relative URL of a preset image (`/viewer-static/draw-presets/<file>`), or null for an unknown id. */\nexport function drawPresetPath(id) {\n const preset = getDrawPreset(id);\n return preset ? `${DRAW_PRESET_PATH_PREFIX}/${preset.file}` : null;\n}\n","// @vid-master/config/logic-types\n// Canonical shape for node branching logic — the VideoAsk-pattern \"actions\" graph\n// stored in node_logic.actions (jsonb). Single source of truth shared by:\n// - apps/viewer (evaluates actions to pick the next node)\n// - apps/api (writes + validates actions)\n// - apps/dashboard (builder edges <-> actions)\n//\n// The types themselves live in logic-types.d.ts. This file exports the runtime\n// constant sets used for validation. The grammar is intentionally small today\n// (one action, one operator); richer branching extends these arrays without a\n// DB migration or API signature change.\n\n/** Action verbs a logic entry can perform. */\nexport const LOGIC_ACTION_TYPES = ['jump'];\n\n/**\n * Condition operators. 'is' is the original choice/binary equality op.\n * 'eq'/'ne'/'gt'/'gte'/'lt'/'lte' are the numeric comparison ops added for\n * the conditional node (#4105) - a branch condition compares a `variable`\n * var against a `constant` var.\n */\nexport const LOGIC_CONDITION_OPS = ['is', 'eq', 'ne', 'gt', 'gte', 'lt', 'lte'];\n\n/**\n * Variable types a condition can reference. 'variable' (#4105) references a\n * built-in routable variable (see ROUTABLE_VARIABLES, e.g. the generic\n * \"score\" number); 'constant' is a literal comparison value.\n */\nexport const LOGIC_VAR_TYPES = ['node', 'option', 'variable', 'constant'];\n\n/** Jump target types. */\nexport const LOGIC_TARGET_TYPES = ['node', 'end_screen', 'redirect', 'link_list'];\n\n/**\n * Operand types (from LOGIC_VAR_TYPES) whose `value` is an entity id that\n * must be REMAPPED when a form is cloned (save_form) - as opposed to\n * 'constant', a literal comparison value with no reference to remap. Single\n * source for the clone path's SQL (`remap_ids_in_actions`, extended for\n * `variable` in `supabase/migrations/20260922030000_save_form_copy_variables.sql`)\n * so a future id-bearing operand type added to LOGIC_VAR_TYPES fails the\n * config<->SQL drift guard until the clone path covers it too (#4192).\n */\nexport const LOGIC_REMAPPABLE_VAR_TYPES = ['node', 'option', 'variable'];\n\n/**\n * The static built-in routable variables (#4105 phase 1 of the #4104\n * variables engine): the generic cumulative number derived from\n * node_options.score -> ScoreState.cumulativeScore. A RESERVED key - never\n * stored as a form_variables row (no id), resolved specially by every\n * consumer (viewer, config, api). Every other routable variable (category\n * today, custom/text later) is a row in the form's own `form_variables`\n * table, identified by its stable `id` - see getFormVariableIds.\n *\n * V1 routes on a plain number vs a constant, so `max_score` (the score's\n * denominator) is NOT a routable variable (#4258) - it wasn't a variable in\n * its own right, just the \"out of\" facet of `score`, and the grammar can't\n * compare a variable against another variable anyway. Quiz score DISPLAY\n * (`maxPossibleScore`, EndScreen \"X out of Y\") is a separate concern and\n * keeps its denominator. If per-variable ceilings or percentage routing land,\n * model the operand as `{ ref, aggregate }` rather than re-adding `max_*`\n * twins (see #4252 discussion).\n */\nexport const ROUTABLE_VARIABLES = ['score'];\n\n/**\n * A form's full set of valid `variable` operand values (#4173, revised\n * stable-id variable registry): the static built-ins (ROUTABLE_VARIABLES)\n * UNION every one of the form's own `form_variables` row ids. Unlike the\n * superseded name-based `getFormRoutableVariables`, this does NOT look at\n * node_options.scores directly - category identity now lives in the\n * form_variables table (backfilled by migration 20260922020000, kept current\n * by the API on category authoring), so a `variable` operand is always\n * either a reserved built-in key or a form_variables.id - never a mutable\n * display name.\n *\n * @param {Array<{ id?: string }>} formVariables - the form's form_variables\n * rows (or the RPC's `variables` array - same {id,...} shape).\n * @returns {string[]} Built-ins first (ROUTABLE_VARIABLES order), then\n * variable ids in the order given.\n */\nexport function getFormVariableIds(formVariables) {\n const ids = (formVariables || [])\n .map((v) => v?.id)\n .filter((id) => typeof id === 'string' && id.length > 0);\n return [...ROUTABLE_VARIABLES, ...ids];\n}\n\n// ── Active-graph semantics ───────────────────────────────────────────────────\n// Toggling branching never deletes node_logic - it changes how the SAME actions\n// are interpreted. A per-option (option-var) edge is live only when its source\n// is a choice/binary node with branching enabled; otherwise it is \"parked\" and\n// the node routes via its node-var/default edge. These helpers are the single\n// source of truth for that rule, so every consumer that walks the logic graph -\n// the publish gate, viewer routing, node ordering and builder validation - reads\n// the identical active graph. (#1021 / #704)\n\n/**\n * Whether per-option (branch) edges are live for a node.\n *\n * Branching is OPT-IN: a choice/binary node routes per-option only when it\n * explicitly sets enable_branching:true. Unset / false -> off (the node routes\n * via its node-var/default edge). This is the single source the publish gate,\n * viewer routing, node ordering and builder validation all derive from, so they\n * read the identical active graph; off-by-default holds even if a brand-new\n * node's config isn't persisted yet. Non-choice nodes always route their edges.\n */\nexport function isBranchingActive(node) {\n if (!node) return true;\n // A multi-select choice has ONE route out (the node-level edge): per-option\n // routes stay stored but paused until the node is switched back to single.\n if (isMultiSelectChoice(node)) return false;\n return node.type === 'choice' || node.type === 'binary'\n ? node.config?.choice?.enable_branching === true\n : true;\n}\n\n/** True for a choice node set to pick more than one option (config.selection_mode). */\nexport function isMultiSelectChoice(node) {\n return node?.type === 'choice' && node.config?.selection_mode === 'multiple';\n}\n\n/**\n * The multi-select rollout gate (#151). When the company isn't allowed\n * multi-select (companyHasMultiSelect), a stored selection_mode 'multiple' must\n * behave as single everywhere: returns the config with selection_mode forced to\n * 'single'. Pure - never mutates the input, and the stored value is never\n * rewritten in the DB on read. Same reference when nothing changes.\n */\nexport function gateSelectionMode(config, allowed) {\n if (allowed || !config || config.selection_mode !== 'multiple') return config;\n return { ...config, selection_mode: 'single' };\n}\n\n/** gateSelectionMode applied to a node's `config` (same node reference when unchanged). */\nexport function gateNodeSelectionMode(node, allowed) {\n if (!node || allowed || node.config?.selection_mode !== 'multiple') return node;\n return { ...node, config: gateSelectionMode(node.config, allowed) };\n}\n\n/** gateNodeSelectionMode over a list (same array when nothing changes). */\nexport function gateNodesSelectionMode(nodes, allowed) {\n if (allowed || !Array.isArray(nodes)) return nodes;\n return nodes.some(n => n?.config?.selection_mode === 'multiple')\n ? nodes.map(n => gateNodeSelectionMode(n, allowed))\n : nodes;\n}\n\n/**\n * Whether a choice node's answer key (per-option scores / correct marks) counts.\n * Answer keys are single-select only: on a multi-select node the stored scores\n * stay put but are paused, so scoring, feedback, correctness and the publish\n * gate all ignore them until the node is switched back to single.\n */\nexport function isAnswerKeyActive(node) {\n return !isMultiSelectChoice(node);\n}\n\n/**\n * Whether a choice option is marked as a correct answer (#5726). Several options\n * may be correct. Reads `is_correct`; the `score === 1` fallback fires only on\n * JSON with no `is_correct` key (an old cached payload or a deploy-order window)\n * and goes away once every reader ships.\n */\nexport function isCorrectOption(option) {\n if (!option) return false;\n return option.is_correct ?? option.score === 1;\n}\n\n/** True if `action` routes per-option (its condition references an option var). */\nexport function isOptionEdge(action) {\n return !!action?.condition?.vars?.some(v => v.type === 'option');\n}\n\n/** True if `action` is the node-level (node-var, no option var) route out. */\nexport function isNodeLevelAction(action, nodeId) {\n const vars = action?.condition?.vars;\n if (!vars || vars.some(v => v.type === 'option')) return false;\n // With a nodeId, only a node-var naming THAT node counts (what the viewer's\n // buildLogicMap keys on); without, any node-var does.\n return vars.some(v => v.type === 'node' && (nodeId === undefined || v.value === nodeId));\n}\n\n/**\n * Replace a choice/binary node's live (node-level) route with `nextActions`\n * while KEEPING its parked per-option actions (branching off, or the node is\n * multi-select) - the single-path writers (header connect, set_logic) must never\n * wipe routes that return on switch-back. Scoped strictly to parked edges: a\n * live option edge (e.g. a legacy button option) is replaced like any other.\n * Optional `valid` ({ optionIds, nodeIds }, arrays or Sets) drops parked edges\n * whose option or jump target no longer exists: the logic write validates every\n * action's references, so one stale parked edge would otherwise 400 the whole\n * write. (#151)\n */\nexport function replaceNodeLevelActions(node, existingActions, nextActions, valid) {\n const parked = (Array.isArray(existingActions) ? existingActions : []).filter(a => {\n if (!isInactiveOptionEdge(node, a)) return false;\n return !hasStaleRef(a, valid);\n });\n return [...parked, ...nextActions];\n}\n\nconst hasId = (set, v) => (set instanceof Set ? set.has(v) : set.includes(v));\n\n/**\n * True if `action` references an option or node missing from `valid`\n * ({ optionIds?, nodeIds? }, arrays or Sets). A check is skipped when its set\n * is not given. Same references actionReferenceErrors checks (any jump-target\n * type, the top-level option anchor, and every node/option condition var).\n */\nfunction hasStaleRef(action, valid) {\n if (valid?.optionIds) {\n if (typeof action.option_id === 'string' && !hasId(valid.optionIds, action.option_id)) return true;\n for (const v of action.condition?.vars || []) {\n if (v.type === 'option' && typeof v.value === 'string' && !hasId(valid.optionIds, v.value)) return true;\n }\n }\n if (valid?.nodeIds) {\n const target = action.details?.to?.value;\n if (typeof target === 'string' && !hasId(valid.nodeIds, target)) return true;\n for (const v of action.condition?.vars || []) {\n if (v.type === 'node' && typeof v.value === 'string' && !hasId(valid.nodeIds, v.value)) return true;\n }\n }\n return false;\n}\n\n/**\n * Drop actions that reference an option or node that no longer exists.\n * `valid` is { optionIds?, nodeIds? } (arrays or Sets); a check is skipped when\n * its set is not given. Returns the SAME array reference when nothing is\n * dropped, so callers can detect a change with `!==`. Used by the API's\n * update-node (options removed) and the builder's choice-node logic writes:\n * the logic write validates every action's references, so one stale ref would\n * otherwise 400 the whole row. (#5345)\n */\nexport function dropStaleRefs(actions, valid) {\n if (!Array.isArray(actions)) return actions;\n const kept = actions.filter(a => !hasStaleRef(a, valid));\n return kept.length === actions.length ? actions : kept;\n}\n\n/**\n * Ensure a node keeps one route out when per-option routing stops being live\n * (branching switched off, or the node switched to multi-select). If the node\n * has per-option actions but no node-level action, append a node-level jump\n * to their target (the single shared target, else the first). Never deletes or\n * rewrites an existing action - per-option rows stay stored, parked. Returns\n * the SAME array reference when nothing needed adding. Shared by the builder\n * branching toggle / Single-Multiple switch and the API's update-node. (#151)\n */\nexport function ensureNodeVarFallback(actions, nodeId) {\n const existing = Array.isArray(actions) ? actions : [];\n if (existing.some(a => isNodeLevelAction(a, nodeId))) return actions;\n const targets = existing.filter(isOptionEdge).map(a => a.details?.to?.value).filter(Boolean);\n if (targets.length === 0) return actions;\n const uniq = Array.from(new Set(targets));\n const fallbackTarget = uniq.length === 1 ? uniq[0] : targets[0];\n return [\n ...existing,\n {\n action: 'jump',\n details: { to: { type: 'node', value: fallbackTarget } },\n condition: { op: 'is', vars: [{ type: 'node', value: nodeId }] },\n },\n ];\n}\n\n/**\n * True if `action` is a parked option edge on `node` - a per-option edge whose\n * source node has branching off. Such edges are excluded from the active graph.\n */\nexport function isInactiveOptionEdge(node, action) {\n return isOptionEdge(action) && !isBranchingActive(node);\n}\n\n// ── Reference integrity ──────────────────────────────────────────────────────\n// \"Every jump target / node-var / option-var must point to something that exists\n// in the form.\" Single source of the rule + message vocabulary, shared by the\n// write-time gate (set-node-logic) and the publish-time validator\n// (graph-validation's dangling_target / stale_option_ref / self_loop apply the\n// same rule at reachable-graph scope). Keeps the API 400 and the publish error\n// speaking the same language. (#1058 / #1270 / #1406)\n\n/**\n * Reference-integrity errors for a single logic action.\n *\n * @param {object} action - a node_logic action ({ details.to.value, condition.vars })\n * @param {Set<string>} nodeIds - all node ids in the form\n * @param {Set<string>} optionIds - option ids on the action's node\n * @param {string} [sourceNodeId] - the node this action lives on. When given, a\n * jump target that equals this node's own id is flagged as `self_loop` instead\n * of `dangling_target` (the target does exist - it's the node itself). Optional\n * for backward compatibility; existing 3-arg callers are unaffected.\n * @param {string[]} [routableVariables] - the set of valid `variable` operand\n * values for this form (see getFormVariableIds): built-in keys UNION the\n * form's own form_variables row ids. Defaults to the static built-ins\n * (ROUTABLE_VARIABLES) for backward compatibility with existing 3/4-arg\n * callers.\n * @returns {Array<{ kind: 'dangling_target' | 'stale_option_ref' | 'self_loop' | 'unresolved_variable', value: string, reason: string }>}\n * one entry per ref that doesn't resolve; [] when all refs exist.\n */\nexport function actionReferenceErrors(action, nodeIds, optionIds, sourceNodeId, routableVariables = ROUTABLE_VARIABLES) {\n const errors = [];\n\n const to = action?.details?.to?.value;\n if (typeof to === 'string') {\n if (sourceNodeId && to === sourceNodeId) {\n errors.push({ kind: 'self_loop', value: to, reason: `jump target ${to} connects the node to itself - remove the self-referencing connection` });\n } else if (!nodeIds.has(to)) {\n errors.push({ kind: 'dangling_target', value: to, reason: `jump target ${to} not found in this form` });\n }\n }\n\n // Explicit branch anchor (#4105): a conditional's branch edge carries its\n // option (node_options row) id as a top-level field rather than inferring\n // it from a condition var - see buildAdjacencyMap/buildLogicMap. Validated\n // the same way as a condition's option var below.\n if (typeof action?.option_id === 'string' && !optionIds.has(action.option_id)) {\n errors.push({ kind: 'stale_option_ref', value: action.option_id, reason: `references option ${action.option_id} not on this node` });\n }\n\n for (const v of action?.condition?.vars || []) {\n if (typeof v?.value !== 'string') continue;\n if (v.type === 'node' && !nodeIds.has(v.value)) {\n errors.push({ kind: 'dangling_target', value: v.value, reason: `references node ${v.value} not in this form` });\n } else if (v.type === 'option' && !optionIds.has(v.value)) {\n errors.push({ kind: 'stale_option_ref', value: v.value, reason: `references option ${v.value} not on this node` });\n } else if (v.type === 'variable' && !routableVariables.includes(v.value)) {\n errors.push({ kind: 'unresolved_variable', value: v.value, reason: `references variable \"${v.value}\" which is not a routable variable` });\n }\n }\n\n return errors;\n}\n","/**\n * Custom form variables (#5647, slice 1 of #5242) - the one shared engine.\n *\n * A custom variable is a named number or text value on a form. \"Save to a\n * variable\" lives ON THE NODE: `node.config.save_to = { variable_id, op,\n * field_id? }`. A Choice node saves the picked answer's text (`option.content`); only a legacy\n * `op: 'add'` marker reads the per-option `node_options.value`.\n * Routing (node_logic) is untouched.\n *\n * `deriveVariables` is pure and recomputes every value from the current answers,\n * so a re-answer replaces that node's contribution and can never double count.\n * The viewer runs it live; the API runs the same function over saved answers, so\n * nothing computed is trusted from the browser.\n */\n\nimport { isAnswerKeyActive } from './logic-types.js';\n\n/** Longest custom variable key. */\nexport const VARIABLE_KEY_MAX_LENGTH = 40;\n\n/** Custom variable key: lowercase letter first, then lowercase letters, digits or underscores, VARIABLE_KEY_MAX_LENGTH max. */\nexport const VARIABLE_KEY_PATTERN = new RegExp(`^[a-z][a-z0-9_]{0,${VARIABLE_KEY_MAX_LENGTH - 1}}$`);\n\n/** Variable value types. */\nexport const VARIABLE_TYPES = ['number', 'text'];\n\n/** Longest text a variable may hold (base, option value or saved answer). */\nexport const VARIABLE_TEXT_MAX_LENGTH = 500;\n\n/** Longest label a variable may carry (matches the form_variables label check). */\nexport const VARIABLE_LABEL_MAX_LENGTH = 200;\n\n/** Most custom variables one form can declare. */\nexport const VARIABLE_MAX_CUSTOM_PER_FORM = 50;\n\n/** Strict decimal: optional sign, digits with an optional fraction. No hex, binary or exponent forms. */\nconst DECIMAL_PATTERN = /^[+-]?(\\d+(\\.\\d*)?|\\.\\d+)$/;\n\n/** Largest absolute number a variable may hold (keeps sums exactly representable). */\nexport const VARIABLE_NUMBER_MAX = 1e12;\n\n/** Node types that can save an answer to a variable. */\nexport const SAVE_TO_NODE_TYPES = ['choice', 'details', 'open'];\n\n/** Save operations. `add` is for number variables only. */\nexport const SAVE_TO_OPS = ['set', 'add'];\n\n/**\n * Keys the platform already uses in links, sessions or the logic engine, so a\n * custom variable can never shadow them. Exact keys; prefixes are below.\n */\nexport const RESERVED_VARIABLE_KEYS = [\n 'node_id',\n 'rsid',\n 'rsid_ts',\n 'qr',\n 'pt',\n 'imp',\n 'display',\n 'max_score',\n 'fbclid',\n 'gclid',\n 'ttclid',\n // The viewer's own query params (a link variable must never shadow or strip them, #5650).\n 'mode',\n 'save',\n 'debug',\n 'play',\n 'sdk',\n 'source',\n 'platform',\n 'auto_height',\n];\n\n/** Reserved key prefixes (UTM parameters and Clipform's own `cf_` namespace). */\nexport const RESERVED_VARIABLE_KEY_PREFIXES = ['utm_', 'cf_'];\n\n/** True when a key is reserved by the platform. */\nexport function isReservedVariableKey(key) {\n if (typeof key !== 'string') return false;\n return (\n RESERVED_VARIABLE_KEYS.includes(key) ||\n RESERVED_VARIABLE_KEY_PREFIXES.some((p) => key.startsWith(p))\n );\n}\n\n/**\n * Validate a NEW custom variable key. Returns an error message, or null when valid.\n */\nexport function validateVariableKey(key) {\n if (typeof key !== 'string' || key === '') return 'Key is required';\n if (!VARIABLE_KEY_PATTERN.test(key)) {\n return `Key must start with a lowercase letter and use only lowercase letters, numbers and underscores (${VARIABLE_KEY_MAX_LENGTH} characters max)`;\n }\n if (isReservedVariableKey(key)) return `\"${key}\" is reserved`;\n return null;\n}\n\n/**\n * Coerce a raw value to a variable type. Returns the value, or undefined when it\n * cannot be represented. number: a finite number or a numeric string. text: a\n * string (a number is stringified) within VARIABLE_TEXT_MAX_LENGTH.\n */\nexport function coerceVariableValue(type, raw) {\n if (type === 'number') {\n let n;\n if (typeof raw === 'number') n = raw;\n else if (typeof raw === 'string' && DECIMAL_PATTERN.test(raw.trim())) n = Number(raw.trim());\n else return undefined;\n if (!Number.isFinite(n) || Math.abs(n) > VARIABLE_NUMBER_MAX) return undefined;\n return n;\n }\n if (type === 'text') {\n let s;\n if (typeof raw === 'string') s = raw;\n else if (typeof raw === 'number' && Number.isFinite(raw)) s = String(raw);\n else return undefined;\n // An empty string is no value (a blank field never overwrites the base), same as for numbers.\n if (s === '' || s.length > VARIABLE_TEXT_MAX_LENGTH) return undefined;\n return s;\n }\n return undefined;\n}\n\n/**\n * Validate a node's `config.save_to` against the form's variables. Returns an\n * error message, or null when valid. `variables` is the form's variable list\n * ({ id, type, kind }); only custom variables can be saved to.\n */\nexport function validateSaveTo(saveTo, nodeType, variables) {\n if (!saveTo || typeof saveTo !== 'object' || Array.isArray(saveTo)) return 'save_to must be an object';\n if (!SAVE_TO_NODE_TYPES.includes(nodeType)) {\n return `A ${nodeType} node cannot save to a variable`;\n }\n const { variable_id: variableId, op, field_id: fieldId, enabled } = saveTo;\n if (enabled !== undefined && typeof enabled !== 'boolean') return 'save_to.enabled must be a boolean';\n if (typeof variableId !== 'string' || variableId === '') return 'save_to.variable_id is required';\n const variable = (variables || []).find((v) => v.id === variableId && v.kind === 'custom');\n if (!variable) return 'save_to.variable_id does not match a custom variable on this form';\n if (!SAVE_TO_OPS.includes(op)) return 'save_to.op must be \"set\" or \"add\"';\n if (op === 'add' && variable.type !== 'number') return 'save_to.op \"add\" works on number variables only';\n if (nodeType === 'details') {\n if (typeof fieldId !== 'string' || fieldId === '') return 'save_to.field_id is required on a details node';\n } else if (fieldId !== undefined && fieldId !== null) {\n return 'save_to.field_id applies to details nodes only';\n }\n return null;\n}\n\n/**\n * Validate a Choice option `value` against a variable's type. null/undefined\n * (no value) is valid. Returns an error message, or null when valid.\n */\nexport function optionValueError(variableType, value) {\n if (value === null || value === undefined) return null;\n if (coerceVariableValue(variableType, value) === undefined) {\n return variableType === 'number' ? 'Option value must be a number' : 'Option value must be text';\n }\n return null;\n}\n\nfunction asArray(value) {\n return Array.isArray(value) ? value : [];\n}\n\nfunction optionsOf(node) {\n return asArray(node?.options ?? node?.node_options);\n}\n\n/** Most points one answer can give one variable (#5805); mirrors choice `config.points`. */\nexport const CHOICE_POINTS_MAX = 999;\n\n/**\n * `node_options.scores` holds two shapes (#5805). THE KEY IS RESOLVED AGAINST THE FORM'S VARIABLES (never a\n * pattern): a key naming a custom NUMBER variable is points toward that variable, keyed by the variable's\n * KEY (a copy keeps keys while it mints new ids); any other key (a category row, or no row) is a legacy\n * personality category NAME. Pass `variables` (or the Set from customNumberKeys) wherever scores are read.\n */\nexport function customNumberKeys(variables) {\n if (variables instanceof Set) return variables;\n const out = new Set();\n for (const v of asArray(variables)) if (v && v.kind === 'custom' && v.type === 'number' && typeof v.key === 'string') out.add(v.key);\n return out;\n}\n\n/** An option's per-variable points: the entries of its `scores` whose key is a custom number variable, `{ key: points }`. */\nexport function optionPoints(option, variables) {\n const scores = option?.scores;\n const out = {};\n if (variables == null || !scores || typeof scores !== 'object' || Array.isArray(scores)) return out;\n const keys = customNumberKeys(variables);\n for (const [k, v] of Object.entries(scores)) {\n if (keys.has(k) && typeof v === 'number' && Number.isFinite(v)) out[k] = v;\n }\n return out;\n}\n\n/** The legacy personality-category entries of a `scores` object: every key that is not a custom number variable's key. */\nexport function legacyCategoryScores(scores, variables) {\n const raw = scores && typeof scores === 'object' && !Array.isArray(scores) ? scores : null;\n const out = {};\n if (!raw) return out;\n const keys = variables == null ? new Set() : customNumberKeys(variables);\n for (const [k, v] of Object.entries(raw)) if (!keys.has(k)) out[k] = v;\n return out;\n}\n\n/** The form's Score variable (a custom number variable keyed `score`), or undefined. */\nexport function findScoreVariable(variables) {\n return asArray(variables).find((v) => v && v.kind === 'custom' && v.type === 'number' && v.key === 'score');\n}\n\n/** The id of the form's Score variable, or undefined. */\nexport function findScoreVariableId(variables) {\n return findScoreVariable(variables)?.id;\n}\n\n/** True when any option of the node carries a points entry (any custom number key). */\nexport function nodeHasPointsMap(node, variables) {\n return optionsOf(node).some((o) => Object.keys(optionPoints(o, variables)).length > 0);\n}\n\n/** True when some option of the node carries a points entry for the variable KEY. */\nexport function nodeHasPointsFor(node, key) {\n return optionsOf(node).some((o) => typeof o?.scores?.[key] === 'number');\n}\n\n/**\n * What deleting a variable changes on one node (#5971): the ONE strip rule the API's DELETE and the builder share.\n * Returns `config` (a copy without `save_to`, when `save_to` names the variable; else null) and `options`, one entry per\n * option that changes: `index`; `was`, its points map as read (null when none); `scores`, the map without the variable's KEY\n * (number variables only; an emptied map is `{}`, never null, so a write replaces the stored one) and `scoresChanged`; and\n * `clearValue` with the `value` it had. Like a Save to that is replaced or cleared, a node that loses its save_to also loses its\n * leftover option values, or they would revive under another setup (e.g. the Score sync turning them into points).\n * Nothing changes: `{ config: null, options: [] }`.\n */\nexport function withoutVariableRefs(node, variable) {\n const config = node?.config;\n const savesTo = !!config && typeof config === 'object' && config.save_to?.variable_id === variable.id;\n let nextConfig = null;\n if (savesTo) {\n nextConfig = { ...config };\n delete nextConfig.save_to;\n }\n const options = [];\n optionsOf(node).forEach((o, index) => {\n const scoresChanged = variable.type === 'number' && typeof o?.scores?.[variable.key] === 'number';\n const clearValue = savesTo && o?.value != null;\n if (!scoresChanged && !clearValue) return;\n const next = { ...(o.scores ?? {}) };\n if (scoresChanged) delete next[variable.key];\n options.push({ index, was: o.scores ?? null, scores: next, scoresChanged, clearValue, value: o.value });\n });\n return { config: nextConfig, options };\n}\n\n/** The node's save_to marker for the variable is switched off (#5649): its map entries then do not count (#5805). */\nexport function pointsDormantFor(node, variable) {\n const saveTo = node?.config?.save_to;\n return !!saveTo && saveTo.variable_id === variable.id && saveTo.enabled === false;\n}\n\n/**\n * The custom number variable a single-select node's ENABLED `save_to` op add points at, or undefined: the one rule for\n * which per-answer entries are live (the server's conversion and re-point, the builder's inputs, #5805). A switched-off\n * marker, op set, a non-number variable and a multi-select all give undefined.\n */\nexport function addTargetVariable(config, variables) {\n const saveTo = config?.save_to;\n if (!saveTo || saveTo.op !== 'add' || saveTo.enabled === false || config?.selection_mode === 'multiple') return undefined;\n return (Array.isArray(variables) ? variables : []).find((v) => v && v.id === saveTo.variable_id && v.kind === 'custom' && v.type === 'number');\n}\n\n/**\n * Validate a `scores` object against the form's variables (#5805). A key naming a custom NUMBER variable must hold\n * a whole number 0..CHOICE_POINTS_MAX; a key naming a custom non-number variable is an error. Any other key is a\n * legacy category (the API's category rule covers it). null when valid.\n */\nexport function pointsMapError(scores, variables) {\n if (scores === null || scores === undefined) return null;\n if (typeof scores !== 'object' || Array.isArray(scores)) return 'scores must be an object';\n for (const [key, value] of Object.entries(scores)) {\n const variable = asArray(variables).find((v) => v && v.key === key && v.kind === 'custom');\n if (!variable) continue;\n if (variable.type !== 'number') return `scores key ${key} is not a number variable`;\n if (!Number.isInteger(value) || value < 0 || value > CHOICE_POINTS_MAX) {\n return `Points must be a whole number from 0 to ${CHOICE_POINTS_MAX}`;\n }\n }\n return null;\n}\n\n/** Points the picked answers of a choice or binary node give the variable (undefined when none carry it, or its marker is dormant). */\nfunction mapContributionOf(node, responseData, variable) {\n if (node.type !== 'choice' && node.type !== 'binary') return undefined;\n if (pointsDormantFor(node, variable)) return undefined;\n const picked = Array.isArray(responseData) ? responseData : [responseData];\n const options = optionsOf(node);\n let total;\n for (const id of picked) {\n const option = options.find((o) => o.id === id);\n const pts = option && typeof option.scores?.[variable.key] === 'number' ? option.scores[variable.key] : undefined;\n if (pts !== undefined) total = (total ?? 0) + pts;\n }\n return total;\n}\n\n/**\n * What one answered node contributes to a variable, already coerced to the\n * variable's type; undefined when the node contributes nothing (no value picked,\n * empty field, non-coercible text).\n */\nfunction contributionOf(node, saveTo, responseData, variableType) {\n if (node.type === 'choice') {\n // Single-select stores a bare option id; multi-select an array of ids.\n const picked = Array.isArray(responseData) ? responseData : [responseData];\n const options = optionsOf(node);\n if (saveTo.op === 'add') {\n // Legacy marker path: the per-option value.\n const values = [];\n for (const id of picked) {\n const option = options.find((o) => o.id === id);\n const v = coerceVariableValue(variableType, option?.value);\n if (v !== undefined) values.push(v);\n }\n if (values.length === 0) return undefined;\n if (variableType === 'number') return values.reduce((a, b) => a + b, 0);\n return values[0];\n }\n // Set: the picked answer's text. Text joins several picks in pick order; a number takes the first that coerces.\n const values = [];\n for (const id of picked) {\n const option = options.find((o) => o.id === id);\n const v = coerceVariableValue(variableType, option?.content);\n if (v !== undefined) values.push(v);\n }\n if (values.length === 0) return undefined;\n if (variableType === 'text') {\n let joined = values.join(', ');\n if (joined.length > VARIABLE_TEXT_MAX_LENGTH) {\n joined = joined.slice(0, VARIABLE_TEXT_MAX_LENGTH);\n // Do not leave half of a surrogate pair.\n if (/[\\uD800-\\uDBFF]$/.test(joined)) joined = joined.slice(0, -1);\n joined = joined.trim();\n }\n return joined === '' ? undefined : joined;\n }\n return values[0];\n }\n if (node.type === 'details') {\n const fields = asArray(responseData?.fields);\n const field = fields.find((f) => f?.id === saveTo.field_id);\n return coerceVariableValue(variableType, field?.value);\n }\n if (node.type === 'open') {\n // Typed answer only: a recording (or its transcript) is never a variable value.\n if (responseData?.response_type !== 'text') return undefined;\n return coerceVariableValue(variableType, responseData?.text);\n }\n return undefined;\n}\n\n/**\n * Compute every custom variable's value from the current answers.\n *\n * @param {Array<{id: string, key: string, type: 'number'|'text', kind: string, base?: unknown, url_settable?: boolean}>} variables\n * @param {Array<{id: string, type: string, config?: {save_to?: {variable_id: string, op: 'set'|'add', field_id?: string}}, options?: Array<{id: string, content?: string, value?: unknown}>}>} nodes\n * @param {Array<{node_id: string, response_data: unknown}>} answers in first-answered order\n * @param {Record<string, unknown>} [linkValues] link-filled raw values keyed by variable key\n * @param {string[]} [path] ordered node ids the respondent actually took. When given,\n * only answers on the path count, applied in path order (an abandoned branch\n * contributes nothing). Omitted: every answer counts, in first-answered order.\n * @returns {Record<string, number|string>} variable id -> value. A number variable\n * always has a value (default 0); a text variable is absent until set.\n */\nexport function deriveVariables(variables, nodes, answers, linkValues, path) {\n const custom = asArray(variables).filter((v) => v && v.kind === 'custom');\n if (custom.length === 0) return {};\n\n const nodeById = new Map(asArray(nodes).map((n) => [n.id, n]));\n\n // One entry per node: a re-answer replaces the data but keeps its place.\n let answered = new Map();\n for (const a of asArray(answers)) {\n if (a && typeof a.node_id === 'string') answered.set(a.node_id, a.response_data);\n }\n if (Array.isArray(path)) {\n // Route taken only: walk the path in order, keep the nodes that have an answer.\n // A revisited node counts once, at its LATEST position (what happened last wins).\n const onPath = new Map();\n for (const id of path) {\n if (!answered.has(id)) continue;\n onPath.delete(id);\n onPath.set(id, answered.get(id));\n }\n answered = onPath;\n }\n\n const out = {};\n for (const variable of custom) {\n let value = coerceVariableValue(variable.type, variable.base);\n if (value === undefined && variable.type === 'number') value = 0;\n\n // A link-filled value replaces the base (only for a variable the link may set).\n if (variable.url_settable && linkValues && Object.hasOwn(linkValues, variable.key)) {\n const fromLink = coerceVariableValue(variable.type, linkValues[variable.key]);\n if (fromLink !== undefined) value = fromLink;\n }\n\n for (const [nodeId, responseData] of answered) {\n const node = nodeById.get(nodeId);\n if (!node) continue;\n const saveTo = node.config?.save_to;\n // enabled === false: the builder switched it off but kept the setup (#5649); it is dormant.\n if (saveTo && saveTo.enabled !== false && saveTo.variable_id === variable.id) {\n const adds = saveTo.op === 'add' && variable.type === 'number';\n // A node with map entries FOR THIS variable gets its points from the map: its save_to add must not count twice (#5805).\n if (!(adds && nodeHasPointsFor(node, variable.key))) {\n const contribution = contributionOf(node, saveTo, responseData, variable.type);\n if (contribution !== undefined) value = adds ? (value ?? 0) + contribution : contribution;\n }\n }\n if (variable.type === 'number') {\n const points = mapContributionOf(node, responseData, variable);\n if (points !== undefined) value = (value ?? 0) + points;\n }\n }\n\n if (value !== undefined) out[variable.id] = value;\n }\n return out;\n}\n\n/** Most link-fillable (`url_settable`) values one session may carry (#5650). */\nexport const VARIABLE_MAX_LINK_PER_FORM = 25;\n\n/**\n * Code point ranges a link value (and anything shown from it) must never carry:\n * C0/C1 controls, soft hyphen, bidi marks and isolates, line/paragraph separators,\n * zero-width and invisible format characters, filler characters, BOM and the tag block.\n * One list, shared by normalizeLinkValue and the viewer's recall guard (#5650).\n */\nexport const LINK_UNSAFE_RANGES = [\n [0x0, 0x1f],\n [0x7f, 0x9f],\n [0xad, 0xad],\n [0x61c, 0x61c],\n [0x115f, 0x1160],\n [0x180e, 0x180e],\n [0x200b, 0x200f],\n [0x2028, 0x202e],\n [0x2060, 0x2064],\n [0x2066, 0x2069],\n [0x3164, 0x3164],\n [0xfeff, 0xfeff],\n [0xe0000, 0xe007f],\n];\n\n/** True when a code point is in LINK_UNSAFE_RANGES. */\nexport function isUnsafeLinkChar(codePoint) {\n return LINK_UNSAFE_RANGES.some(([lo, hi]) => codePoint >= lo && codePoint <= hi);\n}\n\n/** True when the string contains any unsafe link character. */\nexport function hasUnsafeLinkChar(str) {\n for (const ch of String(str)) if (isUnsafeLinkChar(ch.codePointAt(0))) return true;\n return false;\n}\n\n/** The string without any unsafe link character. */\nexport function stripUnsafeLinkChars(str) {\n let out = '';\n for (const ch of String(str)) if (!isUnsafeLinkChar(ch.codePointAt(0))) out += ch;\n return out;\n}\n\n/** Longest raw (undecoded) link value, and key, one pair may carry. */\nexport const LINK_RAW_VALUE_MAX = 4000;\nexport const LINK_RAW_KEY_MAX = 64;\n/** Most raw pairs, and most total key + value characters, one session POST carries (keeps the body far under the 64 KiB keepalive limit). */\nexport const LINK_RAW_PAIRS_MAX = 50;\nexport const LINK_RAW_TOTAL_MAX = 16000;\n\n/**\n * The raw pairs both sides work from. Drops any pair whose key or value is over its cap, then\n * keeps `#` pairs first, then `?` pairs (each in captured order) until the pair cap or the total-size cap is reached. The viewer\n * posts exactly this and pickLinkValues runs it first, so client and server always agree.\n *\n * @template {{key: string, value: string}} T\n * @param {ReadonlyArray<T> | undefined} pairs\n * @returns {T[]}\n */\nexport function capRawLinkPairs(pairs) {\n const valid = [];\n for (const pair of asArray(pairs)) {\n if (!pair || typeof pair.key !== 'string' || typeof pair.value !== 'string') continue;\n if (pair.key.length > LINK_RAW_KEY_MAX || pair.value.length > LINK_RAW_VALUE_MAX) continue;\n valid.push(pair);\n }\n // `#` pairs win over `?` pairs, so when a cap cuts the list the `#` ones survive: hash pairs\n // first, then query pairs, each in captured order (accepts the viewer's fromHash or the wire's from_hash).\n const isHash = (p) => p.fromHash === true || p.from_hash === true;\n const ordered = [...valid.filter(isHash), ...valid.filter((p) => !isHash(p))];\n const out = [];\n let total = 0;\n for (const pair of ordered) {\n const size = pair.key.length + pair.value.length;\n if (out.length >= LINK_RAW_PAIRS_MAX || total + size > LINK_RAW_TOTAL_MAX) break;\n out.push(pair);\n total += size;\n }\n return out;\n}\n\nconst LINK_EMAIL_SHAPE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\nconst LINK_PLACEHOLDERS = [/^\\{\\{.*\\}\\}$/, /^\\{\\$.*\\}$/, /^\\*\\|.*\\|\\*$/, /^%%.*%%$/, /^x{3,}$/i];\n\n/** Percent-decode without throwing on malformed sequences (those stay as typed). */\nfunction safePercentDecode(s) {\n return s.replace(/(?:%[0-9a-fA-F]{2})+/g, (m) => {\n try {\n return decodeURIComponent(m);\n } catch {\n return m;\n }\n });\n}\n\nfunction isLinkPlaceholder(s) {\n return LINK_PLACEHOLDERS.some((re) => re.test(s));\n}\n\n/**\n * Clean one raw link value (the text after `key=` in `?` or `#`).\n * Percent-decodes; `+` is a space except in an email-shaped value; NFC; strips\n * control and bidi characters; trims. Empty or an unrendered merge-tag\n * placeholder is unset. Truncates to VARIABLE_TEXT_MAX_LENGTH.\n *\n * @param {unknown} raw\n * @returns {{ value: string | undefined, truncated: boolean }}\n */\nexport function normalizeLinkValue(raw) {\n if (typeof raw !== 'string') return { value: undefined, truncated: false };\n const keepPlus = LINK_EMAIL_SHAPE.test(safePercentDecode(raw).trim());\n // Turn `+` into a space BEFORE decoding so an encoded %2B stays a plus.\n let s = safePercentDecode(keepPlus ? raw : raw.replace(/\\+/g, ' '));\n // Strip BEFORE NFC so an invisible character between a base and a combining mark can't change\n // the result: the same value normalises identically on first capture and after a re-encode.\n s = stripUnsafeLinkChars(s).normalize('NFC').trim();\n if (s === '' || isLinkPlaceholder(s) || isLinkPlaceholder(raw.trim())) {\n return { value: undefined, truncated: false };\n }\n let truncated = false;\n if (s.length > VARIABLE_TEXT_MAX_LENGTH) {\n s = s.slice(0, VARIABLE_TEXT_MAX_LENGTH);\n // Do not leave half of a surrogate pair.\n if (/[\\uD800-\\uDBFF]$/.test(s)) s = s.slice(0, -1);\n s = s.trim();\n truncated = true;\n }\n return { value: s === '' ? undefined : s, truncated };\n}\n\n/**\n * Pick the link-fillable values out of raw URL pairs.\n * Only `kind === 'custom' && url_settable` variables can be set (builtin and\n * category never). Keys match case-insensitively and are stored under the\n * declared spelling. A `#` pair wins over a `?` pair. At most\n * VARIABLE_MAX_LINK_PER_FORM values. Values stay strings.\n *\n * @param {Array<{key: string, kind: string, url_settable?: boolean}>} variables\n * @param {Array<{key: string, value: string, fromHash?: boolean}>} pairs raw (undecoded) pairs\n * @returns {{ values: Record<string, string>, dropped: string[], truncated: string[] }}\n */\nexport function pickLinkValues(variables, pairs) {\n const declared = new Map();\n for (const v of asArray(variables)) {\n if (\n v &&\n v.kind === 'custom' &&\n v.url_settable === true &&\n typeof v.key === 'string' &&\n VARIABLE_KEY_PATTERN.test(v.key) &&\n !isReservedVariableKey(v.key)\n ) {\n declared.set(v.key.toLowerCase(), v.key);\n }\n }\n const values = {};\n const dropped = [];\n const truncated = [];\n const fromHashKeys = new Set();\n for (const pair of capRawLinkPairs(pairs)) {\n const key = declared.get(pair.key.toLowerCase());\n if (key === undefined) {\n dropped.push(pair.key);\n continue;\n }\n const fromHash = pair.fromHash === true;\n // A hash value is never replaced by a query value.\n if (!fromHash && fromHashKeys.has(key)) continue;\n const { value, truncated: wasTruncated } = normalizeLinkValue(pair.value);\n if (value === undefined) {\n dropped.push(key);\n continue;\n }\n if (!Object.hasOwn(values, key) && Object.keys(values).length >= VARIABLE_MAX_LINK_PER_FORM) {\n dropped.push(key);\n continue;\n }\n values[key] = value;\n if (fromHash) fromHashKeys.add(key);\n const at = truncated.indexOf(key);\n if (wasTruncated && at === -1) truncated.push(key);\n else if (!wasTruncated && at !== -1) truncated.splice(at, 1);\n }\n return { values, dropped, truncated };\n}\n\n/** A built link longer than this gets a warning (some tools and chats cut long links) (#5683). */\nexport const VARIABLE_LINK_WARN_CHARS = 2000;\n\n/**\n * True for a key that likely holds personal data (`email`, `phone`, `name`, as the whole key or a\n * `_`-separated token). Such values go after `#` in the link so they never reach a server log.\n * Warn only - never blocks.\n */\nexport function isPersonalLinkKey(key) {\n if (typeof key !== 'string') return false;\n return key\n .toLowerCase()\n .split('_')\n .some((token) => token === 'email' || token === 'phone' || token === 'name');\n}\n\n/**\n * Tools that can put an id into a link, so a respondent's id reaches the form (#5683).\n * Rule: major email tools only, one each, and only where the tag or setup is easy to get wrong.\n * `snippet` is the text to paste into the tool (null when the tool adds it itself).\n */\nexport const LINK_VARIABLE_PRESETS = [\n {\n id: 'mailchimp',\n tool: 'Mailchimp',\n key: 'mailchimp_id',\n type: 'text',\n snippet: '?mailchimp_id=*|UNIQID|*',\n note: 'Add this to the end of your form link in your Mailchimp campaign.',\n },\n {\n id: 'kit',\n tool: 'Kit',\n key: 'ck_subscriber_id',\n type: 'text',\n snippet: null,\n note: 'In Kit, turn on \"Add subscriber_id parameter in email links\" in advanced tracking. Kit then adds ck_subscriber_id to every link in your broadcasts and sequences.',\n help_url: 'https://help.kit.com/en/articles/9375532-global-advanced-tracking',\n },\n];\n\n/** The preset whose key is `key`, or undefined. */\nexport function linkVariablePreset(key) {\n return LINK_VARIABLE_PRESETS.find((p) => p.key === key);\n}\n\n/**\n * The form link with every link-fillable variable on it, for the builder's \"Your link\" box.\n * Custom `url_settable` variables with a non-reserved key, in panel order. Personal keys\n * (email, phone, name) go after `#`, the rest in the query. A missing value becomes `key=`.\n *\n * @param {string} shareUrl\n * @param {Array<{key: string, kind: string, url_settable?: boolean}>} variables\n * @param {(variable: object) => unknown} valueFor\n * @returns {string}\n */\nexport function buildVariableLink(shareUrl, variables, valueFor) {\n const query = [];\n const hash = [];\n for (const v of asArray(variables)) {\n if (!v || v.kind !== 'custom' || v.url_settable !== true) continue;\n if (typeof v.key !== 'string' || isReservedVariableKey(v.key)) continue;\n const raw = valueFor ? valueFor(v) : undefined;\n const value = raw === undefined || raw === null ? '' : String(raw);\n const pair = `${v.key}=${encodeURIComponent(value)}`;\n (isPersonalLinkKey(v.key) ? hash : query).push(pair);\n }\n let url = shareUrl;\n if (query.length) url += (url.includes('?') ? '&' : '?') + query.join('&');\n if (hash.length) url += `#${hash.join('&')}`;\n return url;\n}\n\n/**\n * The most points a respondent can score (#5727), for the End Screen \"out of N\" preset.\n * With a custom number variable keyed `score`: each choice node that adds to it counts\n * its top option value (single-select) or the sum of its positive values (multi-select).\n * Without one: the legacy denominator the viewer builds (top positive `score` per node\n * where the answer key is active, see apps/viewer/lib/scoring.ts).\n */\nexport function pointsAvailable(variables, nodes) {\n const scoreVar = asArray(variables).find((v) => v && v.kind === 'custom' && v.type === 'number' && v.key === 'score');\n let total = 0;\n for (const node of asArray(nodes)) {\n const options = optionsOf(node);\n if (options.length === 0) continue;\n if (scoreVar) {\n let values;\n if (nodeHasPointsFor(node, scoreVar.key)) {\n // Map entries for the Score are the node's points; its save_to add is not also counted (#5805).\n // A switched-off marker for the Score (#5649) makes the entries dormant: they count for nothing.\n if ((node.type !== 'choice' && node.type !== 'binary') || pointsDormantFor(node, scoreVar)) continue;\n values = options.map((o) => o?.scores?.[scoreVar.key]).filter((v) => typeof v === 'number' && v > 0);\n } else {\n const saveTo = node?.config?.save_to;\n if (node.type !== 'choice' || !saveTo || saveTo.enabled === false || saveTo.op !== 'add' || saveTo.variable_id !== scoreVar.id) continue;\n values = options.map((o) => o?.value).filter((v) => typeof v === 'number' && Number.isFinite(v) && v > 0);\n }\n if (values.length === 0) continue;\n total += node.config?.selection_mode === 'multiple'\n ? values.reduce((a, b) => a + b, 0)\n : Math.max(...values);\n } else {\n if (!isAnswerKeyActive(node)) continue;\n const top = Math.max(...options.map((o) => o?.score ?? 0));\n if (top > 0) total += top;\n }\n }\n return total;\n}\n\n/**\n * The End Screen score line preset (#5727, #5728): \"You scored {{score}} out of N\",\n * or \"You scored {{score}}\" when N is 0. Shared by the builder and the API.\n */\nexport function scoreLinePreset(points) {\n return Number.isFinite(points) && points > 0\n ? `You scored {{score}} out of ${points}`\n : 'You scored {{score}}';\n}\n\n/**\n * Whether a node's options carry real points (#5728): some option is a correct answer\n * (`is_correct === true`) or has a non-null, non-zero `score`. The builder sends\n * `{ score: null, is_correct: false }` on every option of an unscored question, which is NOT scored.\n */\nexport function hasPointOptions(options) {\n return asArray(options).some((o) => o && (o.is_correct === true || (o.score != null && o.score !== 0)));\n}\n\n/**\n * Whether a node should be wired to the form's Score variable (#5728): a single-select\n * choice with real points (see hasPointOptions) and no `save_to` key, or a `save_to` op SET (#5806: Save to is\n * independent of points; the Set marker is kept). A dormant add `save_to`\n * (`enabled: false`) counts as a key and is never rewired; multi-select, binary and\n * category-only nodes are left alone. `config` must already have the selection-mode gate applied.\n */\nexport function qualifiesForScoreWiring(type, config, options) {\n if (type !== 'choice') return false;\n // A SET marker (Save to capturing an answer) is independent of points (#5806): it does not block Score wiring.\n // Any other save_to (an add, switched on or off) does.\n if (config?.save_to != null && config.save_to.op !== 'set') return false;\n if (config?.selection_mode === 'multiple') return false;\n return hasPointOptions(options);\n}\n\n/**\n * Wire a scored choice node to the Score variable (#5728, #5805): writes the marker `save_to { variable_id, op: 'add' }`\n * (so the node shows as saving to Score) AND, on each option with a non-zero `score`, `scores[variable.key] = score`\n * (legacy category entries and an entry already set are kept). No `value` is written: the points live in the map,\n * the marker adds nothing twice (see deriveVariables). Pure. `variable` is `{ id, key }`. Returns the inputs untouched\n * with `wired: false` when the node does not qualify or is already wired (some option carries a `scores[key]` entry).\n */\nexport function withScoreVariable(type, config, options, variable) {\n if (!qualifiesForScoreWiring(type, config, options)) return { config, options, wired: false };\n if (isWiredToVariable(options, variable.key)) return { config, options, wired: false };\n return {\n // A Set marker stays as it is: the Score points ride the entries alone.\n config: config?.save_to != null ? config : { ...config, save_to: { variable_id: variable.id, op: 'add' } },\n options: options.map((o) =>\n o.score != null && o.score !== 0 ? { ...o, scores: { ...(o.scores ?? {}), [variable.key]: o.score } } : o,\n ),\n wired: true,\n };\n}\n\n/** True when some option carries a points entry for the variable KEY (#5805: that is what \"wired\" means). */\nexport function isWiredToVariable(options, key) {\n return asArray(options).some((o) => typeof o?.scores?.[key] === 'number');\n}\n\n// A stored value is points only when the node ADDS to a variable (a number, non-zero): under op set\n// (or text values, or no save_to) the values are labels or targets, never points.\nfunction carriesPoints(o, addsValues, variables) {\n if (!o) return false;\n if (o.score != null && o.score !== 0) return true;\n if (Object.values(optionPoints(o, variables)).some((n) => n !== 0)) return true;\n return addsValues && typeof o.value === 'number' && o.value !== 0;\n}\n\n/**\n * What kind of scored question a choice node is (#5764), the one rule behind the builder's\n * Points field, the tick and the per-option inputs:\n * - 'multi_select': several picks; no ticks, the answer key is paused.\n * - 'right_answer': at least one tick and every unticked option has no points. One Points\n * number (see choicePoints) covers the ticked options.\n * - 'points_per_answer': anything else carrying points (a mixed legacy node, or no tick with scores,\n * or values on a node that adds to a variable; text and op set values are not points). Keeps per-option inputs; the tick is off when nothing is ticked.\n * - 'unscored': no tick, no points, no values yet. A first tick makes it 'right_answer'.\n */\nexport function choiceQuestionKind(config, options, variables) {\n if (config?.selection_mode === 'multiple') return 'multi_select';\n const list = asArray(options);\n const ticked = list.filter((o) => o?.is_correct === true);\n if (ticked.length > 0) {\n const stray = list.some(\n (o) => o?.is_correct !== true && ((o?.score != null && o.score !== 0) || Object.values(optionPoints(o, variables)).some((n) => n !== 0)),\n );\n return stray ? 'points_per_answer' : 'right_answer';\n }\n const addsValues = config?.save_to?.op === 'add';\n return list.some((o) => carriesPoints(o, addsValues, variables)) ? 'points_per_answer' : 'unscored';\n}\n\n/**\n * The Points N of a right-answer question (#5764): the top ticked score, else\n * `config.points`, else 1. Read from the data so the field never drifts.\n */\nexport function choicePoints(config, options) {\n // Clamped to 0..CHOICE_POINTS_MAX: the stepper can't commit more, so it must never show more.\n const clamp = (n) => Math.min(CHOICE_POINTS_MAX, Math.max(0, n));\n const scores = asArray(options)\n .filter((o) => o?.is_correct === true && Number.isInteger(o.score))\n .map((o) => clamp(o.score));\n if (scores.length > 0) return Math.max(...scores);\n return Number.isInteger(config?.points) ? clamp(config.points) : 1;\n}\n","// @vid-master/config/node-types\n// Static node type definitions — single source of truth for all apps.\n// New node types require code changes (new component, renderer, etc.),\n// so this data is version-controlled rather than stored in the database.\n\nimport { FEATURES, companyHasNodeType } from './features.js';\nimport { DRAW_PRESETS } from './draw-presets.js';\nimport { CHOICE_POINTS_MAX } from './variables.js';\n\n// Canonical answer-format and consent enums (single source of truth). The node\n// schemas below reference these, and all apps import them, so they cannot drift.\nexport const RESPONSE_FORMATS = ['text', 'audio', 'video'];\nexport const CONSENT_TYPES = ['consent', 'opt_in'];\n// Choice option caps (#5411). List display takes up to CHOICE_MAX_OPTIONS; the A/B/C\n// letter chips share one row, so Letters display stays at CHOICE_MAX_LETTERS_OPTIONS.\n// Every other option-count literal (pick limit, response schema, builder, viewer,\n// API, MCP) derives from `choice.max_options` / `choice.max_letters_options`.\nexport const CHOICE_MAX_OPTIONS = 12;\nexport const CHOICE_MAX_LETTERS_OPTIONS = 6;\n// One option's text: about three lines on a phone. The row grows and the list scrolls.\nexport const CHOICE_MAX_OPTION_LENGTH = 80;\nexport const CONTACT_FIELD_TYPES = ['text', 'textarea', 'email', 'tel', 'url', 'date', 'number'];\n\n// Opinionated default tier bands for the draw node's optional match-to-shape\n// game (#2148) - a builder-authored target scores the respondent's drawing on\n// submit. Shipped as the config default (`config_schema.properties.game.\n// properties.tiers.default` below) so a node with a target but no custom tiers\n// still gets a sensible 5-band scale; the viewer's scorer (apps/viewer/lib/\n// matchShape.ts) falls back to this same list when `config.game.tiers` is\n// absent. No tier-editing UI in v1 (see the issue's Future section).\nexport const DRAW_GAME_DEFAULT_TIERS = [\n { min_score: 0, label: 'Scribble' },\n { min_score: 35, label: 'Warming up' },\n { min_score: 55, label: 'Nice try' },\n { min_score: 75, label: 'Great match' },\n { min_score: 92, label: 'Perfect' },\n];\n\n// Draw paper + ink (#5076). Pure so the builder and the viewer share one rule:\n// the first stock pen colour is \"ink\" and follows the paper, so a default pen\n// is always legible (dark ink on light paper, white ink on a chalkboard).\nconst DRAW_INK_ON_LIGHT = '#1F2937';\nconst DRAW_INK_ON_DARK = '#FFFFFF';\n\n/** True when the paper's relative luminance (WCAG) is below 0.5. Unparseable input counts as light. */\nexport function isDarkPaper(hex) {\n const m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(String(hex ?? '').trim());\n if (!m) return false;\n const h = m[1].length === 3 ? m[1].replace(/./g, (c) => c + c) : m[1];\n const lin = [0, 2, 4].map((i) => {\n const v = parseInt(h.slice(i, i + 2), 16) / 255;\n return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);\n });\n return 0.2126 * lin[0] + 0.7152 * lin[1] + 0.0722 * lin[2] < 0.5;\n}\n\n/** The pen colour that reads on this paper: white on dark paper, the stock dark ink otherwise. */\nexport function inkFor(paper) {\n return isDarkPaper(paper) ? DRAW_INK_ON_DARK : DRAW_INK_ON_LIGHT;\n}\n\n// Default number of seconds a video-backed node's answer options stay hidden\n// before revealing (#2794). Lives on `node_media.options_reveal_seconds`\n// (real, nullable) - null means \"use this default\", 0 means \"reveal\n// immediately\". Single source of truth for the viewer's RevealGate default\n// and the builder's placeholder/hint when the node has no stored value.\nexport const DEFAULT_OPTIONS_REVEAL_SECONDS = 3;\n\n// Default cap (seconds) on an open node's audio/video recorder (#2838).\n// Lives on `node.config.max_recording_seconds` (JSONB, not the media asset -\n// an open node can collect a video answer with no media asset attached).\n// Single source of truth for the viewer recorder's `maxDuration` fallback\n// and the builder's placeholder/hint when the node has no stored value.\nexport const DEFAULT_MAX_RECORDING_SECONDS = 120;\n\n// Bounds for `max_recording_seconds` - used directly as the config_schema's\n// minimum/maximum below AND exported so the builder's stepper (OpenNode.tsx)\n// clamps to the exact same numbers instead of a hardcoded local copy that\n// could drift from the schema. No unlimited/0 escape hatch (floor of 10).\nexport const MAX_RECORDING_SECONDS_MIN = 10;\n\n// 300 (restored from 180, #4023; was 300 before #4014 lowered it): at the\n// 720p/1.5Mbps recorder caps, 300s runs well under the now-200 MiB Supabase\n// storage ceiling (SUPABASE_STORAGE_MAX_BYTES), so the tighter #4014 cap is\n// no longer needed. The viewer clamps existing nodes storing a higher value\n// down to this at read time - no data migration.\nexport const MAX_RECORDING_SECONDS_MAX = 300;\n\n/**\n * The noun a camera node's cap/min copy uses for a capture, from what the node\n * accepts: photo(s), video(s), or item(s) when both (or neither) are allowed.\n * Shared by the viewer's errors and the builder's \"Number of <noun>\" row so the\n * two never drift. Library never changes the noun.\n */\nexport function cameraCaptureUnit(allowedCapture, count) {\n const types = Array.isArray(allowedCapture) ? allowedCapture : [];\n const photo = types.includes('photo');\n const video = types.includes('video');\n const plural = count !== 1;\n if (photo && !video) return plural ? 'photos' : 'photo';\n if (video && !photo) return plural ? 'videos' : 'video';\n return plural ? 'items' : 'item';\n}\n\n/**\n * The capture buttons a camera node offers, and what each accepts. Camera\n * buttons come from `camera_capture` (absent = `allowed_capture`, so existing\n * nodes are unchanged); the library button from `allow_library_upload`,\n * accepting `allowed_capture`. `types` is everything a respondent can submit\n * (upload validation, \"photos\" / \"videos\" / \"items\" copy). Shared by the\n * builder and the viewer so the two can't disagree.\n */\nexport function cameraCaptureSources(config) {\n const libraryTypes = Array.isArray(config?.allowed_capture) && config.allowed_capture.length ? config.allowed_capture : ['photo'];\n const camera = Array.isArray(config?.camera_capture) ? config.camera_capture : libraryTypes;\n const photo = camera.includes('photo');\n const video = camera.includes('video');\n const library = config?.allow_library_upload !== false;\n const types = ['photo', 'video'].filter(\n (t) => (t === 'photo' ? photo : video) || (library && libraryTypes.includes(t))\n );\n return { photo, video, library, libraryTypes, types };\n}\n\n/**\n * The display order of a camera node's capture buttons. A saved `capture_order`\n * is trusted only when it is a full permutation of photo/video/library; a\n * missing, partial, duplicated or unknown-key value is the default order.\n * Shared by the builder tiles and the viewer so the rule can't drift.\n */\nexport function resolveCameraCaptureOrder(captureOrder) {\n const fallback = ['photo', 'video', 'library'];\n if (\n Array.isArray(captureOrder) &&\n captureOrder.length === fallback.length &&\n fallback.every((k) => captureOrder.includes(k))\n ) {\n return [...captureOrder];\n }\n return fallback;\n}\n\n// Booking result: response_schema (what the viewer submits) and output_schema\n// (the webhook payload) share one shape. Only provider + status are required:\n// the viewer knows just the provider URIs until the server-side confirm (#5303)\n// fills in the times / links.\nconst BOOKING_PROVIDERS = ['calendly', 'google_meet'];\n\n/** Weekday keys of a Google Meet booking's `availability.weekly_hours`, Monday first. */\nexport const BOOKING_WEEKDAYS = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];\n\nconst WORKDAY_HOURS = [{ start: '09:00', end: '17:00' }];\n\n/**\n * Google Meet booking defaults (#5308/#5309). The builder asks only for the\n * meeting length, the weekly hours and the gap between meetings (#5856);\n * notice and window are fixed, and the timezone is the owner's Google\n * Calendar timezone, read at request time.\n */\nexport const GOOGLE_MEET_BOOKING_DEFAULTS = Object.freeze({\n calendar_id: 'primary',\n duration: 30,\n weekly_hours: Object.freeze({\n mon: WORKDAY_HOURS, tue: WORKDAY_HOURS, wed: WORKDAY_HOURS, thu: WORKDAY_HOURS, fri: WORKDAY_HOURS,\n sat: [], sun: [],\n }),\n buffer_minutes: 0,\n min_notice_minutes: 240,\n days_ahead: 14,\n});\n\nconst BOOKING_RESULT_SCHEMA = {\n type: 'object',\n required: ['provider', 'status'],\n properties: {\n provider: { type: 'string', enum: BOOKING_PROVIDERS },\n status: { type: 'string', enum: ['booked', 'skipped'] },\n start_time: { type: 'string', format: 'date-time' },\n end_time: { type: 'string', format: 'date-time' },\n timezone: { type: 'string' },\n join_url: { type: 'string' },\n reschedule_url: { type: 'string' },\n cancel_url: { type: 'string' },\n invitee: {\n type: 'object',\n properties: {\n name: { type: 'string' },\n email: { type: 'string' },\n },\n },\n provider_ids: {\n type: 'object',\n properties: {\n event_uri: { type: 'string' },\n invitee_uri: { type: 'string' },\n event_id: { type: 'string' },\n calendar_id: { type: 'string' },\n },\n },\n },\n description: 'Booking result',\n};\n\n// Webhook output: the flat result plus node_type, like every sibling output_schema.\nconst BOOKING_OUTPUT_SCHEMA = {\n ...BOOKING_RESULT_SCHEMA,\n required: ['node_type', ...BOOKING_RESULT_SCHEMA.required],\n properties: {\n node_type: { type: 'string', const: 'booking' },\n ...BOOKING_RESULT_SCHEMA.properties,\n },\n};\n\nexport const NODE_TYPES = {\n start: {\n label: 'Start',\n shorthand: 'Start',\n icon: 'ArrowRight',\n color: '#D1FAE5',\n description: 'Entry point for the form - connects to the first node',\n category: 'start',\n sort_order: 0,\n has_options: false,\n is_terminal: false,\n show_nav_bar: false,\n loading: 'eager',\n supports_prompt: false,\n supports_media: false,\n is_system: true,\n show_in_results: false,\n pii: false,\n respondent_media: null,\n // Never appears in a completed submission's answers (system node, no\n // output_schema) - false is a no-op default, set for guard-test coverage.\n notify_inline: false,\n owner_scoped_config_keys: [],\n default_config: null,\n config_schema: null,\n response_schema: null,\n output_schema: null,\n },\n choice: {\n label: 'Multiple Choice',\n shorthand: 'Multi',\n icon: 'CheckSquare',\n color: '#DBEAFE',\n description: 'Single or multiple choice node with predefined options',\n category: 'input',\n sort_order: 1,\n has_options: true,\n min_options: 1,\n max_options: CHOICE_MAX_OPTIONS,\n // Letters display (A/B/C chips on one row) stops here; List takes the full max_options.\n max_letters_options: CHOICE_MAX_LETTERS_OPTIONS,\n max_option_length: CHOICE_MAX_OPTION_LENGTH,\n is_terminal: false,\n show_nav_bar: true,\n loading: 'eager',\n supports_prompt: true,\n supports_media: true,\n is_system: false,\n show_in_results: true,\n pii: false,\n respondent_media: null,\n // Short selected-option label - safe to render inline in a notification (#4154).\n notify_inline: true,\n owner_scoped_config_keys: [],\n default_config: {\n selection_mode: 'single',\n choice: { enable_branching: false, record_scores: false },\n randomise_options: false,\n show_option_count: false,\n option_display: 'list',\n options: [\n { content: 'Option 1' },\n { content: 'Option 2' },\n ],\n },\n config_schema: {\n type: 'object',\n properties: {\n choice: {\n type: 'object',\n properties: {\n enable_branching: {\n type: 'boolean',\n label: 'Enable branching logic',\n default: true,\n description: 'Allow each option to have its own logic path. When disabled, all options share a single jump action.',\n },\n show_answer_feedback: {\n type: 'boolean',\n label: 'Show answer feedback',\n default: false,\n description: 'Show correct/incorrect feedback after selection (requires scored options).',\n },\n record_scores: {\n type: 'boolean',\n label: 'Mark correct answer',\n default: false,\n description: 'Select which option is the correct answer.',\n },\n },\n },\n selection_mode: {\n enum: ['single', 'multiple'],\n type: 'string',\n label: 'Multiple selection',\n default: 'single',\n description: 'Let respondents pick one option (single) or several (multiple). \"multiple\" is gated by the multi_select feature - while it is off, the API coerces it to \"single\" (the viewer renders single-select only).',\n },\n // Points for a correct answer (#5764). A memory for re-ticking: the live points live on the\n // ticked options' `score`; this only seeds a newly ticked option when it carries none.\n points: {\n type: 'number',\n min: 0,\n max: CHOICE_POINTS_MAX,\n default: 1,\n feature: 'variables',\n label: 'Points',\n description: `Points a correct answer is worth (a whole number from 0 to ${CHOICE_POINTS_MAX}). Applied to a ticked option that sets no score.`,\n },\n // Pick limits for multiple mode. Inert on single (kept stored, never read).\n min_selections: {\n type: 'number',\n min: 1,\n default: 1,\n feature: 'multi_select',\n label: 'Minimum picks',\n shortLabel: 'From',\n description: 'Fewest options a respondent must pick before continuing (multiple selection only)',\n },\n max_selections: {\n type: 'number',\n min: 1,\n max: CHOICE_MAX_OPTIONS,\n feature: 'multi_select',\n label: 'Limit',\n shortLabel: 'To',\n description: 'How many options a respondent can pick: any number, an exact number, or a range.',\n // Words for the builder's Limit dropdown (Unlimited / Exact / Range), shared with the docs.\n modeLabels: { unlimited: 'Unlimited', exact: 'Exact number', range: 'Range' },\n exactLabel: 'Number of picks',\n },\n allow_text_response: {\n type: 'boolean',\n label: 'Allow text response',\n default: false,\n description: 'Allow free-text response in addition to options (single choice only). Gated by the text_response feature - while it is off, the API coerces it to false (the viewer renders no free-text field yet).',\n },\n randomise_options: {\n type: 'boolean',\n label: 'Randomise options',\n default: false,\n description: 'Show options in random order',\n },\n show_option_count: {\n type: 'boolean',\n label: 'Show option count',\n default: false,\n description: 'Display number of options',\n },\n option_display: {\n enum: ['list', 'letters'],\n type: 'string',\n label: 'Option display',\n default: 'list',\n description: `How options render: full text rows (list), or compact A/B/C/D chips (letters) when the media already shows the labelled options - e.g. a Grid background. Letters allows up to ${CHOICE_MAX_LETTERS_OPTIONS} options; list allows up to ${CHOICE_MAX_OPTIONS}.`,\n },\n content_media_type: {\n enum: ['upload', 'recorded'],\n type: 'string',\n label: 'Content media type',\n description: 'How the node media was provided',\n },\n },\n },\n // Single-select = the bare option id; multi-select = a bare array of option ids\n // (#151). Readers key on the data shape, never on the node's current selection_mode.\n response_schema: {\n description: 'Selected option ID (single-select) or an array of selected option IDs (multi-select)',\n oneOf: [\n { type: 'string' },\n { type: 'array', items: { type: 'string' }, minItems: 1, maxItems: CHOICE_MAX_OPTIONS },\n ],\n },\n output_schema: {\n type: 'object',\n required: ['node_type', 'label'],\n oneOf: [\n { type: 'object', required: ['option_id'] },\n { type: 'object', required: ['labels', 'option_ids'] },\n ],\n properties: {\n node_type: { type: 'string', const: 'choice' },\n label: { type: 'string', description: 'Human-readable option label (multi-select: the picked labels joined with \", \" in option order)' },\n option_id: { type: 'string', format: 'uuid', description: 'Selected option UUID (single-select only)' },\n labels: { type: 'array', items: { type: 'string' }, description: 'Picked option labels in option order (multi-select only)' },\n option_ids: { type: 'array', items: { type: 'string', format: 'uuid' }, description: 'Picked option UUIDs in option order (multi-select only)' },\n },\n },\n },\n open: {\n label: 'Open Ended',\n shorthand: 'Open',\n icon: 'Type',\n color: '#DBEAFE',\n description: 'Free-form text responses from users',\n category: 'input',\n sort_order: 2,\n has_options: false,\n is_terminal: false,\n show_nav_bar: true,\n loading: 'eager',\n supports_prompt: true,\n supports_media: true,\n is_system: false,\n show_in_results: true,\n pii: false,\n respondent_media: 'recording',\n // True for the common short-text case; a channel notification (#4154)\n // still swaps a recorded audio/video answer for a typed placeholder\n // based on the answer's own media type, not this flag.\n notify_inline: true,\n owner_scoped_config_keys: [],\n default_config: {\n formats: [\n { order: 0, format: 'text' },\n { order: 1, format: 'audio' },\n { order: 2, format: 'video' },\n ],\n },\n config_schema: {\n type: 'object',\n properties: {\n formats: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n format: { enum: RESPONSE_FORMATS, type: 'string' },\n order: { type: 'number' },\n },\n },\n label: 'Allowed response formats',\n description: 'Which formats the user can respond with, in display order',\n },\n content_media_type: {\n enum: ['upload', 'recorded'],\n type: 'string',\n label: 'Content media type',\n description: 'How the node media was provided',\n },\n max_recording_seconds: {\n type: 'number',\n default: DEFAULT_MAX_RECORDING_SECONDS,\n minimum: MAX_RECORDING_SECONDS_MIN,\n maximum: MAX_RECORDING_SECONDS_MAX,\n label: 'Max recording length (seconds)',\n description: 'Cap on the audio/video recorder for this node, in seconds',\n },\n },\n },\n response_schema: {\n type: 'object',\n required: ['response_type'],\n properties: {\n text: {\n type: 'string',\n description: 'Text response (when response_type is text) or transcribed text from audio/video',\n },\n media: {\n type: 'object',\n properties: {\n type: { enum: ['audio', 'video'], type: 'string' },\n storage_path: { type: 'string' },\n original_storage_path: { type: 'string' },\n thumbnail_storage_path: { type: 'string' },\n mp3_storage_path: { type: 'string' },\n duration_s: { type: 'number' },\n // Pixel size of the final stored video, written by the processor (#5125). Video only.\n width: { type: 'number' },\n height: { type: 'number' },\n processed_at: { type: 'string' },\n // Processor-stamped: is the saved video mirrored (#5021)? Absent = legacy.\n saved_mirrored: { type: 'boolean' },\n facing_mode: { enum: ['user', 'environment'], type: 'string' },\n preview_crop: {\n type: 'object',\n properties: {\n stream_width: { type: 'number' },\n stream_height: { type: 'number' },\n preview_width: { type: 'number' },\n preview_height: { type: 'number' },\n },\n },\n },\n description: 'Media response (when response_type is audio or video)',\n },\n response_type: {\n enum: RESPONSE_FORMATS,\n type: 'string',\n },\n transcription: {\n type: 'object',\n properties: {\n text: { type: 'string' },\n language: { type: 'string' },\n duration: { type: 'number' },\n words: { type: 'array' },\n },\n description: 'Whisper transcription data for audio/video responses',\n },\n },\n },\n output_schema: {\n type: 'object',\n required: ['node_type'],\n properties: {\n node_type: { type: 'string', const: 'open' },\n text: { type: 'string', description: 'Text response or transcription' },\n media: {\n type: 'object',\n properties: {\n type: { enum: ['audio', 'video'], type: 'string' },\n content_type: { type: 'string', description: 'MIME type of the recording (e.g. audio/webm, video/mp4)' },\n filename: { type: 'string', description: 'Suggested download filename' },\n // Direct, time-limited signed URL to the recording (~48h, supports\n // HTTP range); minted per delivery, never the internal storage path.\n url: { type: 'string', format: 'uri' },\n download_url: { type: 'string', format: 'uri', description: 'Same link with a forced download (Content-Disposition: attachment)' },\n expires_at: { type: 'string', format: 'date-time', description: 'When url/download_url stop working' },\n },\n },\n transcription: {\n type: 'object',\n properties: {\n text: { type: 'string' },\n language: { type: 'string' },\n segments: {\n type: 'array',\n description: 'Timestamped segments (seconds) for captions/seeking.',\n items: {\n type: 'object',\n properties: {\n start: { type: 'number' },\n end: { type: 'number' },\n text: { type: 'string' },\n },\n },\n },\n },\n },\n },\n },\n },\n scale: {\n label: 'Scale',\n shorthand: 'Scale',\n icon: 'BarChart3',\n color: '#DBEAFE',\n description: 'Numerical rating or scale node (1-10, etc.)',\n category: 'input',\n sort_order: 3,\n has_options: false,\n is_terminal: false,\n show_nav_bar: true,\n loading: 'eager',\n supports_prompt: true,\n supports_media: true,\n is_system: false,\n show_in_results: true,\n pii: false,\n respondent_media: null,\n // A bare numeric value - short enough to render inline (#4154).\n notify_inline: true,\n owner_scoped_config_keys: [],\n default_config: null,\n config_schema: {\n type: 'object',\n properties: {\n max: { type: 'number', label: 'Maximum value', default: 10, required: true },\n min: { type: 'number', label: 'Minimum value', default: 1, required: true },\n step: { min: 0.1, type: 'number', label: 'Step increment', default: 1 },\n left_label: { type: 'string', label: 'Left label', placeholder: 'Not likely' },\n right_label: { type: 'string', label: 'Right label', placeholder: 'Very likely' },\n show_numbers: { type: 'boolean', label: 'Show numbers', default: true },\n },\n },\n response_schema: {\n type: 'number',\n description: 'Selected scale value',\n },\n output_schema: null,\n },\n booking: {\n label: 'Booking',\n shorthand: 'Booking',\n icon: 'Calendar',\n color: '#E9D5FF',\n description: 'Let respondents book a meeting on a connected Calendly account without leaving the form',\n category: 'action',\n sort_order: 8,\n has_options: false,\n is_terminal: false,\n show_nav_bar: true,\n loading: 'lazy',\n // Like Payment: no generic prompt; the heading + description are config title/description\n // (NodeHeadingFields in the builder, shown above the scheduler in the viewer).\n supports_prompt: false,\n supports_media: false,\n // The interaction takes the stage height under the heading + description (an inline embed).\n interaction_fills_stage: true,\n is_system: false,\n show_in_results: true,\n // Invitee name/email plus cancel/reschedule URLs (BOOKING_RESULT_SCHEMA).\n pii: true,\n respondent_media: null,\n // Structured provider data, but notifications render a one-line \"Booked for\n // <time> (<name>)\" from it (bookingAnswerDisplay), not a placeholder (#5306).\n notify_inline: true,\n // Object granularity, not a dotted path (#4618): every property under\n // these provider objects (scheduling_url, event_type_uri, calendar_id) is\n // the source workspace's own calendar, so save_form strips the whole\n // object on cross-workspace copy. workspace_integration_id is the top-level\n // connected-account pointer (Payment's convention). `calcom` is a dead key\n // (Cal.com support was removed, #5311) kept on purpose: save_form is SQL and\n // owner-scoped-config-keys.test.js binds the union of flat keys to the latest\n // save_form migration's strip array, so dropping it would force a migration.\n owner_scoped_config_keys: ['workspace_integration_id', 'calendly', 'calcom', 'google_meet'],\n // The viewer iframes calendly scheduling_url (booking/CalendlyScheduler.tsx): an outbound embed.\n // Unclaimed anonymous-MCP forms may not go live with this node (#4847).\n blocked_for_anon_mcp: true,\n default_config: null,\n config_schema: {\n type: 'object',\n properties: {\n // google_meet ships dark until integration_google_calendar is live (#5310).\n provider: { type: 'string', enum: BOOKING_PROVIDERS, enum_features: { google_meet: 'integration_google_calendar' }, label: 'Provider', description: 'Scheduling provider (one per node)' },\n workspace_integration_id: { type: 'string', description: 'Connected workspace integration (calendar account) this booking uses' },\n title: { type: 'string', label: 'Heading', maxLength: 80, description: 'Heading shown above the scheduler', anon_locked_keep: true },\n description: { type: 'string', label: 'Description', maxLength: 140, description: 'Body text shown below the heading', anon_locked_keep: true },\n allow_skip: { type: 'boolean', feature: 'optional_questions', default: false, label: 'Optional', description: 'Let respondents continue without booking' },\n calendly: {\n type: 'object',\n properties: {\n event_type_uri: { type: 'string', label: 'Event type URI', description: 'Your Calendly event type URI' },\n event_name: { type: 'string', label: 'Event name', description: 'Display name for the event' },\n scheduling_url: { type: 'string', label: 'Scheduling URL', description: 'Calendly scheduling link embedded in the form' },\n duration: { type: 'number', label: 'Duration (minutes)', description: 'Event duration in minutes' },\n },\n },\n google_meet: {\n type: 'object',\n feature: 'integration_google_calendar',\n properties: {\n // 'primary' (the owner's main calendar, Andy 2026-11-11): bookings must block the calendar other tools check.\n calendar_id: { type: 'string', label: 'Calendar', default: 'primary', description: 'Google Calendar to use for bookings' },\n calendar_name: { type: 'string', label: 'Calendar name', description: 'Display name for the selected calendar' },\n duration: { type: 'number', label: 'Duration (minutes)', default: 30, minimum: 15, maximum: 240, description: 'Meeting duration in minutes' },\n event_title: { type: 'string', label: 'Event title', maxLength: 80, description: 'Calendar event title; the form title when unset' },\n // Kept free on both sides of every busy event in the calendar, not just bookings (#5856).\n buffer_minutes: { type: 'number', label: 'Gap between meetings (minutes)', default: 0, minimum: 0, maximum: 60, description: 'Minutes kept free before and after every busy event in the calendar' },\n // Notice (4h), window (14 days) and timezone (the owner's calendar) are fixed:\n // GOOGLE_MEET_BOOKING_DEFAULTS, scope change on #5309 (2026-10-29).\n availability: {\n type: 'object',\n properties: {\n // Keyed mon..sun; each value is an array of { start, end } 'HH:MM' strings,\n // in the owner's Google Calendar timezone.\n weekly_hours: { type: 'object', description: 'Bookable hours per weekday (mon..sun), each an array of { start, end } HH:MM ranges in the calendar timezone' },\n },\n },\n },\n },\n },\n description: 'Booking provider configuration (one provider per node)',\n },\n response_schema: BOOKING_RESULT_SCHEMA,\n output_schema: BOOKING_OUTPUT_SCHEMA,\n },\n details: {\n label: 'Details',\n shorthand: 'Details',\n icon: 'User',\n color: '#ECFCCB',\n description: 'Collect several fields on one screen - name, email, phone, address, date, and more',\n category: 'input',\n sort_order: 4,\n has_options: false,\n is_terminal: false,\n show_nav_bar: true,\n loading: 'lazy',\n supports_prompt: false,\n supports_media: false,\n is_system: false,\n show_in_results: false,\n pii: true,\n respondent_media: null,\n // Excluded from the aggregate Results charts (a list of emails can't be\n // charted) but DOES show in the per-response Responses table, where each\n // lead's contact fields are actionable (#746).\n show_in_responses: true,\n // Key contact fields (first name, email) are the whole point of a\n // notification for this node type - always inline (#4154).\n notify_inline: true,\n owner_scoped_config_keys: [],\n default_config: {\n fields: [\n { id: 'first_name', required: true },\n { id: 'email', required: true },\n ],\n // No agreement out of the box - the builder adds one via \"Add agreement\"\n // when they actually need consent, so a fresh node ships no orphan checkbox. (#1378)\n consent_items: [],\n },\n config_schema: {\n type: 'object',\n required: ['fields'],\n properties: {\n title: { type: 'string' },\n fields: {\n type: 'array',\n minItems: 1,\n items: {\n type: 'object',\n required: ['id', 'required'],\n properties: {\n id: { type: 'string' },\n type: { enum: CONTACT_FIELD_TYPES, type: 'string' },\n label: { type: 'string' },\n order: { type: 'number' },\n required: { type: 'boolean', default: true },\n is_custom: { type: 'boolean', default: false },\n },\n },\n },\n description: { type: 'string' },\n consent_items: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n id: { type: 'string' },\n name: { type: 'string' },\n label: { type: 'string' },\n order: { type: 'number' },\n type: { type: 'string', enum: CONSENT_TYPES },\n // Optional attached agreement document (PDF only in v1, #2760). Served\n // from the public node-media bucket; `version` bumps on file replace.\n // anon_locked_file: an outside file on a guest live form (#4847), stripped from the\n // payload so the item renders as a plain consent checkbox.\n document: {\n type: 'object',\n anon_locked_file: true,\n properties: {\n storage_path: { type: 'string' },\n filename: { type: 'string' },\n url: { type: 'string' },\n version: { type: 'string' },\n },\n },\n // When true, the consent checkbox stays disabled until the respondent\n // scrolls the attached document to the end (scrollwrap gating, #2760).\n require_scroll_to_accept: { type: 'boolean' },\n },\n },\n },\n },\n },\n response_schema: {\n type: 'object',\n required: ['fields'],\n properties: {\n fields: {\n type: 'array',\n items: {\n type: 'object',\n required: ['id', 'type', 'label', 'value'],\n properties: {\n id: { type: 'string' },\n type: { type: 'string' },\n label: { type: 'string' },\n value: { type: 'string' },\n },\n },\n description: 'Contact form field entries with metadata',\n },\n consent: {\n type: 'array',\n items: {\n type: 'object',\n required: ['id', 'name', 'label', 'accepted', 'type'],\n properties: {\n id: { type: 'string' },\n name: { type: 'string' },\n label: { type: 'string' },\n accepted: { type: 'boolean' },\n type: { type: 'string', enum: CONSENT_TYPES },\n // Scrollwrap audit trail (#2760), present only for document-gated\n // consent items: whether they scrolled to the end, the exact\n // document version they saw, and when they accepted.\n reached_end: { type: 'boolean' },\n document_version: { type: 'string' },\n accepted_at: { type: 'string' },\n // Server-stamped on write (#4552) when the node's current document\n // matches document_version; any client-supplied value is discarded.\n document: {\n type: 'object',\n properties: {\n storage_path: { type: 'string' },\n url: { type: 'string' },\n filename: { type: 'string' },\n },\n },\n },\n },\n description: 'Consent checkbox entries',\n },\n },\n },\n output_schema: {\n type: 'object',\n required: ['node_type', 'fields'],\n properties: {\n node_type: { type: 'string', const: 'details' },\n fields: {\n type: 'array',\n items: {\n type: 'object',\n required: ['type', 'value'],\n properties: {\n type: { type: 'string' },\n value: { type: 'string' },\n },\n },\n },\n // Consent/opt-in agreements the respondent was shown. Present only when\n // the node has consent items. `accepted` is their choice; `label` is the\n // exact wording they agreed to, snapshotted per response (#2828).\n consent: {\n type: 'array',\n items: {\n type: 'object',\n required: ['name', 'accepted', 'type', 'label'],\n properties: {\n name: { type: 'string' },\n accepted: { type: 'boolean' },\n type: { type: 'string', enum: CONSENT_TYPES },\n label: { type: 'string' },\n // Scrollwrap audit trail (#2760), emitted only for document-gated items.\n reached_end: { type: 'boolean' },\n document_version: { type: 'string' },\n accepted_at: { type: 'string' },\n // The exact agreement file accepted (#4552). storage_path is not emitted.\n document: {\n type: 'object',\n properties: {\n url: { type: 'string' },\n filename: { type: 'string' },\n },\n },\n },\n },\n },\n },\n },\n },\n file_upload: {\n label: 'File Upload',\n shorthand: 'Upload',\n icon: 'Upload',\n color: '#ECFCCB',\n description: 'Collect file uploads from respondents',\n category: 'input',\n sort_order: 5,\n has_options: false,\n is_terminal: false,\n show_nav_bar: true,\n loading: 'lazy',\n supports_prompt: false,\n supports_media: false,\n is_system: false,\n show_in_results: true,\n pii: false,\n respondent_media: 'files',\n // Files, not a flat value - a notification renders a typed placeholder (#4154).\n notify_inline: false,\n owner_scoped_config_keys: [],\n // Unclaimed anonymous-MCP forms may not go live with this node (#4847; derived into ANON_MCP_BLOCKED_NODE_TYPES).\n blocked_for_anon_mcp: true,\n default_config: null,\n config_schema: {\n type: 'object',\n properties: {\n max_files: { max: 20, min: 1, type: 'number', label: 'Max files', default: 5, description: 'Maximum number of files respondents can upload' },\n // Capped at 50, not 500: respondent file uploads go straight to the Supabase\n // `file-uploads` bucket, and SUPABASE_STORAGE_MAX_BYTES is a hard ceiling there.\n // Anything above it passed validation and then 500'd at the storage layer (#2556).\n max_file_size_mb: { max: 50, min: 1, type: 'number', label: 'Max file size (MB)', default: 50, description: 'Maximum size per file (1-50 MB)' },\n allowed_media_types: {\n type: 'array',\n items: { enum: ['images', 'videos', 'documents', 'all'], type: 'string' },\n label: 'Allowed media types',\n default: ['images', 'documents'],\n enumLabels: {\n all: 'All file types',\n images: 'Images (JPEG, PNG, GIF, WebP, HEIC)',\n videos: 'Videos (MP4, MOV, WebM, AVI)',\n documents: 'Documents (PDF, DOC, DOCX, XLS, XLSX, TXT, CSV)',\n },\n description: 'Select which types of files respondents can upload',\n },\n },\n },\n response_schema: {\n type: 'object',\n required: ['files'],\n properties: {\n files: {\n type: 'array',\n items: {\n type: 'object',\n required: ['id', 'name', 'storage_path', 'url', 'mime_type', 'size', 'uploaded_at'],\n properties: {\n id: { type: 'string', format: 'uuid', description: 'Unique file identifier' },\n url: { type: 'string', format: 'uri', description: 'Signed Supabase Storage URL for download' },\n name: { type: 'string', description: 'Original filename' },\n size: { type: 'integer', minimum: 1, description: 'File size in bytes' },\n mime_type: { type: 'string', description: 'File MIME type' },\n uploaded_at: { type: 'string', format: 'date-time', description: 'ISO timestamp of upload completion' },\n storage_path: { type: 'string', description: 'Full storage path: workspace_id/form_id/node_id/uuid.ext' },\n width: { type: 'number', description: 'Displayed pixel width (EXIF applied), when the browser could read it (#5125)' },\n height: { type: 'number', description: 'Displayed pixel height (EXIF applied), when the browser could read it (#5125)' },\n duration: { type: 'number', description: 'Duration in seconds for video and audio files, when readable (#5125)' },\n },\n },\n minItems: 1,\n description: 'Array of uploaded file metadata',\n },\n },\n },\n output_schema: {\n type: 'object',\n required: ['node_type'],\n properties: {\n node_type: { type: 'string', const: 'file_upload' },\n files: {\n type: 'array',\n description: 'The uploaded files, each a canonical media object with a fresh signed link.',\n items: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Unique file identifier' },\n filename: { type: 'string', description: 'Original filename' },\n content_type: { type: 'string', description: 'File MIME type' },\n size: { type: 'integer', description: 'File size in bytes' },\n uploaded_at: { type: 'string', format: 'date-time', description: 'ISO timestamp of upload completion' },\n url: { type: 'string', format: 'uri', description: 'Direct, time-limited signed link (~48h, supports HTTP range)' },\n download_url: { type: 'string', format: 'uri', description: 'Same link with a forced download (Content-Disposition: attachment)' },\n expires_at: { type: 'string', format: 'date-time', description: 'When url/download_url stop working' },\n },\n },\n },\n },\n },\n },\n draw: {\n label: 'Drawing',\n shorthand: 'Draw',\n icon: 'Pencil',\n color: '#ECFCCB',\n description: 'Drawing canvas; respondents draw and it is saved as a PNG image',\n category: 'input',\n sort_order: 7,\n has_options: false,\n is_terminal: false,\n show_nav_bar: true,\n loading: 'lazy',\n supports_prompt: false,\n supports_media: true,\n is_system: false,\n show_in_results: true,\n pii: false,\n respondent_media: 'drawing',\n // An image, not a flat value - a notification renders a typed placeholder (#4154).\n notify_inline: false,\n owner_scoped_config_keys: [],\n // Per-type node_media presentation default for a NEW placement (attach /\n // upload routes apply it). The reference image is shown whole, not cropped\n // (#5076); the viewer reads node_media.fit_media like every other media node.\n media_defaults: { fit_media: true },\n default_config: {\n paper_color: '#FAF9F6',\n stroke_colors: ['#1F2937', '#EF4444', '#3B82F6', '#22C55E', '#FACC15'],\n stroke_widths: [3, 6, 12],\n diagram: { opacity: 1, scale: 1 },\n },\n config_schema: {\n type: 'object',\n properties: {\n title: { type: 'string', label: 'Heading', maxLength: 80, description: 'Heading shown above the drawing canvas' },\n description: { type: 'string', label: 'Description', maxLength: 140, description: 'Body text shown below the heading' },\n paper_color: {\n type: 'string',\n label: 'Paper',\n default: '#FAF9F6',\n // The builder offers these as single-select chips; any hex set via the API still renders.\n presets: ['#FAF9F6', '#FFFFFF', '#1E293B'],\n optionLabels: { '#FAF9F6': 'Off-white', '#FFFFFF': 'White', '#1E293B': 'Chalkboard' },\n description: 'Canvas background colour (off-white paper by default). The first stock pen colour (ink) follows it: white on dark paper.',\n },\n stroke_colors: {\n type: 'array',\n items: { type: 'string' },\n minItems: 1,\n maxItems: 8,\n label: 'Pen colours',\n // Chip names in the builder (and any picker); unknown values fall back to the hex.\n // The stock first chip (the one equal to inkFor(paper)) is named `inkLabel` instead, so a\n // group's chip names stay unique (a white pen on light paper is \"White\", not \"Ink\").\n inkLabel: 'Ink',\n optionLabels: { '#1F2937': 'Black', '#FFFFFF': 'White', '#EF4444': 'Red', '#3B82F6': 'Blue', '#22C55E': 'Green', '#FACC15': 'Yellow' },\n default: ['#1F2937', '#EF4444', '#3B82F6', '#22C55E', '#FACC15'],\n description: 'Colour swatches the respondent can draw with. The first entry is the default selection; a single entry locks the pen to that colour and hides the picker.',\n },\n stroke_widths: {\n type: 'array',\n items: { type: 'number', minimum: 1, maximum: 60 },\n minItems: 1,\n maxItems: 5,\n label: 'Pen thickness',\n // Keyed by width in px; unknown widths fall back to `${w}px`.\n optionLabels: { 3: 'Thin', 6: 'Medium', 12: 'Thick' },\n default: [3, 6, 12],\n description: 'Stroke widths (px) the respondent can choose. The middle entry is the default selection; a single entry locks the pen to that width and hides the picker.',\n },\n // The reference image is EITHER a built-in outline (`preset`, below: a static image\n // referenced by name, #5263) OR the node's attached media (media_id,\n // via the same media_asset/create-media.ts pipeline every other\n // supports_media node uses) - not a config field, to avoid a\n // duplicated asset ref. This only tunes its display/bake.\n diagram: {\n type: 'object',\n label: 'Diagram',\n description: 'Display settings for the optional diagram the respondent draws on (a body, vehicle or your own image)',\n properties: {\n // Fit + position (uploaded image only) live on the node_media placement (fit_media / position_x), shared with every media node.\n opacity: { type: 'number', minimum: 0, maximum: 1, default: 1, label: 'Opacity', description: 'Diagram opacity, from 0 (invisible) to 1 (fully opaque)' },\n scale: { type: 'number', minimum: 0.5, maximum: 1, default: 1, label: 'Size', description: 'Diagram size as a fraction of its fitted size. Applies only when the diagram is fitted (fit_media true).' },\n // A built-in outline (#5263): a static image served by the viewer, referenced by name. Not a media asset - no placement. Wins over an attached image; always shown whole and centred.\n preset: { type: 'string', enum: DRAW_PRESETS.map((p) => p.id), label: 'Built-in diagram', description: 'Use a ready-made outline instead of an uploaded image: ' + DRAW_PRESETS.map((p) => `${p.id} (${p.label})`).join(', ') + '. Shown whole and centred, so fit/position do not apply. Shown instead of any attached image while set; unset it to use the attached image of the node.' },\n },\n },\n // Optional match-to-shape game (#2148). Absent entirely by default\n // (not in default_config) - a node with no `game.target` behaves\n // exactly as it did before this key existed. `target.points` is\n // authored once in the builder (a simplified sketch modal, see\n // apps/dashboard) and stored pre-normalized to a [0,1] unit box so the\n // viewer's scorer (apps/viewer/lib/matchShape.ts) and the reveal\n // overlay share the same coordinate frame without re-deriving it.\n game: {\n type: 'object',\n feature: 'draw_target_shape',\n label: 'Match-to-shape game',\n description: 'Optional target shape the drawing is scored against on submit',\n properties: {\n target: {\n type: 'object',\n label: 'Target shape',\n description: 'The outline the respondent is scored against, drawn once by the form builder',\n properties: {\n points: {\n type: 'array',\n minItems: 2,\n maxItems: 500,\n items: {\n type: 'object',\n properties: {\n x: { type: 'number', minimum: 0, maximum: 1 },\n y: { type: 'number', minimum: 0, maximum: 1 },\n },\n },\n description: 'Closed polyline outline, normalized to a [0,1] unit box (aspect-preserving)',\n },\n },\n },\n tiers: {\n type: 'array',\n label: 'Score tiers',\n minItems: 1,\n maxItems: 10,\n items: {\n type: 'object',\n properties: {\n min_score: { type: 'number', minimum: 0, maximum: 100 },\n label: { type: 'string' },\n },\n },\n default: DRAW_GAME_DEFAULT_TIERS,\n description: 'Score bands shown in the reveal, ascending by min_score - defaults to a 5-band Scribble to Perfect scale',\n },\n },\n },\n allow_skip: {\n type: 'boolean',\n feature: 'optional_questions',\n default: false,\n label: 'Optional',\n description: 'Respondents can skip this question without drawing',\n },\n },\n },\n response_schema: {\n // Mirrors the live `open` node's media response shape (the only complete\n // media path): the sketch image is uploaded to the `media-responses`\n // bucket via the same upload-client pipeline and referenced by\n // storage_path. Exported as PNG (crisp line art); the off-white paper\n // background is composited in before export so it is baked into the file.\n type: 'object',\n required: ['media'],\n properties: {\n media: {\n type: 'object',\n required: ['storage_path', 'type'],\n properties: {\n type: { enum: ['image'], type: 'string', description: 'Always \"image\" for a sketch' },\n storage_path: { type: 'string', description: 'Path in the media-responses bucket: bucket/workspace_id/.../uuid.png' },\n mime_type: { type: 'string', description: 'Image MIME type (image/png)' },\n width: { type: 'number', description: 'Exported sketch width in pixels (#5125)' },\n height: { type: 'number', description: 'Exported sketch height in pixels (#5125)' },\n },\n description: 'The exported sketch, stored as a single image in media-responses',\n },\n // Present only when the node has a configured game.target - absent for\n // every draw node published before #2148 and for one with no target.\n game: {\n type: 'object',\n description: 'Present when the node has a configured target shape - the respondent\\'s match-to-shape score',\n properties: {\n score: { type: 'number', minimum: 0, maximum: 100, description: '0-100 match score against the target outline' },\n avg_deviation: { type: 'number', minimum: 0, description: 'Average normalized deviation from the target outline (lower is better)' },\n tier: { type: 'string', description: 'The configured tier label the score falls into' },\n },\n },\n },\n },\n output_schema: {\n type: 'object',\n required: ['node_type'],\n properties: {\n node_type: { type: 'string', const: 'draw' },\n media: {\n type: 'object',\n properties: {\n type: { enum: ['image'], type: 'string' },\n content_type: { type: 'string', description: 'Image MIME type (e.g. image/png)' },\n filename: { type: 'string', description: 'Suggested download filename' },\n url: { type: 'string', format: 'uri', description: 'Direct, time-limited signed link to the drawing (~48h, supports HTTP range)' },\n download_url: { type: 'string', format: 'uri', description: 'Same link with a forced download (Content-Disposition: attachment)' },\n expires_at: { type: 'string', format: 'date-time', description: 'When url/download_url stop working' },\n },\n },\n // Mirrors response_schema.game (piece 1 of #2148) - transformResponse\n // passes it through unchanged, so this describes the FINAL emitted shape.\n game: {\n type: 'object',\n description: 'Present when the node has a configured target shape - the respondent\\'s match-to-shape score',\n properties: {\n score: { type: 'number', minimum: 0, maximum: 100, description: '0-100 match score against the target outline' },\n avg_deviation: { type: 'number', minimum: 0, description: 'Average normalized deviation from the target outline (lower is better)' },\n tier: { type: 'string', description: 'The configured tier label the score falls into' },\n },\n },\n },\n },\n },\n camera: {\n label: 'Camera',\n shorthand: 'Camera',\n icon: 'Camera',\n color: '#ECFCCB',\n description: 'Capture a photo or video from the device camera',\n category: 'input',\n sort_order: 6,\n has_options: false,\n is_terminal: false,\n show_nav_bar: true,\n loading: 'lazy',\n supports_prompt: false,\n supports_media: false,\n is_system: false,\n show_in_results: true,\n pii: false,\n respondent_media: 'files',\n // A captured photo/video, not a flat value - a notification renders a\n // typed placeholder (#4154).\n notify_inline: false,\n owner_scoped_config_keys: [],\n default_config: null,\n config_schema: {\n type: 'object',\n properties: {\n title: { type: 'string', label: 'Heading', description: 'Heading shown above the capture area' },\n description: { type: 'string', label: 'Description', description: 'Body text shown below the heading' },\n camera_facing: {\n type: 'string',\n enum: ['user', 'environment'],\n default: 'user',\n label: 'Phone camera default',\n description: 'Where the camera opens on phones - respondents can still switch',\n enumLabels: { user: 'Front (selfie)', environment: 'Rear' },\n },\n // The respondent's buttons (see cameraCaptureSources): Take a photo /\n // Record a video from camera_capture, Choose from library from\n // allow_library_upload accepting allowed_capture. At least one button\n // stays on (the builder enforces it).\n allowed_capture: {\n type: 'array',\n items: { type: 'string', enum: ['photo', 'video'] },\n default: ['photo'],\n label: 'Library accepts',\n // Existing nodes have no value and stay photo-only (the default). Also\n // the camera buttons while camera_capture is unset.\n description: 'What respondents can pick from their library - photos, videos, or both.',\n enumLabels: { photo: 'Photos', video: 'Videos' },\n },\n // Absent = allowed_capture, so existing nodes keep a camera button per type.\n camera_capture: {\n type: 'array',\n items: { type: 'string', enum: ['photo', 'video'] },\n label: 'Camera buttons',\n description: 'Which camera buttons respondents get - take a photo, record a video, or both',\n },\n allow_library_upload: {\n type: 'boolean',\n default: true,\n label: 'Library button',\n description: 'Whether respondents can pick existing photos or videos from their device',\n },\n // Display order of the three capture buttons respondents see. Lists all\n // three, enabled or not, so a disabled tile keeps its slot (Open's\n // `formats` model). The enable flags stay allowed_capture /\n // allow_library_upload; existing nodes have no value and keep today's order.\n capture_order: {\n type: 'array',\n items: { type: 'string', enum: ['photo', 'video', 'library'] },\n default: ['photo', 'video', 'library'],\n // Labels the builder's button tile row, which the creator toggles and\n // drags to set this order.\n label: 'Respondents can',\n description: 'The buttons respondents get. Turn each on or off, and drag to set their order.',\n enumLabels: { photo: 'Take a photo', video: 'Record a video', library: 'Choose from library' },\n },\n // Same meaning and 20 cap as file_upload's max_files (a cap on the\n // `files` array). Default 1 keeps every existing node single-capture (#3737).\n max_files: {\n type: 'number',\n min: 1,\n max: 20,\n default: 1,\n label: 'Media items',\n shortLabel: 'Max',\n description: 'How many photos or videos one answer can hold (1 = a single capture). Set Max above 1 to also set a minimum.',\n },\n // Clamped to <= max_files by the builder; enforced client-side like max_files.\n min_files: {\n type: 'number',\n min: 1,\n max: 20,\n default: 1,\n label: 'Minimum media items',\n shortLabel: 'Min',\n description: 'Fewest photos or videos a respondent must add before continuing',\n },\n allow_skip: {\n type: 'boolean',\n feature: 'optional_questions',\n default: false,\n label: 'Optional',\n description: 'Respondents can skip this question without adding a photo or video',\n },\n },\n },\n // Reuses file_upload's response shape verbatim (array of 1..max_files files) so\n // Results/exports/webhooks treat it the same way (scaffold skill: shape reuse).\n // A video submission carries a video mime_type - the shape doesn't change (#2759).\n response_schema: {\n type: 'object',\n required: ['files'],\n properties: {\n files: {\n type: 'array',\n items: {\n type: 'object',\n required: ['id', 'name', 'storage_path', 'url', 'mime_type', 'size', 'uploaded_at'],\n properties: {\n id: { type: 'string', format: 'uuid', description: 'Unique file identifier' },\n url: { type: 'string', format: 'uri', description: 'Signed Supabase Storage URL for download' },\n name: { type: 'string', description: 'Original filename' },\n size: { type: 'integer', minimum: 1, description: 'File size in bytes' },\n mime_type: { type: 'string', description: 'File MIME type (image/* or video/*)' },\n uploaded_at: { type: 'string', format: 'date-time', description: 'ISO timestamp of upload completion' },\n storage_path: { type: 'string', description: 'Bucket-prefixed storage path: respondent-captures/workspace_id/form_id/session_id/uuid.ext' },\n width: { type: 'number', description: 'Displayed pixel width, when the browser could read it (#5125)' },\n height: { type: 'number', description: 'Displayed pixel height, when the browser could read it (#5125)' },\n duration: { type: 'number', description: 'Video duration in seconds, when readable (#5125)' },\n // Viewer-written for a video recorded without the on-device 9:16 crop (#5253); the camera\n // video processor validates it and crops the playback copy server-side.\n preview_crop: {\n type: 'object',\n description: 'What the viewfinder showed (stream and preview box sizes); untrusted, validated server-side',\n properties: {\n stream_width: { type: 'number' },\n stream_height: { type: 'number' },\n preview_width: { type: 'number' },\n preview_height: { type: 'number' },\n },\n },\n // Server-written by the camera video processor (#5114); stripped from client input.\n thumbnail_storage_path: { type: 'string', description: 'Poster frame (webp) of a video, bucket-prefixed' },\n playback_storage_path: { type: 'string', description: 'Browser-safe H.264/AAC mp4 copy of a video, when the original is not one' },\n processed_at: { type: 'string', description: 'When the video was processed' },\n processing_attempts: { type: 'integer', description: 'Failed processing attempts so far' },\n processing_failed_at: { type: 'string', description: 'Set once processing gave up' },\n },\n },\n minItems: 1,\n maxItems: 20,\n description: 'The captured photos and videos, in capture order (1 to max_files items, mirroring file_upload)',\n },\n },\n },\n output_schema: {\n type: 'object',\n required: ['node_type'],\n properties: {\n node_type: { type: 'string', const: 'camera' },\n files: {\n type: 'array',\n description: 'The captured photos and videos in capture order, each as a canonical media object with a fresh signed link.',\n items: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Unique file identifier' },\n filename: { type: 'string', description: 'Original filename' },\n content_type: { type: 'string', description: 'File MIME type' },\n size: { type: 'integer', description: 'File size in bytes' },\n uploaded_at: { type: 'string', format: 'date-time', description: 'ISO timestamp of upload completion' },\n url: { type: 'string', format: 'uri', description: 'Direct, time-limited signed link (~48h, supports HTTP range)' },\n download_url: { type: 'string', format: 'uri', description: 'Same link with a forced download (Content-Disposition: attachment)' },\n expires_at: { type: 'string', format: 'date-time', description: 'When url/download_url stop working' },\n },\n },\n },\n },\n },\n },\n // Phase 1 of the variables engine (#4104, this node #4105): routes the\n // flow on a generic built-in Number (internally `score`, derived from\n // node_options.score -> ScoreState.cumulativeScore - see ROUTABLE_VARIABLES\n // in logic-types.js). Response-less and screen-less - the viewer evaluates\n // it transparently (no render) and continues to the matching branch. Each\n // branch is a node_options row (has_options:true); the branch edge is a\n // `jump` action anchored by the option's id (LogicAction.option_id).\n conditional: {\n label: 'If / then',\n shorthand: 'If',\n icon: 'Split',\n color: '#E0E7FF',\n description: 'Route the flow to different branches based on a score, max score, or category variable.',\n category: 'logic',\n sort_order: 12,\n has_options: true,\n min_options: 2,\n max_options: 10,\n max_option_length: 40,\n is_terminal: false,\n show_nav_bar: false,\n loading: 'eager',\n supports_prompt: false,\n supports_media: false,\n is_system: false,\n show_in_results: false,\n pii: false,\n respondent_media: null,\n // Logic/routing node - no respondent answer to render in a channel\n // notification, same as the other control nodes (redirect, link_list,\n // end_screen). Required by the #4154 notify_inline invariant.\n notify_inline: false,\n owner_scoped_config_keys: [],\n default_config: {\n options: [\n { content: 'Branch 1' },\n { content: 'Else' },\n ],\n },\n config_schema: null,\n response_schema: null,\n output_schema: null,\n },\n payment: {\n label: 'Payment',\n shorthand: 'Payment',\n icon: 'CreditCard',\n color: '#E9D5FF',\n description: 'Collect a payment from respondents inline, charged to a connected Stripe account',\n category: 'action',\n sort_order: 9,\n has_options: false,\n is_terminal: false,\n show_nav_bar: true,\n loading: 'lazy',\n supports_prompt: false,\n supports_media: false,\n is_system: false,\n show_in_results: true,\n pii: true,\n respondent_media: null,\n // Config keys that are owner-scoped to the authoring workspace - a connected\n // account (Stripe/etc via workspace_integrations), the owner's own uploaded\n // files, or a calendar link - and so must NOT survive a cross-workspace copy\n // (#4619/#4617/#4618/#4620 generalised this from the payment-only\n // connection_config_keys). The SoT for save_form's strip. The publish gate's\n // own showcase waiver (graph-validation.js) still names workspace_integration_id\n // directly since it's the only per-type check today.\n owner_scoped_config_keys: ['workspace_integration_id'],\n // Unclaimed anonymous-MCP forms may not go live with this node (#4847; derived into ANON_MCP_BLOCKED_NODE_TYPES).\n blocked_for_anon_mcp: true,\n // A payment confirmation line is the whole point of a notification for\n // this node type - always inline (#4154).\n notify_inline: true,\n default_config: { amount: null, currency: 'usd', provider: 'stripe' },\n config_schema: {\n type: 'object',\n required: ['amount', 'currency', 'provider'],\n properties: {\n amount: { type: 'number', label: 'Amount (in cents)', minimum: 50, required: true, description: 'Payment amount in cents (e.g., 5000 = $50.00)' },\n currency: { enum: ['usd', 'eur', 'gbp', 'cad', 'aud'], type: 'string', label: 'Currency', default: 'usd', required: true, description: 'Three-letter ISO currency code' },\n provider: { enum: ['stripe', 'paddle'], type: 'string', label: 'Payment Provider', default: 'stripe', required: true, description: 'Payment provider to use' },\n workspace_integration_id: { type: 'string', label: 'Workspace Integration ID', description: 'UUID of the workspace_integrations record for the connected payment account' },\n // Capped (#3940): they share a row with the amount in the viewer's order summary.\n title: { type: 'string', label: 'Heading', maxLength: 60, description: 'Heading shown above the order summary', anon_locked_keep: true },\n description: { type: 'string', label: 'Description', maxLength: 140, description: 'Body text shown below the heading in the order summary', anon_locked_keep: true },\n },\n description: 'Payment configuration with provider-agnostic flat structure',\n },\n response_schema: {\n type: 'object',\n oneOf: [\n {\n required: ['stripe'],\n properties: {\n stripe: {\n type: 'object',\n required: ['payment_intent_id', 'status', 'amount', 'currency'],\n properties: {\n name: { type: 'string', description: 'Customer name from Stripe billing details' },\n email: { type: 'string', format: 'email', description: 'Customer email from Stripe billing details' },\n phone: { type: 'string', description: 'Customer phone from Stripe billing details' },\n address: {\n type: 'object',\n description: 'Customer billing address from Stripe (only non-null parts present)',\n properties: {\n line1: { type: 'string' },\n line2: { type: 'string' },\n city: { type: 'string' },\n state: { type: 'string' },\n postal_code: { type: 'string' },\n country: { type: 'string', description: 'Two-letter ISO country code' },\n },\n },\n amount: { type: 'number', description: 'Payment amount in cents' },\n status: { enum: ['pending', 'succeeded', 'failed', 'partially_refunded', 'refunded'], type: 'string', description: 'Payment status, re-derived from the charge on every webhook sync' },\n amount_refunded: { type: 'number', description: 'Amount refunded so far, in cents. Only present once a refund (full or partial) has been issued' },\n currency: { type: 'string', description: 'Three-letter ISO currency code (e.g., usd, eur)' },\n payment_intent_id: { type: 'string', description: 'Stripe payment intent ID' },\n charge_id: { type: 'string', description: 'Stripe charge ID (ch_...) for reconciliation' },\n receipt_url: { type: 'string', format: 'uri', description: 'Stripe-hosted receipt page for this charge' },\n receipt_number: { type: 'string', description: 'Stripe receipt number (present once Stripe emails a receipt)' },\n balance_transaction: { type: 'string', description: 'Stripe balance transaction ID (txn_...) tying the charge to the payout ledger' },\n },\n },\n },\n },\n {\n required: ['square'],\n properties: {\n square: {\n type: 'object',\n properties: {\n amount: { type: 'number' },\n status: { type: 'string' },\n order_id: { type: 'string' },\n payment_id: { type: 'string' },\n },\n },\n },\n },\n {\n required: ['paddle'],\n properties: {\n paddle: {\n type: 'object',\n properties: {\n amount: { type: 'number' },\n status: { type: 'string' },\n order_id: { type: 'string' },\n checkout_id: { type: 'string' },\n },\n },\n },\n },\n ],\n description: 'Payment response with provider-specific data',\n },\n // The FINAL first-class emitted shape (#3796): transformResponse flattens the\n // stored `{ stripe: {...} }` into this provider-agnostic object. Must match\n // transformResponse's payment arm exactly, or validateOutput warns per row.\n // Card PAN/CVC are never present (only brand/last4 exist upstream).\n output_schema: {\n type: 'object',\n required: ['node_type', 'provider', 'status', 'amount', 'currency', 'payment_intent_id'],\n properties: {\n node_type: { type: 'string', const: 'payment' },\n provider: { type: 'string', const: 'stripe', description: 'Payment provider that processed the charge' },\n status: { enum: ['pending', 'succeeded', 'failed', 'partially_refunded', 'refunded'], type: 'string', description: 'Payment status, re-derived from the charge on every webhook sync' },\n amount: { type: 'number', description: 'Payment amount in cents' },\n amount_refunded: { type: 'number', description: 'Amount refunded so far, in cents. Only present once a refund (full or partial) has been issued' },\n currency: { type: 'string', description: 'Three-letter ISO currency code (e.g., usd, eur)' },\n payment_intent_id: { type: 'string', description: 'Stripe payment intent ID (pi_...)' },\n charge_id: { type: 'string', description: 'Stripe charge ID (ch_...) for reconciliation' },\n receipt_url: { type: 'string', format: 'uri', description: 'Stripe-hosted receipt page for this charge' },\n receipt_number: { type: 'string', description: 'Stripe receipt number (present once Stripe emails a receipt)' },\n customer: {\n type: 'object',\n description: 'Billing details the respondent entered at checkout (only non-null parts present)',\n properties: {\n name: { type: 'string', description: 'Customer name from Stripe billing details' },\n email: { type: 'string', format: 'email', description: 'Customer email from Stripe billing details' },\n phone: { type: 'string', description: 'Customer phone from Stripe billing details' },\n address: {\n type: 'object',\n description: 'Customer billing address (only non-null parts present)',\n properties: {\n line1: { type: 'string' },\n line2: { type: 'string' },\n city: { type: 'string' },\n state: { type: 'string' },\n postal_code: { type: 'string' },\n country: { type: 'string', description: 'Two-letter ISO country code' },\n },\n },\n },\n },\n },\n },\n },\n binary: {\n label: 'Binary',\n shorthand: 'A/B',\n icon: 'CircleCheck',\n color: '#DBEAFE',\n description: 'Two-option choice - yes/no, true/false, or this vs that',\n category: 'input',\n sort_order: 1.5,\n has_options: true,\n min_options: 2,\n max_options: 2,\n max_option_length: 12,\n is_terminal: false,\n show_nav_bar: true,\n loading: 'eager',\n supports_prompt: true,\n supports_media: true,\n is_system: false,\n show_in_results: true,\n pii: false,\n respondent_media: null,\n // Short selected-option label - safe to render inline (#4154).\n notify_inline: true,\n owner_scoped_config_keys: [],\n default_config: {\n choice: { enable_branching: false },\n options: [\n { content: 'Yes' },\n { content: 'No' },\n ],\n },\n config_schema: {\n type: 'object',\n properties: {\n choice: {\n type: 'object',\n properties: {\n enable_branching: {\n type: 'boolean',\n label: 'Enable branching logic',\n default: true,\n description: 'Allow each option to have its own logic path.',\n },\n },\n },\n content_media_type: {\n enum: ['upload', 'recorded'],\n type: 'string',\n label: 'Content media type',\n description: 'How the node media was provided',\n },\n },\n },\n response_schema: {\n type: 'string',\n description: 'Selected option ID',\n },\n output_schema: {\n type: 'object',\n required: ['node_type', 'label', 'option_id'],\n properties: {\n node_type: { type: 'string', const: 'binary' },\n label: { type: 'string', description: 'Human-readable option label' },\n option_id: { type: 'string', format: 'uuid', description: 'Selected option UUID' },\n },\n },\n },\n button: {\n label: 'Button',\n shorthand: 'Button',\n icon: 'RectangleHorizontal',\n color: '#DBEAFE',\n description: 'Simple button for acknowledgment or navigation',\n category: 'input',\n sort_order: 3.5,\n has_options: true,\n min_options: 1,\n max_options: 1,\n max_option_length: 28,\n is_terminal: false,\n show_nav_bar: true,\n loading: 'eager',\n supports_prompt: true,\n supports_media: true,\n is_system: false,\n show_in_results: false,\n pii: false,\n respondent_media: null,\n // Short selected-option label - safe to render inline (#4154).\n notify_inline: true,\n owner_scoped_config_keys: [],\n default_config: { options: [{ content: 'Continue' }] },\n config_schema: {\n type: 'object',\n properties: {\n button_text: { type: 'string', label: 'Button text', default: 'Continue' },\n button_style: { enum: ['primary', 'secondary', 'outline'], type: 'string', label: 'Button style', default: 'primary' },\n },\n },\n response_schema: {\n type: 'string',\n description: 'Selected option ID',\n },\n output_schema: {\n type: 'object',\n required: ['node_type', 'label', 'option_id'],\n properties: {\n node_type: { type: 'string', const: 'button' },\n label: { type: 'string', description: 'Human-readable option label' },\n option_id: { type: 'string', format: 'uuid', description: 'Selected option UUID' },\n },\n },\n },\n redirect: {\n label: 'Redirect',\n shorthand: 'Redirect',\n icon: 'ExternalLink',\n color: '#FFEDD5',\n description: 'Redirect users to an external URL',\n category: 'end',\n sort_order: 997,\n has_options: false,\n is_terminal: true,\n show_nav_bar: false,\n loading: 'lazy',\n supports_prompt: false,\n supports_media: false,\n is_system: false,\n show_in_results: false,\n pii: false,\n respondent_media: null,\n // Terminal node - never appears in a completed submission's answers\n // (filtered by NON_COUNTABLE_FILTER); false is a no-op default.\n notify_inline: false,\n owner_scoped_config_keys: [],\n // Unclaimed anonymous-MCP forms may not go live with this node (#4847; derived into ANON_MCP_BLOCKED_NODE_TYPES).\n blocked_for_anon_mcp: true,\n default_config: { url: '', auto_redirect: true },\n config_schema: {\n type: 'object',\n properties: {\n url: { type: 'string', label: 'Redirect URL', placeholder: 'https://example.com', outbound_link: true },\n auto_redirect: { type: 'boolean', label: 'Auto-redirect', default: true, description: 'Automatically redirect to the URL instead of showing a button' },\n },\n },\n response_schema: {\n type: 'string',\n description: 'URL the user was redirected to',\n },\n output_schema: null,\n },\n link_list: {\n label: 'Link List',\n shorthand: 'Links',\n icon: 'ExternalLink',\n color: '#FFEDD5',\n description: 'Display a list of links for users to choose from',\n category: 'end',\n sort_order: 998,\n has_options: false,\n is_terminal: true,\n show_nav_bar: false,\n loading: 'lazy',\n supports_prompt: false,\n supports_media: false,\n is_system: false,\n show_in_results: false,\n pii: false,\n respondent_media: null,\n // Terminal node - never appears in a completed submission's answers\n // (filtered by NON_COUNTABLE_FILTER); false is a no-op default.\n notify_inline: false,\n owner_scoped_config_keys: [],\n // Unclaimed anonymous-MCP forms may not go live with this node (#4847; derived into ANON_MCP_BLOCKED_NODE_TYPES).\n blocked_for_anon_mcp: true,\n default_config: { links: [{ id: 'default', url: '', title: '', description: '', order: 0 }], auto_redirect: false },\n config_schema: {\n type: 'object',\n properties: {\n links: {\n type: 'array',\n items: {\n type: 'object',\n required: ['id', 'url'],\n properties: {\n id: { type: 'string' },\n url: { type: 'string', label: 'URL', placeholder: 'https://example.com', outbound_link: true },\n title: { type: 'string', label: 'Heading' },\n description: { type: 'string', label: 'Description' },\n order: { type: 'number', label: 'Sort order' },\n },\n },\n label: 'Links',\n minItems: 1,\n },\n auto_redirect: { type: 'boolean', label: 'Auto-redirect', default: false, description: 'Automatically redirect to the URL instead of showing a button' },\n },\n },\n response_schema: {\n type: 'string',\n description: 'URL of the link that was clicked',\n },\n output_schema: null,\n },\n file_download: {\n label: 'File Download',\n shorthand: 'Download',\n icon: 'Download',\n color: '#E9D5FF',\n description: 'Provide a file for respondents to download',\n category: 'action',\n sort_order: 11,\n has_options: false,\n is_terminal: false,\n show_nav_bar: true,\n loading: 'lazy',\n supports_prompt: false,\n supports_media: false,\n is_system: false,\n show_in_results: true,\n pii: false,\n respondent_media: null,\n // Files, not a flat value - a notification renders a typed placeholder (#4154).\n notify_inline: false,\n // The owner's own uploaded files (#4617) - stripped on cross-workspace\n // copy so a forked node can't keep serving the source workspace's files;\n // the publish gate's \"No files uploaded\" check then forces a fresh upload.\n owner_scoped_config_keys: ['files'],\n // Unclaimed anonymous-MCP forms may not go live with this node (#4847; derived into ANON_MCP_BLOCKED_NODE_TYPES).\n blocked_for_anon_mcp: true,\n default_config: null,\n config_schema: {\n type: 'object',\n properties: {\n files: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n file_name: { type: 'string', label: 'Original file name', required: true },\n display_name: { type: 'string', label: 'Friendly name shown to respondents' },\n file_path: { type: 'string', label: 'File path in storage', required: true },\n file_size: { type: 'number', label: 'File size in bytes' },\n mime_type: { type: 'string', label: 'MIME type' },\n },\n },\n label: 'Downloadable files',\n },\n button_text: { type: 'string', label: 'Continue button text', default: 'Continue' },\n description: { type: 'string', label: 'Description text', anon_locked_keep: true },\n },\n },\n response_schema: {\n type: 'object',\n required: ['files'],\n properties: {\n files: {\n type: 'array',\n items: {\n type: 'object',\n required: ['file_path', 'file_name', 'downloaded_at'],\n properties: {\n file_name: { type: 'string', description: 'Display name of the file' },\n file_path: { type: 'string', description: 'Storage path of the downloaded file' },\n downloaded_at: { type: 'string', format: 'date-time', description: 'Timestamp when download was initiated' },\n },\n },\n description: 'List of files downloaded by respondent',\n },\n },\n },\n output_schema: {\n type: 'object',\n required: ['node_type'],\n properties: {\n node_type: { type: 'string', const: 'file_download' },\n files: {\n type: 'array',\n description: 'The files the respondent downloaded, each a canonical media object with a fresh signed link.',\n items: {\n type: 'object',\n properties: {\n filename: { type: 'string', description: 'Original filename' },\n content_type: { type: 'string', description: 'File MIME type' },\n downloaded_at: { type: 'string', format: 'date-time', description: 'Timestamp when download was initiated' },\n url: { type: 'string', format: 'uri', description: 'Direct, time-limited signed link (~48h, supports HTTP range)' },\n download_url: { type: 'string', format: 'uri', description: 'Same link with a forced download (Content-Disposition: attachment)' },\n expires_at: { type: 'string', format: 'date-time', description: 'When url/download_url stop working' },\n },\n },\n },\n },\n },\n },\n shopping: {\n label: 'Shopping',\n shorthand: 'Shop',\n icon: 'ShoppingBag',\n color: '#E9D5FF',\n description: 'Product recommendations with direct checkout',\n category: 'action',\n sort_order: 10,\n has_options: false,\n is_terminal: true,\n show_nav_bar: true,\n loading: 'lazy',\n supports_prompt: false,\n supports_media: false,\n is_system: false,\n show_in_results: false,\n pii: false,\n respondent_media: null,\n // No response_schema - never carries a flat answer value; false is a no-op default.\n notify_inline: false,\n owner_scoped_config_keys: [],\n default_config: { provider: 'shopify', cta_mode: 'checkout', source_mode: 'manual' },\n config_schema: {\n type: 'object',\n required: ['provider', 'cta_mode'],\n properties: {\n title: { type: 'string', label: 'Heading', description: 'Heading shown above the product list' },\n description: { type: 'string', label: 'Description', description: 'Body text shown below the heading' },\n provider: { enum: ['shopify'], type: 'string', label: 'Provider', default: 'shopify', description: 'Ecommerce provider' },\n workspace_integration_id: { type: 'string', label: 'Workspace Integration ID', description: 'UUID of the workspace_integrations record for the connected store' },\n cta_mode: { enum: ['checkout', 'add_to_cart'], type: 'string', label: 'CTA Mode', default: 'checkout', description: 'Whether to go to checkout or add to cart' },\n source_mode: { enum: ['manual', 'collection'], type: 'string', label: 'Product source', default: 'manual', description: 'How products are selected: manually picked or from a collection' },\n collection_id: { type: 'string', label: 'Collection ID', description: 'Shopify collection GID (when source_mode is collection)' },\n collection_title: { type: 'string', label: 'Collection title', description: 'Display name of the selected collection' },\n products: {\n type: 'array',\n label: 'Selected Products',\n description: 'Products to show (static mode)',\n items: {\n type: 'object',\n properties: {\n product_id: { type: 'string', description: 'Shopify product GID' },\n variant_id: { type: 'string', description: 'Shopify variant GID' },\n title: { type: 'string' },\n handle: { type: 'string' },\n image_url: { type: 'string' },\n price: { type: 'string' },\n currency: { type: 'string' },\n recommended: { type: 'boolean', default: true, description: 'Pre-ticked in viewer' },\n },\n },\n },\n product_mappings: {\n type: 'array',\n label: 'Score-based product mappings',\n description: 'Map score ranges to different product sets. First matching range wins.',\n items: {\n type: 'object',\n required: ['min', 'max'],\n properties: {\n min: { type: 'integer', label: 'Minimum score (inclusive)' },\n max: { type: 'integer', label: 'Maximum score (inclusive)' },\n message: { type: 'string', label: 'Message' },\n products: { type: 'array', description: 'Products for this score range' },\n },\n },\n },\n },\n description: 'Shopping configuration with provider-agnostic structure',\n },\n response_schema: null,\n output_schema: null,\n },\n end_screen: {\n label: 'Ending',\n shorthand: 'End',\n icon: 'Flag',\n color: '#FFEDD5',\n description: 'Final screen shown when form is completed',\n category: 'end',\n sort_order: 999,\n has_options: false,\n is_terminal: true,\n show_nav_bar: false,\n loading: 'eager',\n supports_prompt: false,\n supports_media: false,\n is_system: false,\n show_in_results: false,\n pii: false,\n respondent_media: null,\n // Terminal node - never appears in a completed submission's answers\n // (filtered by NON_COUNTABLE_FILTER); false is a no-op default.\n notify_inline: false,\n owner_scoped_config_keys: [],\n default_config: {\n title: 'Thank you!',\n message: 'Your response has been submitted.',\n },\n config_schema: {\n type: 'object',\n properties: {\n title: { type: 'string', label: 'Title', default: 'Thank you!', description: 'Heading shown on completion' },\n message: { type: 'string', label: 'Message', default: 'Your response has been submitted.', description: 'Message shown on completion' },\n show_score: { type: 'boolean', label: 'Show score', default: false, description: 'Display score on the end screen (e.g. \"You scored 4 out of 5\")' },\n icon: { type: 'string', label: 'Icon', enum: ['tick', 'trophy', 'star', 'crown', 'party', 'none'], default: 'tick', description: 'Icon shown above the title' },\n show_share_button: { type: 'boolean', label: 'Show share button', default: false, description: 'Show a share button above the CTA' },\n cta_type: { type: 'string', label: 'CTA type', enum: ['none', 'restart', 'external_link'], default: 'none', description: 'Primary call-to-action button type' },\n cta_text: { type: 'string', label: 'CTA button text', default: 'Continue', description: 'Button label for the CTA' },\n cta_url: { type: 'string', label: 'CTA URL', format: 'uri', description: 'URL to open (only for external_link CTA type)', placeholder: 'https://example.com', outbound_link: true },\n score_ranges: {\n type: 'array',\n label: 'Score-based content',\n description: 'Show different content based on cumulative score. First matching range wins.',\n items: {\n type: 'object',\n required: ['min', 'max', 'title'],\n properties: {\n min: { type: 'integer', label: 'Minimum score (inclusive)' },\n max: { type: 'integer', label: 'Maximum score (inclusive)' },\n title: { type: 'string', label: 'Title' },\n message: { type: 'string', label: 'Message' },\n },\n },\n },\n score_line: {\n type: 'string',\n label: 'Score line',\n feature: 'variables',\n description: 'Sentence shown with the score, with variable codes (e.g. \"You scored {{score}} out of 10\"). Replaces the default \"You scored X out of Y\" line.',\n },\n outcomes: {\n type: 'array',\n label: 'Variable-based results',\n feature: 'variables',\n description: 'Show different content based on a number variable. The first outcome whose range (inclusive) holds the variable value wins.',\n items: {\n type: 'object',\n required: ['variable_id', 'min', 'max', 'title'],\n properties: {\n variable_id: { type: 'string', label: 'Number variable id' },\n min: { type: 'number', label: 'Minimum (inclusive)' },\n max: { type: 'number', label: 'Maximum (inclusive)' },\n title: { type: 'string', label: 'Title' },\n message: { type: 'string', label: 'Message' },\n },\n },\n },\n scoring_results: {\n type: 'array',\n label: 'Category-based results',\n description: 'Results keyed by scoring category. The winning category (highest non-knocked-out score) determines which result is shown.',\n items: {\n type: 'object',\n required: ['category', 'title'],\n properties: {\n category: { type: 'string', label: 'Category key (must match keys used in option scores)' },\n title: { type: 'string', label: 'Title' },\n message: { type: 'string', label: 'Message' },\n cta_url: { type: 'string', label: 'CTA URL', format: 'uri', outbound_link: true },\n cta_text: { type: 'string', label: 'CTA button text' },\n },\n },\n },\n },\n },\n response_schema: null,\n output_schema: null,\n },\n};\n\n// Availability is derived from the FEATURES registry (single source of truth).\n// Each node type `x` maps to feature `node_x`; the throw below makes a missing\n// or renamed feature fail loudly at import, and a vitest guards the mapping.\nfor (const [type, def] of Object.entries(NODE_TYPES)) {\n const feature = FEATURES[`node_${type}`];\n if (!feature) {\n throw new Error(`NODE_TYPES.${type}: no matching FEATURES[\"node_${type}\"] entry`);\n }\n def.is_active = feature.enabled;\n}\n\n// A top-level config_schema property may carry `feature: '<FEATURES key>'`: the\n// key is available only while that feature is enabled. Author surfaces (MCP\n// summary + write tools, OpenAPI key list) read gatedConfigKeys; stored data is\n// never touched, so flipping the flag re-exposes the key. An unknown feature\n// name throws at import (same loud-failure pattern as the node_${type} mapping).\n// `enum_features: { <value>: '<FEATURES key>' }` gates single enum values the\n// same way (booking's `google_meet` provider while Calendly is live alone).\nexport function validateFeatureMarkers(nodeTypes, features) {\n for (const [type, def] of Object.entries(nodeTypes)) {\n for (const [key, prop] of Object.entries(def.config_schema?.properties ?? {})) {\n if (prop.feature !== undefined && !features[prop.feature]) {\n throw new Error(`NODE_TYPES.${type}.config_schema.${key}: feature \"${prop.feature}\" is not in FEATURES`);\n }\n for (const [value, feature] of Object.entries(prop.enum_features ?? {})) {\n if (!prop.enum?.includes(value)) {\n throw new Error(`NODE_TYPES.${type}.config_schema.${key}: enum_features value \"${value}\" is not in its enum`);\n }\n if (!features[feature]) {\n throw new Error(`NODE_TYPES.${type}.config_schema.${key}: enum_features feature \"${feature}\" is not in FEATURES`);\n }\n }\n }\n }\n}\nvalidateFeatureMarkers(NODE_TYPES, FEATURES);\n\n/**\n * Enum values of `type`'s top-level config key `key` whose `enum_features`\n * marker is currently off. Evaluated on each call so a flag flip is honoured.\n */\nexport function gatedEnumValues(type, key) {\n const prop = NODE_TYPES[type]?.config_schema?.properties?.[key];\n return new Set(\n Object.entries(prop?.enum_features ?? {})\n .filter(([, feature]) => !FEATURES[feature]?.enabled)\n .map(([value]) => value)\n );\n}\n\n/** True when `config[key]` holds a gated enum value (see gatedEnumValues). */\nfunction holdsGatedEnumValue(type, key, value) {\n return typeof value === 'string' && gatedEnumValues(type, key).has(value);\n}\n\n/**\n * Top-level config keys of `type` whose `feature` marker is currently off.\n * Evaluated on each call so a flag flip is honoured.\n */\nexport function gatedConfigKeys(type) {\n const props = NODE_TYPES[type]?.config_schema?.properties ?? {};\n return new Set(\n Object.entries(props)\n .filter(([, prop]) => prop.feature !== undefined && !FEATURES[prop.feature]?.enabled)\n .map(([key]) => key)\n );\n}\n\n/**\n * Drop gated keys from a caller-supplied config, and any key set to a gated\n * enum value. Returns a new object (never mutates - default_config is shared)\n * plus the dropped key names.\n */\nexport function stripGatedConfigKeys(type, config) {\n if (!config || typeof config !== 'object') return { config, dropped: [] };\n const gated = gatedConfigKeys(type);\n const isGated = ([k, v]) => gated.has(k) || holdsGatedEnumValue(type, k, v);\n const dropped = Object.entries(config).filter(isGated).map(([k]) => k);\n if (dropped.length === 0) return { config, dropped };\n return { config: Object.fromEntries(Object.entries(config).filter((e) => !isGated(e))), dropped };\n}\n\n// Derived exports\n\n/** Sorted list of all node types with their type key included */\nexport const NODE_TYPES_LIST = Object.entries(NODE_TYPES)\n .map(([type, def]) => ({ type, ...def }))\n .sort((a, b) => a.sort_order - b.sort_order);\n\n/**\n * Node types the dashboard treats as active, as full definitions - the single\n * owner of the derivation previously inlined in NodeTypesProvider. A type is\n * active when it is globally active OR the company is allowlisted to dogfood it\n * ahead of the global flip. Mirrors the old dashboard filter exactly: system\n * nodes (e.g. `start`, which is is_active) stay in, so getNodeType('start')\n * still resolves its colour - the node picker filters `is_system` separately.\n * Pass no companyId for the plain globally-active set.\n */\nexport function getActiveNodeTypes(companyId) {\n return NODE_TYPES_LIST.filter(\n t => t.is_active || companyHasNodeType(companyId, t.type)\n );\n}\n\n/**\n * Active, non-system node type KEYS - the user-addable set consumed by the API\n * and MCP server. Derived from Object.entries(NODE_TYPES) (definition order) so\n * the list is byte-identical to the derivations it replaces, including the order\n * that surfaces in z.enum / validation error messages.\n */\nexport const ACTIVE_NODE_TYPES = Object.entries(NODE_TYPES)\n .filter(([, def]) => def.is_active && !def.is_system)\n .map(([type]) => type);\n\n/** All valid node type keys */\nexport const NODE_TYPE_KEYS = Object.keys(NODE_TYPES);\n\nconst END_SCREEN_ICON_SCHEMA = NODE_TYPES.end_screen.config_schema.properties.icon;\n\n/** The End Screen icons a creator can pick, in picker order (`none` shows no icon). */\nexport const END_SCREEN_ICONS = END_SCREEN_ICON_SCHEMA.enum;\n\n/**\n * The End Screen icon to show for a stored `config.icon` (#6077): the value\n * when the schema knows it, else the schema default. Stored data can hold an\n * off-schema value (null, a non-string, a retired name), so the viewer and the\n * builder picker both read through this instead of trusting the raw value.\n */\nexport function resolveEndScreenIcon(value) {\n return END_SCREEN_ICONS.includes(value) ? value : END_SCREEN_ICON_SCHEMA.default;\n}\n\n/**\n * Node types -> their owner_scoped_config_keys, for types that declare any\n * (non-empty). The SoT for save_form (cross-workspace copy, #2064 part 2,\n * generalised by #4619/#4617/#4618/#4620) to strip workspace-owner-scoped\n * refs from a copied node's config - derived like ACTIVE_NODE_TYPES so no\n * consumer hand-maintains a duplicate list. Does NOT cover\n * `details.consent_items[].document`, which is nested inside an array and\n * handled by a dedicated SQL rewrite instead.\n *\n * `owner_scoped_config_keys` is MANDATORY on every NODE_TYPES entry (`[]`\n * when nothing in that type's config is owner-scoped) - a fail-safe default\n * so a new node type can't silently inherit this bug class by omission.\n * Enforced by packages/config/test/owner-scoped-config-keys.test.js.\n */\nexport const OWNER_SCOPED_CONFIG_KEYS = Object.fromEntries(\n Object.entries(NODE_TYPES)\n .filter(([, def]) => Array.isArray(def.owner_scoped_config_keys) && def.owner_scoped_config_keys.length > 0)\n .map(([type, def]) => [type, def.owner_scoped_config_keys])\n);\n\n/** Response schemas keyed by node type */\nexport const RESPONSE_SCHEMAS = Object.fromEntries(\n Object.entries(NODE_TYPES).map(([k, v]) => [k, v.response_schema])\n);\n\n/** Config schemas keyed by node type */\nexport const CONFIG_SCHEMAS = Object.fromEntries(\n Object.entries(NODE_TYPES).map(([k, v]) => [k, v.config_schema])\n);\n\n/** Output schemas keyed by node type */\nexport const OUTPUT_SCHEMAS = Object.fromEntries(\n Object.entries(NODE_TYPES).map(([k, v]) => [k, v.output_schema])\n);\n\n/** Metadata subset used by viewer for layout decisions */\nexport const NODE_TYPE_METADATA = Object.fromEntries(\n Object.entries(NODE_TYPES).map(([k, v]) => [k, {\n supports_prompt: v.supports_prompt,\n supports_media: v.supports_media,\n is_terminal: v.is_terminal,\n show_nav_bar: v.show_nav_bar,\n category: v.category,\n loading: v.loading,\n interaction_fills_stage: v.interaction_fills_stage === true,\n }])\n);\n\n/** Terminal node type keys (is_terminal === true) */\nexport const TERMINAL_TYPES = Object.entries(NODE_TYPES)\n .filter(([, v]) => v.is_terminal)\n .map(([k]) => k);\n\n/** Node types excluded from counts (system + terminal) */\nexport const NON_COUNTABLE_TYPES = Object.entries(NODE_TYPES)\n .filter(([, v]) => v.is_system || v.is_terminal)\n .map(([k]) => k);\n\n/** Supabase .not() filter string for non-countable types */\nexport const NON_COUNTABLE_FILTER = `(${NON_COUNTABLE_TYPES.map(t => `\"${t}\"`).join(',')})`;\n\n/** Node types excluded from the aggregate Results charts */\nexport const RESULTS_EXCLUDED_TYPES = Object.entries(NODE_TYPES)\n .filter(([, v]) => !v.show_in_results)\n .map(([k]) => k);\n\n/** Node types whose answer is contact or payment data (`pii` flag). */\nexport const PII_NODE_TYPES = Object.entries(NODE_TYPES)\n .filter(([, v]) => v.pii)\n .map(([k]) => k);\n\n/** Node types that can hold respondent-uploaded or recorded media (`respondent_media` flag). */\nexport const RESPONDENT_MEDIA_NODE_TYPES = Object.entries(NODE_TYPES)\n .filter(([, v]) => v.respondent_media !== null)\n .map(([k]) => k);\n\n/** Node types whose answer is a `files` array of stored uploads (`respondent_media: 'files'`). */\nexport const FILE_ANSWER_NODE_TYPES = Object.entries(NODE_TYPES)\n .filter(([, v]) => v.respondent_media === 'files')\n .map(([k]) => k);\n\n/**\n * Node types excluded from the PUBLIC results portal on top of\n * `RESULTS_EXCLUDED_TYPES` (#2129): PII (contact details, booking details,\n * payment data) and\n * respondent media stored as files or drawings (file uploads, camera captures,\n * drawings) never leave the owner-only Results tab, even when a form's results\n * are shared publicly. Derived from the `pii` and `respondent_media` flags\n * (#5282). Recordings (`open`) are not listed: an open answer is usually text.\n * The `get_public_form_results` RPC mirrors this list in SQL (drift-gated by\n * `test/public-results-excluded-sql.test.js`); the API route applies it again\n * on the returned rows, and the public page applies it a third time.\n */\nexport const PUBLIC_RESULTS_EXCLUDED_TYPES = Object.entries(NODE_TYPES)\n .filter(([, v]) => v.pii || v.respondent_media === 'files' || v.respondent_media === 'drawing')\n .map(([k]) => k);\n\n/**\n * Node types that count as a step in the respondent-facing step counter (#488).\n * Only answer-collecting nodes count - the respondent thinks in questions\n * (\"3 of 5\"), not screens. Pure transitions (`button`) and terminals/start are\n * nav-bar or non-nav nodes that advance neither the current step nor the total.\n */\nconst NON_STEP_TYPES = new Set(['button']);\nexport const STEP_COUNTED_TYPES = Object.entries(NODE_TYPES)\n .filter(([k, v]) => v.show_nav_bar && !NON_STEP_TYPES.has(k))\n .map(([k]) => k);\n\n/**\n * Node types excluded from the per-response Responses table.\n * Defaults to the Results exclusions; a type can opt back IN for responses\n * with `show_in_responses: true` (e.g. contact - aggregate-meaningless but\n * actionable per-lead, #746).\n */\nexport const RESPONSES_EXCLUDED_TYPES = Object.entries(NODE_TYPES)\n .filter(([, v]) => !(v.show_in_responses ?? v.show_in_results))\n .map(([k]) => k);\n\n/** Check if a node type is terminal */\nexport function isTerminalType(type) {\n return NODE_TYPE_METADATA[type]?.is_terminal === true;\n}\n\n/** Check if a node type counts as a step in the respondent step counter (#488) */\nexport function countsAsStep(type) {\n return STEP_COUNTED_TYPES.includes(type);\n}\n\n\n/**\n * Node types an unclaimed anonymous-MCP form may NOT go live with (#4847):\n * phishing-capable (`redirect`, `link_list`, `file_download`, `payment`) and\n * `file_upload` (audio/video answers are allowed, arbitrary files wait for a\n * claim). Derived from the `blocked_for_anon_mcp` flag on NODE_TYPES - never\n * hardcode this list downstream.\n */\nexport const ANON_MCP_BLOCKED_NODE_TYPES = Object.entries(NODE_TYPES)\n .filter(([, v]) => v.blocked_for_anon_mcp === true)\n .map(([k]) => k);\n\n/**\n * Config fields that send a respondent to an outbound URL, derived from the\n * config_schema: a property flagged `outbound_link: true` is a rule \"non-empty\",\n * and a property whose `enum` offers `external_link` is a rule \"equals\n * external_link\". Paths use `[]` for array items. Together with\n * ANON_MCP_BLOCKED_NODE_TYPES this is what an unclaimed anonymous-MCP form may\n * not go live with (#4847): the end_screen CTA is the ending-node escape hatch.\n * @type {{ type: string, path: string[], kind: 'non_empty' | 'equals', value?: string }[]}\n */\nexport const ANON_MCP_OUTBOUND_LINK_RULES = (() => {\n const rules = [];\n const walk = (type, schema, path) => {\n if (!schema || typeof schema !== 'object') return;\n for (const [key, prop] of Object.entries(schema.properties ?? {})) {\n const next = [...path, key];\n if (prop.outbound_link === true) rules.push({ type, path: next, kind: 'non_empty' });\n if (Array.isArray(prop.enum) && prop.enum.includes('external_link')) {\n rules.push({ type, path: next, kind: 'equals', value: 'external_link' });\n }\n walk(type, prop, next);\n if (prop.items) walk(type, prop.items, [...next, '[]']);\n }\n // Union variants (booking's per-provider config) share the same path.\n for (const branch of [...(schema.oneOf ?? []), ...(schema.anyOf ?? [])]) walk(type, branch, path);\n };\n for (const [type, def] of Object.entries(NODE_TYPES)) walk(type, def.config_schema, []);\n return rules;\n})();\n\n/**\n * Per-field strip rules for NON-blocked node types on a live anonymous-workspace\n * form (#4847): every outbound-link destination (non-empty\n * ANON_MCP_OUTBOUND_LINK_RULES: end_screen cta_url + scoring_results[].cta_url)\n * plus every property flagged `anon_locked_file: true` (details\n * consent_items[].document - an outside file). A BLOCKED node type\n * (ANON_MCP_BLOCKED_NODE_TYPES) is not handled field by field: its whole config\n * is blanked (see stripAnonMcpLockedNode), so an undeclared url field can never\n * slip through. Derived from the config_schema markers - never hand-list these.\n * @type {{ type: string, path: string[] }[]}\n */\nexport const ANON_MCP_STRIPPED_FIELD_RULES = (() => {\n const rules = ANON_MCP_OUTBOUND_LINK_RULES.filter((r) => r.kind === 'non_empty' && !ANON_MCP_BLOCKED_NODE_TYPES.includes(r.type)).map(({ type, path }) => ({ type, path }));\n const walk = (type, schema, path) => {\n if (!schema || typeof schema !== 'object') return;\n for (const [key, prop] of Object.entries(schema.properties ?? {})) {\n const next = [...path, key];\n if (prop.anon_locked_file === true) rules.push({ type, path: next });\n walk(type, prop, next);\n if (prop.items) walk(type, prop.items, [...next, '[]']);\n }\n for (const branch of [...(schema.oneOf ?? []), ...(schema.anyOf ?? [])]) walk(type, branch, path);\n };\n for (const [type, def] of Object.entries(NODE_TYPES)) {\n if (!ANON_MCP_BLOCKED_NODE_TYPES.includes(type)) walk(type, def.config_schema, []);\n }\n return rules;\n})();\n\n/**\n * Plain display-text keys a BLOCKED node type keeps when its config is blanked on a\n * guest live form (#4847), so the creator's own heading survives on the locked step:\n * the TOP-LEVEL config_schema string properties flagged `anon_locked_keep: true`\n * (payment title/description, file_download description). Everything else - urls,\n * ids, providers, amounts, files, links - is dropped. Derived from the markers.\n * @type {Record<string, string[]>}\n */\nexport const ANON_MCP_KEPT_TEXT_KEYS = (() => {\n const out = {};\n for (const type of ANON_MCP_BLOCKED_NODE_TYPES) {\n const props = NODE_TYPES[type]?.config_schema?.properties ?? {};\n const keys = Object.entries(props)\n .filter(([, p]) => p && p.anon_locked_keep === true && p.type === 'string')\n .map(([k]) => k);\n if (keys.length > 0) out[type] = keys;\n }\n return out;\n})();\n\nfunction anonValuesAtPath(value, path) {\n if (path.length === 0) return [value];\n const [head, ...rest] = path;\n if (head === '[]') return Array.isArray(value) ? value.flatMap((v) => anonValuesAtPath(v, rest)) : [];\n if (value && typeof value === 'object') return anonValuesAtPath(value[head], rest);\n return [];\n}\n\nfunction blankAtPath(value, path) {\n if (path.length === 0) return '';\n const [head, ...rest] = path;\n if (head === '[]') return Array.isArray(value) ? value.map((v) => blankAtPath(v, rest)) : value;\n if (value && typeof value === 'object' && head in value) {\n return { ...value, [head]: blankAtPath(value[head], rest) };\n }\n return value;\n}\n\n/**\n * Does this node carry a locked step for an unclaimed anonymous workspace\n * (#4847)? ONE derivation shared by the payload strip and the claim lock, so\n * neither has its own list: a blocked node type, OR an outbound-link rule match,\n * OR a non-empty value at any ANON_MCP_STRIPPED_FIELD_RULES path (an outside file\n * such as a consent document). Whatever the strip removes, this detects.\n * @param {{ type: string, config?: unknown }} node\n */\nexport function isAnonMcpLockedNode(node) {\n if (!node || typeof node.type !== 'string') return false;\n if (ANON_MCP_BLOCKED_NODE_TYPES.includes(node.type)) return true;\n const isSet = (v) => (typeof v === 'string' ? v.trim() !== '' : v != null && v !== false);\n const outbound = ANON_MCP_OUTBOUND_LINK_RULES.some((rule) => {\n if (rule.type !== node.type) return false;\n return anonValuesAtPath(node.config, rule.path).some((v) => (rule.kind === 'equals' ? v === rule.value : isSet(v)));\n });\n if (outbound) return true;\n return ANON_MCP_STRIPPED_FIELD_RULES.some(\n (rule) => rule.type === node.type && anonValuesAtPath(node.config, rule.path).some(isSet),\n );\n}\n\n/**\n * The node as a guest live form may serve it. A BLOCKED node type has its config\n * reduced to ANON_MCP_KEPT_TEXT_KEYS (plain display text, so the locked step keeps its\n * heading) and nothing else. Any other\n * type has just its ANON_MCP_STRIPPED_FIELD_RULES fields blanked to \"\", keeping\n * the shape. Pure: returns the same node when nothing applies, never mutates.\n * @template T\n * @param {T & { type: string, config?: unknown }} node\n * @returns {T}\n */\nexport function stripAnonMcpLockedNode(node) {\n if (!node || typeof node.type !== 'string') return node;\n if (ANON_MCP_BLOCKED_NODE_TYPES.includes(node.type)) {\n // Keep only marked plain-text fields (and only if they are strings); drop everything else.\n const src = node.config && typeof node.config === 'object' ? node.config : {};\n const kept = {};\n for (const key of ANON_MCP_KEPT_TEXT_KEYS[node.type] ?? []) {\n if (typeof src[key] === 'string') kept[key] = src[key];\n }\n const same =\n node.config && typeof node.config === 'object' &&\n Object.keys(node.config).length === Object.keys(kept).length &&\n Object.keys(kept).every((k) => node.config[k] === kept[k]);\n return same ? node : { ...node, config: kept };\n }\n if (!node.config || typeof node.config !== 'object') return node;\n let config = node.config;\n for (const rule of ANON_MCP_STRIPPED_FIELD_RULES) {\n if (rule.type === node.type) config = blankAtPath(config, rule.path);\n }\n return config === node.config ? node : { ...node, config };\n}\n","/**\n * Recall (#5671, #5686): show a variable's value, or an earlier answer, inside node text with a\n * short code. One parser shared by the viewer, the dashboard, the API (\"used in\" scan) and the\n * share image.\n *\n * {{key}} a variable (or the quiz score)\n * {{answer:<node uuid>}} the answer the respondent gave to that step\n * {{answer:<node uuid>.<field>}} one field of a Details step (a CONTACT_FIELDS id or a custom field's uuid)\n * {{ref|fallback}} shown when the value is empty (1-60 characters, none of `{ } |` or a line\n * break, so there is no escaping: `{{points|}}` and `{{a|b}c}}` stay plain text)\n *\n * Capture 1 is the ref, capture 2 the fallback (undefined when there is none).\n */\nimport { VARIABLE_KEY_MAX_LENGTH, coerceVariableValue } from './variables.js';\n\n/** The longest fallback text a code carries. */\nexport const RECALL_FALLBACK_MAX_LENGTH = 60;\n\n/** How many characters a code counts as when text is measured for display (about one chip's width). */\nexport const RECALL_CHIP_DISPLAY_LENGTH = 10;\n\n/** The longest Details field id an answer code names. */\nexport const RECALL_FIELD_ID_MAX_LENGTH = 64;\n\nconst UUID = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';\nconst KEY = `[a-z][a-z0-9_]{0,${VARIABLE_KEY_MAX_LENGTH - 1}}`;\n// A Details field id is whatever the form stores (a CONTACT_FIELDS id, a custom field's uuid, or an id an API/MCP client\n// chose: `companyName`, `job-title`): any 1-64 characters except `.`, braces, `|` and whitespace. Defined ONCE, here.\nconst FIELD_ID = `[^.{}|\\\\s]{1,${RECALL_FIELD_ID_MAX_LENGTH}}`;\nconst ANSWER = `answer:(${UUID})(?:\\\\.(${FIELD_ID}))?`;\nconst REF = `answer:${UUID}(?:\\\\.${FIELD_ID})?|${KEY}`;\n\n/** Source of one recall code. Capture 1 is the ref (a variable key or an answer ref), capture 2 the optional fallback. */\nexport const RECALL_TOKEN_SOURCE = `\\\\{\\\\{(${REF})(?:\\\\|([^{}|\\\\r\\\\n]{1,${RECALL_FALLBACK_MAX_LENGTH}}))?\\\\}\\\\}`;\n\n/** Global matcher for recall codes. Stateful (`g`): use `new RegExp(RECALL_TOKEN_PATTERN)` or the helpers. */\nexport const RECALL_TOKEN_PATTERN = new RegExp(RECALL_TOKEN_SOURCE, 'g');\n\nconst ANSWER_REF = new RegExp(`^${ANSWER}$`);\nconst KEY_REF = new RegExp(`^${KEY}$`);\nconst WHOLE_TOKEN = new RegExp(`^${RECALL_TOKEN_SOURCE}$`);\n\n/**\n * A ref string as parts: `{ kind: 'variable', ref, key }` or `{ kind: 'answer', ref, nodeId, fieldId }` (`fieldId`\n * null unless a Details field). null for anything that is not a valid ref.\n */\nexport function parseRecallRef(ref) {\n if (typeof ref !== 'string') return null;\n const a = ANSWER_REF.exec(ref);\n if (a) return { kind: 'answer', ref, nodeId: a[1], fieldId: a[2] ?? null };\n if (KEY_REF.test(ref)) return { kind: 'variable', ref, key: ref };\n return null;\n}\n\n/** One whole `{{ref}}` or `{{ref|fallback}}` code as parts (`fallback` null when absent); null when it is not a valid code. */\nexport function parseRecallToken(token) {\n if (typeof token !== 'string') return null;\n const m = WHOLE_TOKEN.exec(token);\n if (!m) return null;\n const parsed = parseRecallRef(m[1]);\n return parsed ? { ...parsed, fallback: m[2] ?? null } : null;\n}\n\n/**\n * What a fallback input accepts: `{ } |` and line breaks removed, cut to 60 characters, so what is typed always fits the\n * grammar (no escaping). Trimming is the caller's choice.\n */\nexport function sanitizeRecallFallback(value) {\n return typeof value === 'string' ? value.replace(/[{}|\\r\\n]/g, '').slice(0, RECALL_FALLBACK_MAX_LENGTH) : '';\n}\n\n/**\n * The quiz keys that resolve in a `{{key}}` code without being custom variables, and the name the builder shows for each\n * (the chip and the `@` menu read this, so they can never drift).\n */\nexport const RECALL_RESERVED_LABELS = { score: 'Score', max_score: 'Max score' };\n\n/** A number without trailing zeros and at most 2 decimals; text as is; anything else blank. */\nexport function formatRecallValue(value) {\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) return '';\n return String(Math.round(value * 100) / 100);\n }\n if (typeof value === 'string') return value;\n return '';\n}\n\n/** Every distinct ref (variable key or answer ref) used in the text, in first-seen order. */\nexport function findRecallRefs(text) {\n if (typeof text !== 'string' || !text.includes('{{')) return [];\n const refs = [];\n for (const m of text.matchAll(new RegExp(RECALL_TOKEN_SOURCE, 'g'))) {\n if (!refs.includes(m[1])) refs.push(m[1]);\n }\n return refs;\n}\n\n/** Every distinct answer ref (`answer:<uuid>[.<field>]`) used in the text, in first-seen order. */\nexport function findRecallAnswerRefs(text) {\n return findRecallRefs(text).filter((r) => r.startsWith('answer:'));\n}\n\n/** Every distinct VARIABLE key used in the text, in first-seen order (answer refs are not keys; `{{points|0}}` uses `points`). */\nexport function findRecallKeys(text) {\n return findRecallRefs(text).filter((r) => !r.startsWith('answer:'));\n}\n\n/** True when the text holds a `{{key}}` code for exactly `key` (`{{answer:x}}`, `{{ptsx}}`, `{{PTS}}` do not match `pts`). */\nexport function textUsesRecallKey(text, key) {\n return findRecallKeys(text).includes(key);\n}\n\n/** True when the text recalls the answer of node `nodeId` (any of its fields). */\nexport function textUsesRecallAnswer(text, nodeId) {\n return findRecallAnswerRefs(text).some((r) => parseRecallRef(r)?.nodeId === nodeId);\n}\n\nfunction valueMatches(value, textTest) {\n if (typeof value === 'string') return textTest(value);\n if (Array.isArray(value)) return value.some((v) => valueMatches(v, textTest));\n if (value && typeof value === 'object') return Object.values(value).some((v) => valueMatches(v, textTest));\n return false;\n}\n\n/** True when any string anywhere inside the value (deep: arrays, objects) holds a `{{key}}` code. */\nexport function valueUsesRecallKey(value, key) {\n return valueMatches(value, (t) => textUsesRecallKey(t, key));\n}\n\n/** A node's respondent-facing text: its prompt, every string in its config (deep) and its live (not deleted) option labels. */\nfunction nodeTextMatches(node, textTest) {\n if (!node) return false;\n if (valueMatches(node.prompt, textTest) || valueMatches(node.config, textTest)) return true;\n return (Array.isArray(node.options) ? node.options : []).some((o) => !o?.deleted_at && valueMatches(o?.content, textTest));\n}\n\n/**\n * True when a node's respondent-facing text names `{{key}}`: its prompt, every string in its\n * config (deep) and its live (not deleted) option labels. The ONE scan behind the API's\n * Delete 409 (`used_in_text`) and the dashboard's disabled Delete.\n */\nexport function nodeUsesRecallKey(node, key) {\n return nodeTextMatches(node, (t) => textUsesRecallKey(t, key));\n}\n\n/** True when a node's respondent-facing text (same places as `nodeUsesRecallKey`) recalls the answer of node `nodeId`. */\nexport function nodeUsesRecallAnswer(node, nodeId) {\n return nodeTextMatches(node, (t) => textUsesRecallAnswer(t, nodeId));\n}\n\n/** Every distinct answer ref a node's text uses (same places as `nodeUsesRecallKey`), first-seen order. */\nexport function nodeRecallAnswerRefs(node) {\n const refs = [];\n nodeTextMatches(node, (t) => {\n for (const r of findRecallAnswerRefs(t)) if (!refs.includes(r)) refs.push(r);\n return false;\n });\n return refs;\n}\n\n/**\n * Text as segments: `{ text, recalled }`, where `recalled` is true for a value that replaced a code (so a surface can\n * bold it) and false for plain text. Same resolution rules as `interpolateRecall`, which is a join over this.\n * - A value that formats to '' shows the fallback, else blank (a blank value adds no segment).\n * - An answer ref always resolves (value, then fallback, then blank) and never shows its raw code.\n * - A variable key missing from `valuesByKey` stays as its raw code (plain text), unless the code has a fallback.\n */\nexport function interpolateRecallParts(text, valuesByKey) {\n if (typeof text !== 'string') return [];\n if (!text.includes('{{') || !valuesByKey) return text === '' ? [] : [{ text, recalled: false }];\n const parts = [];\n let last = 0;\n const push = (t, recalled) => {\n if (t === '') return;\n const prev = parts[parts.length - 1];\n if (prev && prev.recalled === recalled) prev.text += t;\n else parts.push({ text: t, recalled });\n };\n for (const m of text.matchAll(new RegExp(RECALL_TOKEN_SOURCE, 'g'))) {\n const [whole, ref, fallback] = m;\n push(text.slice(last, m.index), false);\n last = m.index + whole.length;\n const known = Object.hasOwn(valuesByKey, ref);\n if (!known && !ref.startsWith('answer:') && fallback === undefined) {\n push(whole, false);\n continue;\n }\n const value = known ? formatRecallValue(valuesByKey[ref]) : '';\n push(value !== '' ? value : (fallback ?? ''), true);\n }\n push(text.slice(last), false);\n return parts;\n}\n\n/**\n * Replace each code with its formatted value (see `interpolateRecallParts` for the rules).\n * Text with no `{{` is returned as the same string.\n */\nexport function interpolateRecall(text, valuesByKey) {\n if (typeof text !== 'string' || !text.includes('{{') || !valuesByKey) return text;\n return interpolateRecallParts(text, valuesByKey).map((p) => p.text).join('');\n}\n\n/**\n * How long text reads in the builder: each recall code counts as one chip (`RECALL_CHIP_DISPLAY_LENGTH`), not its stored\n * length (an answer chip is ~47 stored characters). For soft display limits only; hard limits count stored text.\n */\nexport function recallDisplayLength(text) {\n if (typeof text !== 'string') return 0;\n return text.replace(new RegExp(RECALL_TOKEN_SOURCE, 'g'), 'x'.repeat(RECALL_CHIP_DISPLAY_LENGTH)).length;\n}\n\nfunction optionsOf(node) {\n const list = node?.options ?? node?.node_options;\n return Array.isArray(list) ? list : [];\n}\n\n/**\n * The text an earlier answer shows when recalled. `responseData` is the answer as stored (an option id or ids, a\n * number, `{ response_type, text }`, `{ fields }`).\n * - choice / binary: the picked option labels in OPTION order, joined ', ' (the webhook `label`);\n * - scale: the number; open: typed text only (a recording is blank);\n * - details: the value of field `fieldId`;\n * - anything else: ''.\n */\nexport function recallAnswerText(node, responseData, fieldId) {\n if (!node || responseData === undefined || responseData === null) return '';\n if (node.type === 'choice' || node.type === 'binary') {\n const picked = new Set(Array.isArray(responseData) ? responseData : [responseData]);\n return optionsOf(node)\n .filter((o) => o && !o.deleted_at && picked.has(o.id) && typeof o.content === 'string')\n .map((o) => o.content)\n .join(', ');\n }\n if (node.type === 'scale') return typeof responseData === 'number' && Number.isFinite(responseData) ? String(responseData) : '';\n if (node.type === 'open') {\n return responseData.response_type === 'text' && typeof responseData.text === 'string' ? responseData.text : '';\n }\n if (node.type === 'details') {\n if (!fieldId || !Array.isArray(responseData.fields)) return '';\n const value = responseData.fields.find((f) => f?.id === fieldId)?.value;\n return typeof value === 'string' ? value : typeof value === 'number' ? String(value) : '';\n }\n return '';\n}\n\n/**\n * Values by key before anything is answered: each custom variable's base (a number\n * defaults to 0, text to blank) and a zero quiz total. For surfaces that show the\n * first screen with no respondent (the share image).\n */\nexport function startingRecallValues(variables) {\n const out = { score: 0, max_score: 0 };\n for (const v of Array.isArray(variables) ? variables : []) {\n if (!v || v.kind !== 'custom' || typeof v.key !== 'string') continue;\n const base = coerceVariableValue(v.type, v.base);\n out[v.key] = base !== undefined ? base : v.type === 'text' ? '' : 0;\n }\n return out;\n}\n","// @vid-master/config/validate\n// Shared JSON Schema validation for config and response data.\n// Supports: object, array, string, number, integer, boolean, oneOf, enum, min/max, minItems/maxItems.\n\nimport { NODE_TYPES, CONFIG_SCHEMAS, RESPONSE_SCHEMAS, OUTPUT_SCHEMAS } from './node-types.js';\n\n/**\n * Validate data against a JSON Schema subset.\n * @param {any} data\n * @param {Record<string, any>} schema\n * @returns {{ valid: boolean, errors: string[] }}\n */\nexport function validateAgainstSchema(data, schema) {\n const errors = [];\n\n if (data === null || data === undefined) {\n if (schema.required === true || (Array.isArray(schema.required) && schema.required.length > 0)) {\n errors.push('Value is required');\n }\n return { valid: errors.length === 0, errors };\n }\n\n // Const check (exact value match)\n if (schema.const !== undefined && data !== schema.const) {\n errors.push(`Expected value ${JSON.stringify(schema.const)}, got ${JSON.stringify(data)}`);\n return { valid: false, errors };\n }\n\n // Determine actual type\n const actualType = Array.isArray(data) ? 'array' : typeof data;\n\n // Type check\n if (schema.type) {\n if (schema.type === 'integer') {\n if (typeof data !== 'number' || !Number.isInteger(data)) {\n errors.push(`Expected type integer, got ${actualType}${typeof data === 'number' ? ' (non-integer)' : ''}`);\n return { valid: false, errors };\n }\n } else if (schema.type === 'array') {\n if (!Array.isArray(data)) {\n errors.push(`Expected type array, got ${actualType}`);\n return { valid: false, errors };\n }\n } else if (actualType !== schema.type) {\n errors.push(`Expected type ${schema.type}, got ${actualType}`);\n return { valid: false, errors };\n }\n }\n\n // Array validation\n if (Array.isArray(data) && (schema.type === 'array' || !schema.type)) {\n if (schema.minItems !== undefined && data.length < schema.minItems) {\n errors.push(`Array must have at least ${schema.minItems} item(s), got ${data.length}`);\n }\n if (schema.maxItems !== undefined && data.length > schema.maxItems) {\n errors.push(`Array must have at most ${schema.maxItems} item(s), got ${data.length}`);\n }\n if (schema.items) {\n for (let i = 0; i < data.length; i++) {\n const itemResult = validateAgainstSchema(data[i], schema.items);\n if (!itemResult.valid) {\n errors.push(`Item [${i}]: ${itemResult.errors.join(', ')}`);\n }\n }\n }\n }\n\n // oneOf for every data type except the typed-object case, which evaluates it\n // below (after `required`, keeping that branch's error order). Lets a schema\n // express \"string or array of strings\" (#151 choice answers).\n const isTypedObject = schema.type === 'object' && typeof data === 'object' && !Array.isArray(data);\n if (!isTypedObject && Array.isArray(schema.oneOf)) {\n const matched = schema.oneOf.some((sub) => validateAgainstSchema(data, sub).valid);\n if (!matched) {\n errors.push('Data does not match any of the allowed schemas (oneOf)');\n }\n }\n\n // Object validation\n if (isTypedObject) {\n // Required properties (array form)\n if (Array.isArray(schema.required)) {\n for (const key of schema.required) {\n if (!(key in data)) {\n errors.push(`Missing required property: ${key}`);\n }\n }\n }\n\n // oneOf\n if (Array.isArray(schema.oneOf)) {\n const matched = schema.oneOf.some((sub) => {\n const r = validateAgainstSchema(data, sub);\n return r.valid;\n });\n if (!matched) {\n errors.push('Data does not match any of the allowed schemas (oneOf)');\n }\n }\n\n // Validate known properties + reject unknown ones\n if (schema.properties) {\n for (const key in data) {\n if (schema.properties[key]) {\n const propResult = validateAgainstSchema(data[key], schema.properties[key]);\n if (!propResult.valid) {\n errors.push(`Property \"${key}\": ${propResult.errors.join(', ')}`);\n }\n } else if (!schema.additionalProperties) {\n errors.push(`Unknown property: \"${key}\"`);\n }\n }\n }\n }\n\n // String validation\n if (schema.type === 'string' && typeof data === 'string') {\n if (schema.enum && !schema.enum.includes(data)) {\n errors.push(`Value must be one of: ${schema.enum.join(', ')}`);\n }\n }\n\n // Number / integer validation (support both min/max and minimum/maximum)\n if ((schema.type === 'number' || schema.type === 'integer') && typeof data === 'number') {\n const lo = schema.minimum !== undefined ? schema.minimum : schema.min;\n const hi = schema.maximum !== undefined ? schema.maximum : schema.max;\n if (lo !== undefined && data < lo) {\n errors.push(`Value must be >= ${lo}`);\n }\n if (hi !== undefined && data > hi) {\n errors.push(`Value must be <= ${hi}`);\n }\n }\n\n return { valid: errors.length === 0, errors };\n}\n\n/**\n * Plain-language error when a choice node asks for Letters display with more\n * options than the Letters cap (#5411), else null. The A/B/C chips share one\n * row, so Letters stops at `choice.max_letters_options` while List takes the\n * full `max_options`. Shared by the API write routes and the MCP schemas so\n * the MCP never accepts what a route rejects.\n * @param {string} nodeType\n * @param {Record<string, any> | null | undefined} config effective node config\n * @param {number} count option count\n * @returns {string | null}\n */\nexport function lettersCapError(nodeType, config, count) {\n const typeDef = NODE_TYPES[nodeType];\n const cap = typeDef?.max_letters_options;\n if (cap === undefined || config?.option_display !== 'letters' || count <= cap) return null;\n return `Letters display works with up to ${cap} options, got ${count}. Use option_display \"list\" for up to ${typeDef.max_options}, or remove options.`;\n}\n\n/**\n * Plain-language error when an options count is over the node type's\n * `max_options` (#5434), else null. Split out of `validateOptions` so write\n * routes can enforce just the max rule (no min_options, Letters or length\n * checks) and `validateOptions` reports the identical message.\n * @param {string} nodeType\n * @param {number} count option count\n * @returns {string | null}\n */\nexport function maxOptionsError(nodeType, count) {\n const typeDef = NODE_TYPES[nodeType];\n if (typeDef?.max_options === undefined || count <= typeDef.max_options) return null;\n return `${nodeType} nodes allow at most ${typeDef.max_options} option(s), got ${count}`;\n}\n\n/**\n * Validate that a node's options array meets the requirements for its type.\n * Uses min_options / max_options from NODE_TYPES as the source of truth.\n * @param {string} nodeType\n * @param {Array<{ content: string }>} [options]\n * @param {Record<string, any> | null} [config] effective node config (for the Letters cap)\n * @returns {{ valid: boolean, errors: string[] }}\n */\nexport function validateOptions(nodeType, options, config) {\n const typeDef = NODE_TYPES[nodeType];\n if (!typeDef) {\n return { valid: false, errors: [`Unknown node type \"${nodeType}\"`] };\n }\n\n const errors = [];\n const count = Array.isArray(options) ? options.length : 0;\n\n if (typeDef.has_options && typeDef.min_options !== undefined && count < typeDef.min_options) {\n errors.push(`${nodeType} nodes require at least ${typeDef.min_options} option(s), got ${count}`);\n }\n\n const maxError = maxOptionsError(nodeType, count);\n if (maxError) errors.push(maxError);\n\n const lettersError = lettersCapError(nodeType, config, count);\n if (lettersError) errors.push(lettersError);\n\n if (typeDef.max_option_length !== undefined && Array.isArray(options)) {\n for (let i = 0; i < options.length; i++) {\n if (typeof options[i]?.content === 'string' && options[i].content.length > typeDef.max_option_length) {\n errors.push(`options[${i}].content must be ${typeDef.max_option_length} characters or fewer`);\n }\n }\n }\n\n return { valid: errors.length === 0, errors };\n}\n\n/**\n * Validate a node config against its CONFIG_SCHEMA.\n * @param {string} nodeType\n * @param {any} configData\n * @returns {{ valid: boolean, errors: string[] }}\n */\nexport function validateConfig(nodeType, configData) {\n const schema = CONFIG_SCHEMAS[nodeType];\n if (!schema) {\n return { valid: false, errors: [`No config schema found for type \"${nodeType}\"`] };\n }\n return validateAgainstSchema(configData, schema);\n}\n\n/**\n * Whether a node type collects a response at all, derived from RESPONSE_SCHEMAS\n * (never hand-enumerate a type list here). Terminal/system types like\n * `end_screen`, `shopping`, and `start` have no response schema - reaching one\n * is not a validation failure, it's a not-applicable case (#4097).\n * @param {string} nodeType\n * @returns {boolean}\n */\nexport function collectsResponse(nodeType) {\n return Boolean(RESPONSE_SCHEMAS[nodeType]);\n}\n\n/**\n * Validate a response against its RESPONSE_SCHEMA.\n * @param {string} nodeType\n * @param {any} responseData\n * @returns {{ valid: boolean, errors: string[] }}\n */\nexport function validateResponse(nodeType, responseData) {\n const schema = RESPONSE_SCHEMAS[nodeType];\n if (!schema) {\n return { valid: false, errors: [`No response schema found for type \"${nodeType}\"`] };\n }\n return validateAgainstSchema(responseData, schema);\n}\n\n/**\n * Validate an output against its OUTPUT_SCHEMA.\n * @param {string} nodeType\n * @param {any} outputData\n * @returns {{ valid: boolean, errors: string[] }}\n */\nexport function validateOutput(nodeType, outputData) {\n const schema = OUTPUT_SCHEMAS[nodeType];\n if (!schema) {\n return { valid: false, errors: [`No output schema for \"${nodeType}\"`] };\n }\n return validateAgainstSchema(outputData, schema);\n}\n","// @vid-master/config/form-types\n// Static form type definitions — single source of truth for all apps.\n// Workflow prose (step-by-step instructions) and craft guides remain in the\n// MCP server. This registry defines structural metadata only.\n\nimport { FEATURES } from './features.js';\nimport { NODE_TYPES } from './node-types.js';\n\nexport const FORM_TYPES = {\n quiz: {\n label: 'Quiz',\n description: 'Scored knowledge quiz with narrated video questions',\n sort_order: 1,\n category: 'assessment',\n aliases: ['trivia', 'test', 'exam'],\n variants: ['personality', 'comprehension', 'composition'],\n required_features: [],\n required_node_types: ['choice', 'end_screen'],\n default_media_style: 'video',\n guide_uri: 'clipform://guides/quiz',\n guide_description: 'Craft knowledge for writing engaging quizzes - difficulty curves, question psychology, narration style, scoring',\n discovery: [\n { key: 'topic', question: 'What topic or subject area?', fallback: 'General trivia', mode: 'all' },\n { key: 'question_count', question: 'How many questions?', fallback: '8', mode: 'all' },\n { key: 'media_style', question: 'Video with narration (recommended), images, or text only?', fallback: 'Video with narration', mode: 'full' },\n ],\n variant_discovery: {\n personality: [\n { key: 'topic', question: \"What's the theme? (Which X are you?)\", fallback: 'General personality', mode: 'all' },\n { key: 'categories', question: 'What outcome categories? (3-5 results)', fallback: 'Infer 4 categories from the theme', mode: 'full' },\n { key: 'question_count', question: 'How many questions?', fallback: '8', mode: 'all' },\n ],\n comprehension: [\n { key: 'source', question: \"What's the source material? (paste the transcript, document text, or notes)\", fallback: 'Ask the user to paste it in chat', mode: 'all' },\n { key: 'question_count', question: 'How many questions?', fallback: '8', mode: 'all' },\n { key: 'audience', question: \"Who's the audience? (kids, teens, adults)\", fallback: 'General adults', mode: 'full' },\n ],\n composition: [\n { key: 'topic', question: 'What topic? (flags, movies, geography, music...)', fallback: 'General trivia', mode: 'all' },\n { key: 'question_count', question: 'How many questions? (composition quizzes use ~1 node per question, plus one more for any optional reveal beat - 5-6 is the sweet spot)', fallback: '5', mode: 'all' },\n ],\n },\n variant_guide_uris: {\n personality: 'clipform://guides/quiz/personality',\n comprehension: 'clipform://guides/quiz/comprehension',\n composition: 'clipform://guides/quiz/composition',\n },\n variant_descriptions: {\n personality: 'Addendum for personality quizzes - category design, option weighting, outcome writing, no right/wrong answers',\n comprehension: 'Addendum for comprehension quizzes - writing questions from source material (transcript, document, notes), distractor design, audience adaptation',\n composition: 'Addendum for composition quizzes - guess formats built from rendered compositions: mechanic selection, the clue clip + answer feedback default (with an optional reveal payoff node), difficulty design',\n },\n prompt: { name: 'create-quiz', title: 'Create a Quiz', description: 'Build a scored knowledge quiz with narrated video questions' },\n },\n\n survey: {\n label: 'Survey',\n description: 'Feedback survey, NPS form, or research questionnaire',\n sort_order: 2,\n category: 'feedback',\n aliases: ['feedback', 'poll', 'nps', 'questionnaire'],\n variants: [],\n required_features: [],\n required_node_types: ['choice', 'open', 'end_screen'],\n default_media_style: 'text',\n guide_uri: 'clipform://guides/survey',\n guide_description: 'Craft knowledge for feedback surveys, NPS, and research forms - brevity, rating scales, respondent fatigue',\n discovery: [\n { key: 'topic', question: 'What are you measuring? (satisfaction, NPS, feedback on what?)', fallback: 'General satisfaction', mode: 'all' },\n { key: 'anonymous', question: 'Anonymous or identified responses?', fallback: 'Anonymous', mode: 'full' },\n ],\n variant_discovery: {},\n variant_guide_uris: {},\n variant_descriptions: {},\n prompt: { name: 'create-survey', title: 'Create a Survey', description: 'Build a feedback survey, NPS form, or research questionnaire' },\n },\n\n interview: {\n label: 'Interview',\n description: 'Async video interview, case study, or expert input collection',\n sort_order: 3,\n category: 'collection',\n aliases: ['case-study', 'callout'],\n variants: [],\n required_features: [],\n required_node_types: ['open', 'details', 'end_screen'],\n default_media_style: 'video',\n guide_uri: 'clipform://guides/interview',\n guide_description: 'Craft knowledge for building interview forms - warm-up pacing, open questions, consent, video responses',\n discovery: [\n { key: 'purpose', question: 'What are you collecting? (case studies, feedback, expert input)', fallback: 'General responses', mode: 'all' },\n { key: 'response_format', question: 'How should people respond? (video, audio, text, all)', fallback: 'All formats', mode: 'full' },\n { key: 'needs_consent', question: 'Need a consent statement?', fallback: 'Yes', mode: 'full' },\n ],\n variant_discovery: {},\n variant_guide_uris: {},\n variant_descriptions: {},\n prompt: { name: 'create-interview', title: 'Create an Interview', description: 'Build an async video interview for collecting case studies, feedback, or expert input' },\n },\n\n funnel: {\n label: 'Funnel',\n description: 'Lead qualification funnel with conditional routing',\n sort_order: 4,\n category: 'qualification',\n aliases: ['lead-gen', 'qualification', 'lead-magnet'],\n variants: [],\n required_features: ['branching', 'funnel'],\n required_node_types: ['choice', 'details', 'end_screen'],\n default_media_style: 'text',\n guide_uri: 'clipform://guides/funnel',\n guide_description: 'Craft knowledge for lead qualification funnels - planned feature, conditional routing coming soon',\n discovery: [],\n variant_discovery: {},\n variant_guide_uris: {},\n variant_descriptions: {},\n prompt: { name: 'create-funnel', title: 'Create a Funnel', description: 'Lead qualification funnels with branching logic are planned but not yet available' },\n },\n\n testimonial: {\n label: 'Testimonial',\n description: 'Video testimonial and story collection form',\n sort_order: 5,\n category: 'collection',\n aliases: ['story', 'review'],\n variants: [],\n required_features: [],\n required_node_types: ['open', 'details', 'end_screen'],\n default_media_style: 'video',\n guide_uri: 'clipform://guides/testimonial',\n guide_description: 'Craft knowledge for collecting testimonials and customer stories on video - storytelling prompts, comfort techniques, consent',\n discovery: [\n { key: 'use_case', question: 'What stories are you collecting? (customer success, employee, partner)', fallback: 'Customer success stories', mode: 'all' },\n { key: 'media_style', question: 'Video responses (recommended), audio, or text?', fallback: 'Video', mode: 'full' },\n ],\n variant_discovery: {},\n variant_guide_uris: {},\n variant_descriptions: {},\n prompt: { name: 'create-testimonial', title: 'Collect Testimonials', description: 'Build a video testimonial collection form - capture authentic customer stories on camera' },\n },\n\n application: {\n label: 'Application',\n description: 'Structured application form for jobs, programmes, or grants',\n sort_order: 6,\n category: 'collection',\n aliases: ['job-application', 'admission', 'enrollment', 'grant'],\n variants: [],\n required_features: [],\n required_node_types: ['open', 'choice', 'details', 'end_screen'],\n default_media_style: 'video',\n guide_uri: 'clipform://guides/application',\n guide_description: 'Craft knowledge for application and evaluation forms - multi-section structure, video responses for behavioural questions, screening',\n discovery: [\n { key: 'role', question: 'What role or position?', fallback: 'General application', mode: 'all' },\n ],\n variant_discovery: {},\n variant_guide_uris: {},\n variant_descriptions: {},\n prompt: { name: 'create-application', title: 'Create an Application Form', description: 'Build a structured application form with video responses for behavioural questions' },\n },\n\n booking: {\n label: 'Booking',\n description: 'Event registration, course signup, or booking form',\n sort_order: 7,\n category: 'registration',\n aliases: ['registration', 'signup', 'event', 'rsvp', 'workshop'],\n variants: [],\n required_features: [],\n required_node_types: ['details', 'choice', 'end_screen'],\n default_media_style: 'text',\n guide_uri: 'clipform://guides/booking',\n guide_description: 'Craft knowledge for event registration and booking forms - minimal friction, video welcome, confirmation flow',\n discovery: [\n { key: 'event_name', question: \"What's the event name?\", fallback: 'Event registration', mode: 'all' },\n { key: 'event_type', question: 'What type? (workshop, webinar, meetup, conference)', fallback: 'Event', mode: 'full' },\n ],\n variant_discovery: {},\n variant_guide_uris: {},\n variant_descriptions: {},\n prompt: { name: 'create-booking', title: 'Create a Booking Form', description: 'Build an event registration or booking form with a personal video welcome' },\n },\n\n intake: {\n label: 'Client Intake',\n description: 'Client intake and onboarding form for a service business',\n sort_order: 8,\n category: 'collection',\n aliases: ['client-intake', 'onboarding', 'enquiry', 'inquiry', 'new-client'],\n variants: [],\n required_features: [],\n required_node_types: ['details', 'open', 'end_screen'],\n default_media_style: 'video',\n guide_uri: 'clipform://guides/intake',\n guide_description: 'Craft knowledge for client intake and onboarding forms - a warm welcome, minimal contact capture, a video-first question about what the client needs, and a clear next step',\n discovery: [\n { key: 'use_case', question: 'What kind of business or service? (massage, coaching, personal training, agency)', fallback: 'General client intake', mode: 'all' },\n { key: 'response_format', question: 'How should people answer the open question? (video, audio, text, all)', fallback: 'All formats', mode: 'full' },\n ],\n variant_discovery: {},\n variant_guide_uris: {},\n variant_descriptions: {},\n prompt: { name: 'create-intake', title: 'Create a Client Intake Form', description: 'Build a warm client intake or onboarding form that captures contact details and what the client needs' },\n },\n\n 'lead-capture': {\n label: 'Lead Capture',\n description: 'Linear lead capture or enquiry form - turn interest into a contact with minimal friction',\n sort_order: 9,\n category: 'collection',\n aliases: ['lead', 'lead-form', 'enquiry-form', 'waitlist', 'get-a-quote'],\n variants: [],\n required_features: [],\n required_node_types: ['details', 'end_screen'],\n default_media_style: 'text',\n guide_uri: 'clipform://guides/lead-capture',\n guide_description: 'Craft knowledge for linear lead capture and enquiry forms - minimal friction, a light qualifier only if it routes follow-up, and a clear next step (no branching, no scoring)',\n discovery: [\n { key: 'use_case', question: 'What are you capturing leads for? (a service, a product, a waitlist, a quote)', fallback: 'General enquiries', mode: 'all' },\n ],\n variant_discovery: {},\n variant_guide_uris: {},\n variant_descriptions: {},\n prompt: { name: 'create-lead-capture', title: 'Create a Lead Capture Form', description: 'Build a short lead capture or enquiry form that turns interest into a contact' },\n },\n};\n\n// ---------------------------------------------------------------------------\n// Derived exports\n// ---------------------------------------------------------------------------\n\n// Availability is derived from dependencies (single source of truth): a form type\n// is active iff every required feature is enabled and every required node type is\n// active. No hand-set flag to drift - e.g. funnel auto-hides while branching is planned.\nfor (const def of Object.values(FORM_TYPES)) {\n const featuresLive = def.required_features.every((k) => FEATURES[k]?.enabled === true);\n const nodesLive = def.required_node_types.every((t) => NODE_TYPES[t]?.is_active === true);\n def.is_active = featuresLive && nodesLive;\n}\n\nexport const FORM_TYPES_LIST = Object.entries(FORM_TYPES)\n .map(([key, def]) => ({ key, ...def }))\n .sort((a, b) => a.sort_order - b.sort_order);\n\nexport const FORM_TYPE_KEYS = Object.keys(FORM_TYPES);\n\nexport const WORKFLOW_TYPES = FORM_TYPE_KEYS.filter(\n key => FORM_TYPES[key].is_active\n);\n\nexport const FORM_TYPE_ALIASES = Object.fromEntries(\n Object.entries(FORM_TYPES).flatMap(([key, def]) =>\n def.aliases.map(alias => [alias, key])\n )\n);\n\nexport const ALL_VARIANTS = Object.entries(FORM_TYPES).flatMap(\n ([, def]) => def.variants\n);\n\nexport function resolveFormType(input) {\n const normalised = input.toLowerCase().trim();\n if (FORM_TYPES[normalised]) return normalised;\n return FORM_TYPE_ALIASES[normalised] ?? null;\n}\n\nexport function getDiscoveryParams(formType, variant, mode = 'full') {\n const def = FORM_TYPES[formType];\n if (!def) return [];\n\n let params;\n if (variant && def.variant_discovery?.[variant]) {\n params = def.variant_discovery[variant];\n } else {\n params = def.discovery;\n }\n\n if (mode === 'demo') {\n return params.filter(p => p.mode === 'all');\n }\n return params;\n}\n\nexport function isFormTypeAvailable(formType, features) {\n const def = FORM_TYPES[formType];\n if (!def || !def.is_active) return false;\n return def.required_features.every(\n featureKey => features[featureKey]?.enabled === true\n );\n}\n\nexport function getAvailableFormTypes(features) {\n return FORM_TYPE_KEYS.filter(key => isFormTypeAvailable(key, features));\n}\n","/**\n * Anonymous-MCP safety floor limits (#4847). An \"unclaimed anonymous MCP\n * workspace\" is one linked via bot_linked_accounts(platform = 'mcp') whose\n * uid is still an anonymous Supabase user (apps/api/src/mcp/anon-workspace.ts).\n */\n\n/** Completed responses an unclaimed anonymous-MCP form accepts before the limit screen. */\nexport const ANON_MCP_RESPONSE_CAP = 3;\n\n/**\n * Started (viewed or in-progress) sessions are bounded at this multiple of the\n * cap, so abandoned sessions cannot be used for unlimited uploads. The cap is\n * enforced at session init, answer writes and completion, but the count is not\n * atomic: concurrent inits can briefly overshoot it (a strict cap needs a DB function).\n */\nexport const ANON_MCP_STARTED_SESSION_MULTIPLE = 5;\n\n/** Max started sessions per unclaimed anonymous-MCP form. */\nexport const ANON_MCP_STARTED_SESSION_CAP =\n ANON_MCP_RESPONSE_CAP * ANON_MCP_STARTED_SESSION_MULTIPLE;\n\n/** Days a live, unclaimed anonymous-MCP form stays published (matches the claim-link TTL). */\nexport const ANON_MCP_LIVE_TTL_DAYS = 7;\n\n/**\n * Upload sessions (stream-start / signed-url) one form session may open on an\n * unclaimed anonymous-MCP form. Best-effort and per API process only (not shared\n * across instances); the completed cap is the real bound.\n */\nexport const ANON_MCP_UPLOADS_PER_SESSION = 10;\n","// @vid-master/config/logic-chain\n// Pure, branch-aware graph helpers over node_logic actions - no DB, no React\n// Flow. Moved out of apps/api/src/lib/logic-chain.ts (#1058) so a single\n// implementation backs the DB-backed chain ops; apps/api re-exports these so\n// existing callers/imports are unchanged.\n//\n// The chain helpers historically read/wrote only `actions[0]`, which silently\n// orphaned every other edge on a branched node (#704). These pure functions\n// treat a node's logic as the multi-edge graph it is.\n\nimport { isOptionEdge, isInactiveOptionEdge } from './logic-types.js';\n\n/**\n * Distinct outgoing target node-ids from a node's actions, in action order.\n * When `node` is given, parked option edges (branching off) are skipped so the\n * walk follows only the ACTIVE graph; omit it to treat every edge as live.\n *\n * @param {import('./logic-types.js').LogicAction[] | undefined} actions\n * @param {import('./logic-types.js').BranchingNode} [node]\n * @returns {string[]}\n */\nexport function outgoingTargets(actions, node) {\n const out = [];\n for (const a of actions ?? []) {\n if (node && isInactiveOptionEdge(node, a)) continue;\n const v = a?.details?.to?.value;\n if (v && !out.includes(v)) out.push(v);\n }\n return out;\n}\n\n/**\n * A node is \"branched\" when its logic routes more than one way: per-option\n * (an option-typed condition var) or to more than one distinct target. A node\n * with no logic, or a single node-level jump, is linear. With `node` given, a\n * choice/binary node whose branching is off is linear (its parked option edges\n * don't count) even though the parked edges still exist in node_logic.\n *\n * @param {import('./logic-types.js').LogicAction[] | undefined} actions\n * @param {import('./logic-types.js').BranchingNode} [node]\n * @returns {boolean}\n */\nexport function isBranched(actions, node) {\n if (!actions || actions.length === 0) return false;\n const active = node ? actions.filter((a) => !isInactiveOptionEdge(node, a)) : actions;\n const routesByOption = active.some((a) => isOptionEdge(a));\n return routesByOption || outgoingTargets(active).length > 1;\n}\n\n/**\n * The default (fallback) target of a node: the target of its node-level action\n * (\"everything else -> X\"), else the first action's target, else null when the\n * node is a chain tail / terminal.\n *\n * @param {import('./logic-types.js').LogicAction[] | undefined} actions\n * @returns {import('./logic-types.js').LogicActionDetails['to'] | null}\n */\nexport function defaultTarget(actions) {\n if (!actions || actions.length === 0) return null;\n const nodeLevel = actions.find((a) => {\n const vars = a.condition?.vars;\n return !!vars && vars.length > 0 && vars.every((v) => v.type === 'node');\n });\n return (nodeLevel ?? actions[0])?.details?.to ?? null;\n}\n\n/**\n * Order nodes by BFS from the start node, following ALL outgoing edges (not\n * just the first). Unreachable nodes are appended in stable input order so the\n * caller still receives every node - branched forms used to come back\n * mis-ordered and missing whole branches.\n *\n * @template {{ id: string, type: string, config?: object }} T\n * @param {T[]} nodes\n * @param {Map<string, import('./logic-types.js').LogicAction[]>} logicByNode\n * @returns {T[]}\n */\nexport function bfsOrder(nodes, logicByNode) {\n const byId = new Map(nodes.map((n) => [n.id, n]));\n const ordered = [];\n const seen = new Set();\n\n const start = nodes.find((n) => n.type === 'start');\n if (start) {\n const queue = [start.id];\n while (queue.length) {\n const id = queue.shift();\n if (seen.has(id)) continue;\n seen.add(id);\n const node = byId.get(id);\n if (node) ordered.push(node);\n for (const target of outgoingTargets(logicByNode.get(id), node)) {\n if (!seen.has(target) && byId.has(target)) queue.push(target);\n }\n }\n }\n\n // Append anything the start can't reach (parked/draft branches) so the full\n // node set is always returned, reachable-first.\n for (const node of nodes) if (!seen.has(node.id)) ordered.push(node);\n return ordered;\n}\n\n/**\n * Rewrites for deleting `nodeId`: every action across every node that targets\n * it is re-pointed at the deleted node's default target, so no incoming edge is\n * left dangling. If the deleted node has no default target (it was a tail /\n * terminal), the incoming action is dropped instead. Returns only the entries\n * that changed.\n *\n * @param {Array<{ node_id: string, actions: import('./logic-types.js').LogicAction[] }>} allLogic\n * @param {string} nodeId\n * @returns {Array<{ node_id: string, actions: import('./logic-types.js').LogicAction[] }>}\n */\nexport function computeRemovalRewrites(allLogic, nodeId) {\n const target = defaultTarget(\n allLogic.find((e) => e.node_id === nodeId)?.actions\n );\n const changes = [];\n\n for (const entry of allLogic) {\n if (entry.node_id === nodeId) continue;\n let changed = false;\n const next = [];\n for (const action of entry.actions ?? []) {\n if (action?.details?.to?.value === nodeId) {\n changed = true;\n // Re-point to the deleted node's default target - unless there is no\n // default, or doing so would create a self-loop (a 2-cycle through the\n // deleted node), in which case drop the edge.\n if (target && target.value !== entry.node_id) {\n next.push({ ...action, details: { to: { ...target } } });\n }\n } else {\n next.push(action);\n }\n }\n if (changed) changes.push({ node_id: entry.node_id, actions: next });\n }\n return changes;\n}\n","// @vid-master/config/guide\n// Template walkthrough notes (#6269): a short note on a node of an outbound\n// template, shown as a builder tour step when someone opens their copy. The\n// note rides in `node.config.guide`, which save_form copies verbatim, so no\n// migration. Authoring is dark (FEATURES.template_walkthrough); `guide` is in\n// NO config_schema, so no public surface derived from those schemas names it.\n//\n// Shape: node.config.guide = { tour?: { title, body, anchor? }, intro?: { title, body }, checklist?: ChecklistItem[] }.\n// `intro` is the card shown before the first note (the first one in form order wins;\n// Start is read-only, so it goes on the first noted node). `checklist` (#6275) is the\n// copy's getting-started list, written per company. All three go through the same\n// merge and strip.\n\nimport { bfsOrder } from './logic-chain.js';\nimport { NODE_TYPES } from './node-types.js';\nimport { FEATURES } from './features.js';\nimport { INTEGRATION_CATALOG } from './integration-catalog.js';\n\nexport const GUIDE_CONFIG_KEY = 'guide';\n\nexport const GUIDE_LIMITS = Object.freeze({\n titleMax: 60,\n bodyMax: 280,\n maxTourSteps: 5,\n maxChecklistItems: 6,\n // The getting-started card is 288px wide and its rows wrap: about two lines each at these sizes (#6275).\n checklistLabelMax: 40,\n checklistDescriptionMax: 80,\n});\n\n/** `node`: the step points at its own node. `share`: the closing step points at the Share button. */\nexport const GUIDE_TOUR_ANCHORS = Object.freeze(['node', 'share']);\n\n/**\n * Named parts of a node a note can point at (#6286). The node card marks each with\n * `data-guide-section=\"<name>\"`. `media`, `prompt` and `body` come from the NODE_TYPES\n * flags; GUIDE_NODE_SECTIONS adds the type-specific ones.\n */\nexport const GUIDE_SECTIONS = Object.freeze(['media', 'prompt', 'body', 'formats', 'options']);\n\nexport const GUIDE_NODE_SECTIONS = Object.freeze({ open: Object.freeze(['formats']), choice: Object.freeze(['options']) });\n\n/** The sections a node type has, in card order. Unknown types and Start (no card body to point at) get none. */\nexport function guideSectionsFor(nodeType) {\n const def = NODE_TYPES[nodeType];\n if (!def || nodeType === 'start') return [];\n const sections = [];\n if (def.supports_media === true) sections.push('media');\n if (def.supports_prompt === true) sections.push('prompt');\n sections.push('body');\n return [...sections, ...(GUIDE_NODE_SECTIONS[nodeType] ?? [])];\n}\n\n/**\n * What a company checklist item can ask for (#6275). Each is an ACTIVATION_STEP_KINDS\n * entry the builder ticks from real state. `record_video` is about the node it sits on;\n * the others are workspace-wide, so they sit on any node (by convention the End screen).\n */\nexport const COMPANY_CHECKLIST_KINDS = Object.freeze(['record_video', 'preview', 'connect', 'go_live', 'claim_account']);\n\nconst GUIDE_KEYS = ['tour', 'intro', 'checklist'];\nconst TOUR_KEYS = ['title', 'body', 'anchor'];\nconst INTRO_KEYS = ['title', 'body'];\nconst CHECKLIST_ITEM_KEYS = ['kind', 'label', 'description', 'integration'];\n\n/**\n * Integrations a `connect` item may name: native, connected in-app, and globally live\n * (`integration_<slug>` enabled). An allowlist-only one is left out: a copy lives in\n * another workspace, where it would show Coming Soon.\n */\nexport function checklistConnectableIntegrations() {\n return Object.entries(INTEGRATION_CATALOG)\n .filter(([slug, def]) => def.kind === 'native' && def.feature === `integration_${slug}` && FEATURES[def.feature]?.enabled === true)\n .map(([slug]) => slug);\n}\n\nfunction isPlainObject(value) {\n return !!value && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction checkText(value, field, max) {\n if (typeof value !== 'string') return { error: `guide.${field} must be a string` };\n const text = value.trim();\n if (text.length === 0 || text.length > max) return { error: `guide.${field} must be 1 to ${max} characters` };\n return { text };\n}\n\n/** One tour note, trimmed. `anchor` is kept only when sent. */\nfunction validateTour(tour, nodeType) {\n if (!isPlainObject(tour)) return { ok: false, error: 'guide.tour must be an object with a title and a body' };\n const unknown = Object.keys(tour).find((k) => !TOUR_KEYS.includes(k));\n if (unknown) return { ok: false, error: `guide.tour supports only: ${TOUR_KEYS.join(', ')}` };\n const title = checkText(tour.title, 'tour.title', GUIDE_LIMITS.titleMax);\n if (title.error) return { ok: false, error: title.error };\n const body = checkText(tour.body, 'tour.body', GUIDE_LIMITS.bodyMax);\n if (body.error) return { ok: false, error: body.error };\n if (tour.anchor !== undefined) {\n const allowed = [...GUIDE_TOUR_ANCHORS, ...guideSectionsFor(nodeType)];\n if (!allowed.includes(tour.anchor)) {\n return { ok: false, error: `guide.tour.anchor must be one of: ${allowed.join(', ')}` };\n }\n }\n const value = { title: title.text, body: body.text };\n if (tour.anchor !== undefined) value.anchor = tour.anchor;\n return { ok: true, value };\n}\n\n/** The intro card, trimmed. Same limits as a note; it points at nothing. */\nfunction validateIntro(intro) {\n if (!isPlainObject(intro)) return { ok: false, error: 'guide.intro must be an object with a title and a body' };\n const unknown = Object.keys(intro).find((k) => !INTRO_KEYS.includes(k));\n if (unknown) return { ok: false, error: `guide.intro supports only: ${INTRO_KEYS.join(', ')}` };\n const title = checkText(intro.title, 'intro.title', GUIDE_LIMITS.titleMax);\n if (title.error) return { ok: false, error: title.error };\n const body = checkText(intro.body, 'intro.body', GUIDE_LIMITS.bodyMax);\n if (body.error) return { ok: false, error: body.error };\n return { ok: true, value: { title: title.text, body: body.text } };\n}\n\n/**\n * One checklist item, trimmed. `nodeType` is the type of the node it sits on: a\n * `record_video` item needs one that carries media.\n */\nfunction validateChecklistItem(item, index, nodeType) {\n const at = `guide.checklist[${index}]`;\n if (!isPlainObject(item)) return { ok: false, error: `${at} must be an object with a kind and a label` };\n const unknown = Object.keys(item).find((k) => !CHECKLIST_ITEM_KEYS.includes(k));\n if (unknown) return { ok: false, error: `${at} supports only: ${CHECKLIST_ITEM_KEYS.join(', ')}` };\n if (!COMPANY_CHECKLIST_KINDS.includes(item.kind)) {\n return { ok: false, error: `${at}.kind must be one of: ${COMPANY_CHECKLIST_KINDS.join(', ')}` };\n }\n if (typeof item.label !== 'string') return { ok: false, error: `${at}.label must be a string` };\n const label = item.label.trim();\n if (label.length === 0 || label.length > GUIDE_LIMITS.checklistLabelMax) {\n return { ok: false, error: `${at}.label must be 1 to ${GUIDE_LIMITS.checklistLabelMax} characters` };\n }\n let description;\n if (item.description !== undefined) {\n if (typeof item.description !== 'string') return { ok: false, error: `${at}.description must be a string` };\n description = item.description.trim();\n if (description.length > GUIDE_LIMITS.checklistDescriptionMax) {\n return { ok: false, error: `${at}.description must be at most ${GUIDE_LIMITS.checklistDescriptionMax} characters` };\n }\n }\n if (item.kind === 'record_video' && NODE_TYPES[nodeType]?.supports_media !== true) {\n return { ok: false, error: `${at}: record_video needs a step that can carry a video` };\n }\n if (item.kind === 'connect') {\n const connectable = checklistConnectableIntegrations();\n if (!connectable.includes(item.integration)) {\n return { ok: false, error: `${at}.integration must be a live integration: ${connectable.join(', ')}` };\n }\n } else if (item.integration !== undefined) {\n return { ok: false, error: `${at}.integration is only for a connect item` };\n }\n const value = { kind: item.kind, label };\n if (description) value.description = description;\n if (item.kind === 'connect') value.integration = item.integration;\n return { ok: true, value };\n}\n\n/** A checklist write: an array (empty deletes it, like null). */\nfunction validateChecklist(checklist, nodeType) {\n if (!Array.isArray(checklist)) return { ok: false, error: 'guide.checklist must be an array of items, or null' };\n if (checklist.length > GUIDE_LIMITS.maxChecklistItems) {\n return { ok: false, error: `guide.checklist supports at most ${GUIDE_LIMITS.maxChecklistItems} items` };\n }\n const items = [];\n for (let i = 0; i < checklist.length; i += 1) {\n const item = validateChecklistItem(checklist[i], i, nodeType);\n if (!item.ok) return item;\n items.push(item.value);\n }\n return { ok: true, value: items.length > 0 ? items : null };\n}\n\n/**\n * Validate a `guide` write (a patch: `tour: null`, `intro: null` or `checklist: null`\n * deletes that key). Trims the text, enforces GUIDE_LIMITS, the anchor and kind enums, and rejects\n * any other key. `nodeType` is the type of the node being written: a `record_video`\n * checklist item needs one that carries media.\n * Returns `{ ok: true, value }` or `{ ok: false, error }`.\n */\nexport function validateNodeGuide(value, { nodeType } = {}) {\n if (!isPlainObject(value)) return { ok: false, error: 'guide must be an object' };\n const unknown = Object.keys(value).find((k) => !GUIDE_KEYS.includes(k));\n if (unknown) return { ok: false, error: `guide supports only: ${GUIDE_KEYS.join(', ')}` };\n const out = {};\n if ('tour' in value) {\n if (value.tour === null) {\n out.tour = null;\n } else {\n const tour = validateTour(value.tour, nodeType);\n if (!tour.ok) return tour;\n out.tour = tour.value;\n }\n }\n if ('intro' in value) {\n if (value.intro === null) {\n out.intro = null;\n } else {\n const intro = validateIntro(value.intro);\n if (!intro.ok) return intro;\n out.intro = intro.value;\n }\n }\n if ('checklist' in value) {\n if (value.checklist === null) {\n out.checklist = null;\n } else {\n const checklist = validateChecklist(value.checklist, nodeType);\n if (!checklist.ok) return checklist;\n out.checklist = checklist.value;\n }\n }\n return { ok: true, value: out };\n}\n\n/**\n * One-level merge of a validated guide patch into the stored guide, so `tour`\n * and `checklist` stay independent (update-node's own merge replaces nested\n * objects wholesale). A null sub-key deletes it; an empty guide is null.\n */\nexport function mergeNodeGuide(existing, patch) {\n const merged = isPlainObject(existing) ? { ...existing } : {};\n if (isPlainObject(patch)) {\n for (const [key, value] of Object.entries(patch)) {\n if (value === null) delete merged[key];\n else merged[key] = value;\n }\n }\n return Object.keys(merged).length > 0 ? merged : null;\n}\n\n/** The config without `guide` (the same object when it has none). */\nexport function stripNodeGuide(config) {\n if (!isPlainObject(config) || !(GUIDE_CONFIG_KEY in config)) return config;\n const { [GUIDE_CONFIG_KEY]: _guide, ...rest } = config;\n return rest;\n}\n\n/**\n * The walkthrough steps of a form, from its live nodes' notes: in BFS order\n * from Start (unreachable nodes after), one step per valid note, the single\n * `share` step last (the first one in that order wins), capped at\n * GUIDE_LIMITS.maxTourSteps including it. A note on a node that is not in\n * `nodes` (or is deleted) never shows, and an invalid note is dropped.\n *\n * @param {Array<{ id: string, type: string, config?: object | null, deleted_at?: string | null }>} nodes\n * @param {Map<string, import('./logic-types.js').LogicAction[]>} logicByNode\n * @returns {Array<{ node_id: string, node_type: string, title: string, body: string, anchor: string }>}\n */\nexport function buildTemplateTourSteps(nodes, logicByNode) {\n const ordered = liveInFormOrder(nodes, logicByNode);\n const steps = [];\n let closing = null;\n for (const node of ordered) {\n const raw = isPlainObject(node.config) && isPlainObject(node.config[GUIDE_CONFIG_KEY]) ? node.config[GUIDE_CONFIG_KEY].tour : undefined;\n if (raw == null) continue;\n // A stored section the type no longer has (a type change) falls back to the whole node.\n const stale = isPlainObject(raw) && GUIDE_SECTIONS.includes(raw.anchor) && !guideSectionsFor(node.type).includes(raw.anchor);\n const tour = validateTour(stale ? { ...raw, anchor: 'node' } : raw, node.type);\n if (!tour.ok) continue;\n const step = { node_id: node.id, node_type: node.type, title: tour.value.title, body: tour.value.body, anchor: tour.value.anchor ?? 'node' };\n if (step.anchor === 'share') {\n if (!closing) closing = step;\n } else {\n steps.push(step);\n }\n }\n const cap = GUIDE_LIMITS.maxTourSteps;\n return closing ? [...steps.slice(0, cap - 1), closing] : steps.slice(0, cap);\n}\n\n/**\n * The company checklist of a form (#6275), from its live nodes' `guide.checklist`: nodes\n * in the same BFS order as the tour steps, then array order within a node; an invalid\n * item is dropped (a type change can leave a `record_video` on a node without media, a\n * catalog change can take an integration dark) and the list is capped at\n * GUIDE_LIMITS.maxChecklistItems. An item on a node not in `nodes` (or deleted) never shows.\n * Ids are `company:<node_id>:<index in the node's list>`, so they stay put when another\n * item is dropped. A `record_video` item carries `baseline_media_id`: the node's media\n * that came with the copy (`baselineMediaByNode`), which never counts as the owner's own.\n *\n * @param {Array<{ id: string, type: string, config?: object | null, deleted_at?: string | null }>} nodes\n * @param {Map<string, import('./logic-types.js').LogicAction[]>} logicByNode\n * @param {Map<string, string | null>} [baselineMediaByNode]\n */\nexport function buildTemplateChecklist(nodes, logicByNode, baselineMediaByNode) {\n const ordered = liveInFormOrder(nodes, logicByNode);\n const baselines = baselineMediaByNode instanceof Map ? baselineMediaByNode : new Map();\n const items = [];\n for (const node of ordered) {\n const raw = isPlainObject(node.config) && isPlainObject(node.config[GUIDE_CONFIG_KEY]) ? node.config[GUIDE_CONFIG_KEY].checklist : undefined;\n if (!Array.isArray(raw)) continue;\n raw.forEach((entry, index) => {\n const checked = validateChecklistItem(entry, index, node.type);\n if (!checked.ok) return;\n const item = { id: `company:${node.id}:${index}`, node_id: node.id, ...checked.value };\n if (item.kind === 'record_video') item.baseline_media_id = baselines.get(node.id) ?? null;\n items.push(item);\n });\n }\n return items.slice(0, GUIDE_LIMITS.maxChecklistItems);\n}\n\n/**\n * The walkthrough's intro card: the first valid `guide.intro` in the same order as\n * the steps (BFS from Start), or null (the builder shows its plain default). It\n * never counts as a step.\n *\n * @param {Array<{ id: string, type: string, config?: object | null, deleted_at?: string | null }>} nodes\n * @param {Map<string, import('./logic-types.js').LogicAction[]>} logicByNode\n * @returns {{ title: string, body: string } | null}\n */\nexport function buildTemplateTourIntro(nodes, logicByNode) {\n for (const node of liveInFormOrder(nodes, logicByNode)) {\n const raw = isPlainObject(node.config) && isPlainObject(node.config[GUIDE_CONFIG_KEY]) ? node.config[GUIDE_CONFIG_KEY].intro : undefined;\n if (raw == null) continue;\n const intro = validateIntro(raw);\n if (intro.ok) return intro.value;\n }\n return null;\n}\n\nfunction liveInFormOrder(nodes, logicByNode) {\n const live = (Array.isArray(nodes) ? nodes : []).filter((n) => n && typeof n.id === 'string' && !n.deleted_at);\n return bfsOrder(live, logicByNode instanceof Map ? logicByNode : new Map());\n}\n","import { FEATURES, getLiveFeatures, ANNOUNCE_PALETTES } from './features.js';\nimport { HELP_TOPICS, buildHelpLinks } from './help-links.js';\nimport { NODE_TYPES as NODE_TYPE_DEFS, CONSENT_TYPES } from './node-types.js';\nimport { RECALL_TOKEN_SOURCE, RECALL_RESERVED_LABELS, parseRecallRef } from './recall.js';\n\n// @vid-master/config - Essential shared configuration\n\n/**\n * Environment Detection\n * Automatically detects dev/localhost vs production\n */\nconst isServer = typeof window === 'undefined';\nconst isBrowser = typeof window !== 'undefined';\n\n// Detect localhost/development environment\nconst isLocalhost = isBrowser && (\n window.location.hostname === 'localhost' ||\n window.location.hostname === '127.0.0.1' ||\n window.location.hostname.includes('local')\n);\n\nconst isDevelopment = isServer\n ? process.env.NODE_ENV !== 'production'\n : isLocalhost;\n\nexport const ENV = {\n isDevelopment,\n isProduction: !isDevelopment,\n isLocalhost: isDevelopment, // alias for clarity\n};\n\n/**\n * Domain the dashboard auth cookies USED to be written on (#5528). Auth\n * cookies are now host-only (no Domain), so a form owner's session is never\n * sent to or readable on form pages on the apex. This is kept ONLY to expire\n * the old domain-wide cookies: a cookie is deleted only by a write with the\n * same name, Domain and Path.\n * undefined in dev (browsers reject explicit domain on localhost).\n */\nexport const LEGACY_AUTH_COOKIE_DOMAIN = ENV.isDevelopment ? undefined : '.clipform.io';\n\n// `sb-<ref>-auth-token`, its `.N` chunks, and `-code-verifier` (PKCE), as\n// written by @supabase/ssr before the session cookie got its own name.\nconst LEGACY_AUTH_COOKIE_RE = /^sb-.+-auth-token(?:-code-verifier)?(?:\\.\\d+)?$/;\n\n/** True for a pre-#5528 Supabase auth cookie name (see LEGACY_AUTH_COOKIE_DOMAIN). */\nexport function isLegacyAuthCookie(name) {\n return LEGACY_AUTH_COOKIE_RE.test(name);\n}\n\n/**\n * Browser is accessing the app via the Cloudflare dev tunnel\n * (e.g. dashboard-dev.smith-forge.com → routes to local Next.js).\n * In that case browser fetches must use the matching tunnel hostnames,\n * because the browser cannot reach localhost on the dev's machine.\n */\nconst isTunnelBrowser = isBrowser &&\n window.location.hostname.endsWith('.smith-forge.com');\n\n/**\n * Production origins - the single source of truth for Clipform's public URLs.\n * getUrls() returns these in prod (dev/tunnel branches override). Embed adapters\n * that run on third-party platforms and can't import this package (apps/embeds/*,\n * apps/shopify) hardcode these origins; they're pinned to this value by\n * apps/api/src/__tests__/lib/embed-origin-parity.test.ts so a domain change\n * can't silently skip an adapter.\n */\nexport const PROD_URLS = {\n marketing: 'https://www.clipform.io',\n // Dedicated CDN host for the embed SDK, decoupled from the marketing deploy\n // (ships in seconds via packages/embed-sdk `deploy:cf`). www.clipform.io/embed.js\n // stays as the legacy bridge until all installs migrate here.\n embed: 'https://js.clipform.io',\n dashboard: 'https://app.clipform.io',\n viewer: 'https://clipform.io',\n api: 'https://api.clipform.io',\n // Dedicated subdomain for the remote MCP server. Same Render service\n // as `api`, just routed by Host header. Token audience is bound here.\n mcp: 'https://mcp.clipform.io',\n docs: 'https://clipform.io/docs',\n};\n\nexport function getUrls() {\n if (isTunnelBrowser) {\n return {\n marketing: 'https://marketing-dev.smith-forge.com',\n // Dev/tunnel: the marketing dev server 308-redirects /embed.js to js.clipform.io\n // (public/embed.js was retired in #1288), so embeds load the live SDK.\n embed: 'https://marketing-dev.smith-forge.com',\n dashboard: 'https://dashboard-dev.smith-forge.com',\n viewer: 'https://viewer-dev.smith-forge.com',\n api: 'https://api-dev.smith-forge.com',\n mcp: 'https://api-dev.smith-forge.com/mcp',\n docs: 'https://clipform.io/docs',\n };\n }\n\n if (ENV.isDevelopment) {\n // Per-worktree overrides: a parallel worktree can run its own full stack on\n // a distinct port block by setting NEXT_PUBLIC_*_URL in its .env.local (plus\n // a matching `-p` / PORT). Without these the apps resolve each other at the\n // base ports below and would cross-wire to another worktree's servers.\n // Direct `process.env.NEXT_PUBLIC_*` reads (not destructured) so Next inlines\n // them into client bundles - every app that imports this package client-side\n // transpiles it (see each app's next.config transpilePackages).\n const api = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3003';\n return {\n marketing: process.env.NEXT_PUBLIC_MARKETING_URL || 'http://localhost:3002',\n // Local: the marketing dev server redirects /embed.js to js.clipform.io\n // (public/embed.js was retired in #1288), so embeds load the live SDK.\n embed: process.env.NEXT_PUBLIC_MARKETING_URL || 'http://localhost:3002',\n dashboard: process.env.NEXT_PUBLIC_DASHBOARD_URL || 'http://localhost:3000',\n viewer: process.env.NEXT_PUBLIC_VIEWER_URL || 'http://localhost:3001',\n api,\n // No separate MCP host in dev - tools live on the api subpath.\n mcp: api + '/mcp',\n // The docs app serves under basePath /docs (matching prod\n // clipform.io/docs), so the dev URL must include it too.\n docs: process.env.NEXT_PUBLIC_DOCS_URL || 'http://localhost:3004/docs',\n };\n }\n\n // Fresh copy so callers can't mutate the shared PROD_URLS source of truth.\n return { ...PROD_URLS };\n}\n\n/** Public changelog page (generated from FEATURES). Dev-aware; the trailing slash matches marketing's `trailingSlash`. */\nexport function changelogUrl() {\n return `${getUrls().marketing}/changelog/`;\n}\n\n/** The remote MCP server's two surfaces (#6241): `forms` (forms and results) and `all` (every tool, media included). */\nexport const MCP_SURFACES = ['forms', 'all'];\n\n/**\n * The remote MCP server URL an AI client connects to (#6241), env-resolved\n * off getUrls().mcp (`https://mcp.clipform.io` in prod, `<api>/mcp` in dev\n * and on the tunnel), never hardcoded. `forms` is the forms-and-results\n * surface at `/forms`, the one the Claude directory listing uses; `all` is\n * the bare URL with every tool (apps/api/src/mcp/path-match.ts). Throws on\n * an unknown surface so a caller can't hand a client a dead URL.\n */\nexport function mcpServerUrl(surface) {\n if (!MCP_SURFACES.includes(surface)) {\n throw new Error(`mcpServerUrl: unknown surface \"${surface}\" - must be one of ${MCP_SURFACES.join(', ')}`);\n }\n const base = getUrls().mcp;\n return surface === 'forms' ? `${base}/forms` : base;\n}\n\n/**\n * Core business information - UPDATE THESE AS NEEDED\n */\nexport const BUSINESS = {\n name: \"Clipform\",\n tagline: \"Video-Driven Form Builder\",\n description:\n \"Create engaging forms that combine video content with interactive questions. Capture authentic responses with text, audio, or video recordings.\",\n shortDescription:\n \"Interactive video forms that capture authentic responses. Build engaging forms in minutes.\",\n domain: \"clipform.io\",\n email: {\n support: \"support@clipform.io\",\n sales: \"sales@clipform.io\",\n hello: \"hello@clipform.io\",\n founder: \"andy@clipform.io\",\n // Inbound form-builder address (Cloudflare Email Routing -> email-inbound\n // worker). Also the Reply-To on bot replies so a reply reaches the bot.\n new: \"new@clipform.io\",\n // Vulnerability disclosure inbox (#4011) - advertised in security.txt\n // (RFC 9116) and the docs disclosure policy.\n security: \"security@clipform.io\",\n },\n urls: getUrls(),\n};\n\n/**\n * Two-tier video delivery threshold (#1015): a video at/above this size goes to\n * Mux (adaptive HLS); below it it's stored direct in Supabase. The\n * API gate (`apps/api/src/lib/video-delivery.ts`) and the uploader client both\n * read this so the client knows whether to send bytes through the API (direct)\n * or straight to Mux (large). Single source - never hardcode the threshold.\n *\n * Set to 20MB from real data (#1495): the old 10MB cap sent ~half of uploads to\n * Mux purely for being big. A clip up to VIDEO_COMPRESS_MAX_SECONDS (43s)\n * compresses to under 20MB at the 3.5Mbps target (#1512).\n *\n * Not a playback cutoff: the #5887 lab found start time and stalls follow\n * bitrate against the connection, not size or length (a 5 min 3.5 Mbps clip\n * starts as fast direct as a 10s one). It stays for two other reasons, both\n * retired by #6136: bytes at/over it upload straight from the browser to Mux,\n * so the API never has them; and nothing re-encodes the served original on the\n * server (only a lite fallback copy, #6044), so a file this big is almost\n * always a full-bitrate camera original that would stall if served as-is,\n * which Mux's transcode fixes.\n */\nexport const MEDIA_DIRECT_MAX_BYTES = 20 * 1024 * 1024; // 20 MB\n\n/**\n * Product-level cap on any still image, whatever the source (multipart\n * upload, phone upload, or a caller/model-supplied URL). Every image\n * ingest path (apps/api's create-media.ts, the node upload route, the\n * phone-upload page) and the dashboard's own client-side pre-check\n * (MediaModal) read this single source rather than hardcoding 10MB.\n */\nexport const MEDIA_IMAGE_MAX_BYTES = 10 * 1024 * 1024; // 10 MB\n\n/**\n * What makes a good custom draw diagram (#5210, #5052). One sentence shared by the\n * builder's upload hint, the MCP craft line (packages/mcp-content) and the help docs.\n */\nexport const DRAW_DIAGRAM_SPEC = `PNG with simple dark outlines on a light or transparent background (no shading or text), portrait, at least 1000px wide. Up to ${Math.round(MEDIA_IMAGE_MAX_BYTES / (1024 * 1024))}MB.`;\n\n/**\n * Product-level cap on a consent-agreement PDF (#4525), whatever the source\n * (multipart upload or a caller/model-supplied URL).\n */\nexport const MEDIA_DOCUMENT_MAX_BYTES = 20 * 1024 * 1024; // 20 MB\n\n/**\n * Hard ceiling on ANY single object written to Supabase storage, in bytes.\n *\n * This is not our choice - it is the project-global storage limit imposed by the\n * Supabase plan, and it OVERRIDES every per-bucket `file_size_limit` declared in\n * `supabase/config.toml` at upload time. Offering the user more than this just\n * produces an upload that passes every client check and then dies at the storage\n * layer (#2556).\n *\n * Only applies to the Supabase destination. Mux-bound uploads are unaffected and\n * keep their own, larger limits.\n *\n * Raising it means lifting the plan ceiling in the Supabase dashboard FIRST, then\n * raising the bucket declarations in `supabase/config.toml`, then this value.\n * #4023: raised 50 -> 200 MiB now that we're confirmed on Supabase Pro (the\n * global project ceiling was raised to 500 MiB and the `media-responses`\n * bucket to 200 MiB to match).\n */\nexport const SUPABASE_STORAGE_MAX_BYTES = 200 * 1024 * 1024; // 200 MiB\n\n/**\n * Storage `cacheControl` (seconds, sent as `max-age=<n>`) for uploads (#5133).\n *\n * Both are bare whole-number strings on purpose: Supabase TUS only accepts an\n * integer `cacheControl` and stores `no-cache` for anything else, so there is\n * no `immutable` directive.\n *\n * IMMUTABLE (1 year) is for public `node-media` objects at a unique path.\n * RULE: a path written with IMMUTABLE must never be rewritten with different\n * bytes - browsers hold it for a year. Write a new path instead (UUID, content\n * hash, or a bumped rendition `version`).\n *\n * PRIVATE (1 hour) is for the signed-URL buckets (media-responses,\n * respondent-captures, file-uploads, file-downloads), matching the signed-URL\n * lifetime.\n */\nexport const STORAGE_CACHE_CONTROL_IMMUTABLE = \"31536000\";\nexport const STORAGE_CACHE_CONTROL_PRIVATE = \"3600\";\n\n/**\n * Trash (#2596 slice 3): days a trashed form stays recoverable before the\n * purge sweep (a later slice) hard-deletes it. Single source for the\n * dashboard's countdown badge and dialogs - never hardcode 30 there.\n *\n * The docs page (apps/docs/content/docs/help/managing-forms.mdx) states this\n * in prose as a hand-synced copy, NOT a derived value (MDX has no import of\n * this module) - if this constant ever changes, update that prose by hand too.\n */\nexport const TRASH_RETENTION_DAYS = 30;\n\n/**\n * Default resume window (#3885): hours before an incomplete response session\n * is considered expired and cleared, when a form has no explicit\n * `form_metadata.session_expiry_hours` override. Single source for the\n * `form_metadata.session_expiry_hours` column default (kept in step by hand -\n * SQL can't import this), `useFormMetadata`'s optimistic-cache default, the\n * dashboard's \"Keep progress for\" field, viewer's resume-window fallbacks,\n * and the responses table's stale-session threshold. Stored/displayed in\n * hours; the dashboard presents it in days (this / 24).\n */\nexport const DEFAULT_SESSION_EXPIRY_HOURS = 168;\n\n/**\n * Upper bound of `form_metadata.session_expiry_hours` (#1216): the builder\n * offers 1-30 days and the API clamps writes to this. It is therefore the\n * longest a respondent session can live, which the staged-node-delete sweep\n * (#5077) uses as its grace window. Single source - never hardcode 720.\n */\nexport const MAX_SESSION_EXPIRY_HOURS = 720;\n\n/**\n * On-device video compression settings (#1512, desktop parity #2329) - single\n * source of truth for both the phone upload page (`apps/api/src/routes/v1/media/\n * phone-upload-page.ts`, inline script) and the desktop builder helper\n * (`apps/dashboard/lib/compress-video.ts`). Both re-encode via mediabunny/\n * WebCodecs to these exact settings before the direct-vs-Mux size handshake, so\n * a clip compresses identically regardless of upload surface.\n *\n * VIDEO_COMPRESS_FLOOR_BYTES is a \"won't shrink, skip the generation loss + CPU\"\n * floor - below this a clip can't meaningfully benefit from re-encoding at the\n * bitrate below, and the keep-only-if-smaller guard in both callers already\n * blocks any accidental bloat. Locked at 1 MB (#2329).\n *\n * VIDEO_COMPRESS_MAX_SHORT_SIDE caps the SHORT side of the output (#6321), so a\n * 9:16 portrait clip keeps 1080x1920 and a landscape one 1920x1080 (a height\n * cap squashed portrait to 608x1080). It never upscales: a clip whose short\n * side is already at or under it keeps that size, rounded down to even (H.264\n * refuses odd sizes). The phone page and the desktop apply the identical\n * rule - change both together.\n */\nexport const VIDEO_COMPRESS_BITRATE = 3_500_000;\nexport const VIDEO_COMPRESS_MAX_SHORT_SIDE = 1080;\nexport const VIDEO_COMPRESS_FPS = 30;\nexport const VIDEO_COMPRESS_FLOOR_BYTES = 1 * 1024 * 1024; // 1 MB\n\n/**\n * Product-level cap on a single video upload (#5876), whatever the surface\n * (builder picker, phone upload page, Mux direct upload). Single source - the\n * dashboard's client-side pre-check, the phone page and the API's Mux upload\n * message all read this rather than hardcoding 200MB.\n */\nexport const MEDIA_VIDEO_MAX_BYTES = 200 * 1024 * 1024; // 200 MB\n\n/**\n * Max size of one file a creator attaches to a File Download node (#4706). The\n * builder's upload widget, its \"Max file size\" hint and the size refusal all\n * read this. Matches the `file-downloads` bucket ceiling in supabase/config.toml.\n */\nexport const FILE_DOWNLOAD_MAX_BYTES = 50 * 1024 * 1024; // 50 MB\n\n/**\n * Longest clip that still fits the direct tier (MEDIA_DIRECT_MAX_BYTES) after\n * on-device compression, in whole seconds (43). Both compressors set only the\n * video bitrate (VIDEO_COMPRESS_BITRATE) and pass the source audio through, so\n * the budget allows up to 256 kbps of audio plus 3% for MP4 overhead and encoder\n * overshoot. The desktop picker skips compressing a longer clip: it is over the\n * size cap even compressed, so it goes to Mux whatever we do, and Mux bills\n * minutes, not bytes (#5876). There is no length rule on delivery itself (#5887).\n */\nconst VIDEO_COMPRESS_AUDIO_ALLOWANCE = 256_000; // bits per second\nconst VIDEO_COMPRESS_SIZE_MARGIN = 0.97;\nexport const VIDEO_COMPRESS_MAX_SECONDS = Math.floor(\n (MEDIA_DIRECT_MAX_BYTES * 8 * VIDEO_COMPRESS_SIZE_MARGIN) / (VIDEO_COMPRESS_BITRATE + VIDEO_COMPRESS_AUDIO_ALLOWANCE),\n);\n\n/**\n * Upload stall bound (#5876): abort when no bytes move for this long. Shared by\n * the dashboard's upload watchdog and the phone upload page.\n */\nexport const UPLOAD_STALL_MS = 45_000;\n\n/** Once every byte is up, the server's budget to probe and store the file before an upload is abandoned (#5876). */\nexport const UPLOAD_RESPONSE_BUDGET_MS = 120_000;\n\n/** Share of a compressed video's progress bar given to the encode (0-1); the upload fills the rest (#5360). */\nexport const UPLOAD_COMPRESS_BAND = 0.4;\n\n/**\n * Backoff (ms) between retries of a resumable (tus) upload chunk, one entry per retry (#6197). Shared by\n * `uploadFileToStorageTus` (upload-client) and the phone upload page's inline tus client.\n */\nexport const TUS_RETRY_DELAYS_MS = Object.freeze([0, 3000, 5000, 10000, 20000]);\n\n/**\n * Desktop compression is skipped for a clip that is already ready to serve\n * (fast-start H.264/AAC MP4) at or under this bitrate (#5876).\n */\nexport const VIDEO_COMPRESS_SKIP_BITRATE = VIDEO_COMPRESS_BITRATE * 1.5; // 5.25 Mbps\n\n/**\n * Desktop encode bails to the original when its projected total time exceeds\n * this (#5876). A starting value, tuned from `video_compression` events.\n */\nexport const VIDEO_COMPRESS_MAX_PROJECTED_MS = 20_000;\n\n/**\n * Whether front-camera captures are SAVED mirrored (#5021). Off: only the\n * live preview is mirrored; the review and the saved photo/video show the true\n * camera image - the industry default (iPhone/Android cameras,\n * Zoom/Meet/Loom recordings, VideoAsk), so writing in shot reads correctly for\n * the form owner. Read by the API media processor (video answers) and the\n * viewer's desktop webcam capture and Open review (on: the saved file is mirrored\n * and the review shows it as saved); kept as a switch rather than deleting the flip.\n */\nexport const SAVE_FRONT_CAMERA_MIRRORED = false;\n\n/**\n * In-product \"Learn more\" deep-links (#394) - single source of truth, keyed\n * by concept. Anchors are CI-checked against real docs headings\n * (apps/docs/scripts/check-help-links.mjs). Never hardcode docs URLs in UI.\n */\nexport const HELP_LINKS = buildHelpLinks(BUSINESS.urls.docs);\nexport { HELP_TOPICS };\n\n/**\n * Per-node-type \"Learn more\" deep-link (#3963): looks up `node_<nodeType>` in\n * HELP_LINKS, so a node's settings menu can link straight to its section on\n * help/node-types.mdx. Returns null when the node type has no docs topic\n * (menu renders nothing rather than a dead link).\n */\nexport function nodeHelpLink(nodeType) {\n return HELP_LINKS[`node_${nodeType}`] ?? null;\n}\n\n/** URL builders — single source of truth for public-facing links */\nexport function viewerUrl(shareId) {\n return `${BUSINESS.urls.viewer}/${shareId}`;\n}\n/**\n * The link handed to someone to open/claim a form they built as a guest\n * (bot email + social replies, MCP create-form). Flag-gated on\n * `FEATURES.anonymous_builder` (#2979): on -> `/try`, which drops them\n * straight into the builder to see the product (no signup gate); off -> the\n * legacy `/save` signup wall. `getTemplateCtaUrl` (marketing) mirrors this\n * branch for template CTAs.\n */\nexport function formUrl(shareId) {\n return FEATURES.anonymous_builder.enabled\n ? templateTryUrl(shareId, BUSINESS.urls.dashboard)\n : `${BUSINESS.urls.dashboard}/save/${shareId}`;\n}\n/**\n * Same-UID claim handoff link (#3330 decision 3) for an MCP-minted anonymous\n * session: opens the dashboard's one-time claim route, which signs the\n * browser back into that exact anon Supabase session (not a copy) so the\n * standard convert flow can flip is_anonymous on it in place. `token` is a\n * one-time, ~15-minute opaque token from mintMcpClaimToken - never a\n * share_id or workspace id.\n */\nexport function mcpClaimUrl(token) {\n return `${BUSINESS.urls.dashboard}/claim/${token}`;\n}\n/**\n * Every dashboard tab a form has (#3405) - single source for the tab path\n * segment, so an MCP/bot deeplink can never drift from the real route. The\n * dashboard route folders under apps/dashboard/app/(app)/[workspaceId]/forms/[formId]/\n * are the ground truth this mirrors. Enforced, not just documentation:\n * dashboardFormUrl throws on any tab not in this list, so a caller's own\n * hardcoded tab string (e.g. get-form.ts's urls object) fails loudly the\n * moment it drifts from this array instead of silently building a dead link.\n */\nexport const DASHBOARD_FORM_TABS = ['build', 'summary', 'responses', 'analytics', 'share', 'share/embed', 'share/dynamic-link'];\n\n/**\n * Relative dashboard path for a form tab (#5131), optionally with a query\n * (object of string values). Same tab validation as dashboardFormUrl, which is\n * built on it. Use this for in-app links; use dashboardFormUrl for absolute URLs.\n */\nexport function dashboardFormPath(workspaceId, formId, tab = 'build', query) {\n if (!DASHBOARD_FORM_TABS.includes(tab)) {\n throw new Error(\n `dashboardFormPath: unknown tab \"${tab}\" - must be one of ${DASHBOARD_FORM_TABS.join(', ')}`\n );\n }\n const qs = query ? new URLSearchParams(query).toString() : '';\n return `/${workspaceId}/forms/${formId}/${tab}${qs ? `?${qs}` : ''}`;\n}\n\nexport function dashboardFormUrl(workspaceId, formId, tab = 'build') {\n return `${BUSINESS.urls.dashboard}${dashboardFormPath(workspaceId, formId, tab)}`;\n}\n\n/** Dashboard workspace root (redirects to the forms list). */\nexport function dashboardWorkspaceUrl(workspaceId) {\n return `${BUSINESS.urls.dashboard}/${workspaceId}`;\n}\n\n/** Dashboard forms list for a workspace. */\nexport function dashboardFormsListUrl(workspaceId) {\n return `${BUSINESS.urls.dashboard}/${workspaceId}/forms`;\n}\n\n/**\n * The dashboard's Settings area (#6211): one place, grouped by the scope a\n * setting applies to - Account (you), Company (every workspace in it) and\n * Workspace. Paths are relative to the workspace root `/{workspaceId}/`; the\n * route folders under apps/dashboard/app/(app)/[workspaceId]/settings/ are the\n * ground truth this mirrors (apps/dashboard/__tests__/app/settings/routes.test.ts).\n */\nexport const DASHBOARD_SETTINGS_PAGES = {\n account: 'settings/account',\n company: 'settings/company',\n companyBilling: 'settings/company/billing',\n workspace: 'settings/workspace',\n domains: 'settings/workspace/domains',\n};\n\n/**\n * The dashboard's Developers page (#6241), the one home for developer tools:\n * connecting AI clients over MCP (the hub), API keys, webhooks and the\n * authorized apps that hold access to the workspace. A rail item next to\n * Integrations, not part of Settings. Paths are relative to the workspace\n * root `/{workspaceId}/`; the route folders under\n * apps/dashboard/app/(app)/[workspaceId]/developers/ are the ground truth\n * (apps/dashboard/__tests__/app/developers/routes.test.ts).\n */\nexport const DASHBOARD_DEVELOPER_PAGES = {\n developers: 'developers',\n apiKeys: 'developers/api-keys',\n webhooks: 'developers/webhooks',\n authorizedApps: 'developers/authorized-apps',\n};\n\n/**\n * Old settings URLs and the page each moved to (#6211, #6241), both relative\n * to `/{workspaceId}/`. One table, read by the dashboard's next.config.js\n * redirects (in-workspace URLs), the workspace-less `/settings`, `/company`,\n * `/account` and `/developers` forwarders, and their tests. Every `to` is a\n * current page (never another `from`), so an old link lands in one hop,\n * query kept. Integrations stays a rail item, so its pre-#3203 URL goes\n * there; API keys, Webhooks and Authorized apps live in Developers.\n */\nexport const DASHBOARD_SETTINGS_REDIRECTS = [\n { from: 'settings', to: DASHBOARD_SETTINGS_PAGES.workspace },\n { from: 'company', to: DASHBOARD_SETTINGS_PAGES.company },\n { from: 'company/billing', to: DASHBOARD_SETTINGS_PAGES.companyBilling },\n { from: 'settings/billing', to: DASHBOARD_SETTINGS_PAGES.companyBilling },\n { from: 'api-keys', to: DASHBOARD_DEVELOPER_PAGES.apiKeys },\n { from: 'webhooks', to: DASHBOARD_DEVELOPER_PAGES.webhooks },\n { from: 'settings/api-keys', to: DASHBOARD_DEVELOPER_PAGES.apiKeys },\n { from: 'settings/webhooks', to: DASHBOARD_DEVELOPER_PAGES.webhooks },\n { from: 'settings/integrations', to: 'integrations' },\n { from: 'settings/domains', to: DASHBOARD_SETTINGS_PAGES.domains },\n { from: 'settings/connected-apps', to: DASHBOARD_DEVELOPER_PAGES.authorizedApps },\n // #6211's Settings - Workspace pages, moved to Developers (#6241).\n { from: 'settings/workspace/api-keys', to: DASHBOARD_DEVELOPER_PAGES.apiKeys },\n { from: 'settings/workspace/webhooks', to: DASHBOARD_DEVELOPER_PAGES.webhooks },\n { from: 'settings/workspace/authorized-apps', to: DASHBOARD_DEVELOPER_PAGES.authorizedApps },\n];\n\n/**\n * The workspace-less deep-link roots the dashboard forwards (#1002, #4587,\n * #6211, #6241): `/settings/...`, `/company/...`, `/account/...` and\n * `/developers/...` resolve the user's active workspace, so docs and emails\n * never carry a workspace id.\n */\nexport const DASHBOARD_SETTINGS_FORWARDERS = ['settings', 'company', 'account', 'developers'];\n\n/**\n * A settings page's dashboard path. With no workspace it is the\n * workspace-less deep link (`/settings/...`), which resolves the active\n * workspace. Throws on an unknown page so a caller can't build a dead link.\n */\nexport function dashboardSettingsPath(workspaceId, page) {\n const path = DASHBOARD_SETTINGS_PAGES[page];\n if (!path) {\n throw new Error(\n `dashboardSettingsPath: unknown page \"${page}\" - must be one of ${Object.keys(DASHBOARD_SETTINGS_PAGES).join(', ')}`\n );\n }\n return workspaceId ? `/${workspaceId}/${path}` : `/${path}`;\n}\n\n/**\n * A Developers page's dashboard path (#6241), mirroring dashboardSettingsPath:\n * with no workspace it is the workspace-less deep link (`/developers/...`),\n * which resolves the active workspace. Throws on an unknown page so a caller\n * can't build a dead link.\n */\nexport function dashboardDeveloperPath(workspaceId, page) {\n const path = DASHBOARD_DEVELOPER_PAGES[page];\n if (!path) {\n throw new Error(\n `dashboardDeveloperPath: unknown page \"${page}\" - must be one of ${Object.keys(DASHBOARD_DEVELOPER_PAGES).join(', ')}`\n );\n }\n return workspaceId ? `/${workspaceId}/${path}` : `/${path}`;\n}\n\n/**\n * Where a workspace-less settings or developers deep link lands, relative to\n * `/{workspaceId}/` (#6211, #6241): an old URL maps through\n * DASHBOARD_SETTINGS_REDIRECTS, `/company/<x>` sits under\n * `settings/company/<x>`, anything under `/account` is the Account page, and\n * a current Settings or Developers path passes through. Null when the link\n * doesn't reach a real page (an unknown root or sub-page), which the docs\n * link guard fails on.\n */\nexport function dashboardSettingsTarget(path) {\n const clean = String(path ?? '').replace(/^\\/+|\\/+$/g, '');\n const root = clean.split('/')[0];\n if (!DASHBOARD_SETTINGS_FORWARDERS.includes(root)) return null;\n const row = DASHBOARD_SETTINGS_REDIRECTS.find((r) => r.from === clean);\n let target = row ? row.to : clean;\n if (!row && root === 'company') target = `settings/${clean}`;\n if (root === 'account') target = DASHBOARD_SETTINGS_PAGES.account;\n const isPage =\n target === 'integrations' ||\n Object.values(DASHBOARD_SETTINGS_PAGES).includes(target) ||\n Object.values(DASHBOARD_DEVELOPER_PAGES).includes(target);\n return isPage ? target : null;\n}\n\n/**\n * Company settings - Billing (#4587, under Settings since #6211), the\n * dashboard path the billing API's Stripe return URLs and every dashboard\n * Upgrade link share. With no workspace it is the workspace-less\n * `/settings/company/billing` deep link, which resolves the active workspace.\n */\nexport function dashboardCompanyBillingPath(workspaceId) {\n return dashboardSettingsPath(workspaceId, 'companyBilling');\n}\n\n/**\n * Dashboard auth routes - single source of truth so a login/signup route rename\n * is one edit here (plus renaming the app/<route> folder). Internal dashboard\n * redirects use AUTH_ROUTES.*; cross-app links (marketing) use the *Url builders.\n */\nexport const AUTH_ROUTES = { login: '/login', signup: '/signup' };\nexport function loginUrl() {\n return `${BUSINESS.urls.dashboard}${AUTH_ROUTES.login}`;\n}\nexport function signupUrl() {\n return `${BUSINESS.urls.dashboard}${AUTH_ROUTES.signup}`;\n}\n\n/**\n * Minimum password length (#3843) - single source of truth for both the\n * client-side floor (AuthForm's password step, SetPasswordCard, the\n * /auth/callback recovery form, ConvertAccountModal) and the server-side\n * one (`minimum_password_length` in supabase/config.toml, dashboard-set on\n * dev + prod - see that file's #2984/#3843 note). Kept in lockstep by\n * apps/api/src/__tests__/lib/min-password-length-sync.test.ts - change both\n * together.\n */\nexport const MIN_PASSWORD_LENGTH = 8;\n\n/**\n * OTP/magic-link resend cooldown, in seconds (#3873) - must equal\n * `[auth.email] max_frequency` in supabase/config.toml AND the hosted\n * Supabase dashboard value (Auth -> Providers -> Email -> \"Rate limit for\n * sending emails\"; Studio's shared default is 60s for both the OTP and\n * magic-link email types). GoTrue rejects an email send inside this window\n * with `over_email_send_rate_limit`, so AuthForm's Resend control disables\n * itself and shows a countdown for this long after every send instead of\n * letting the user hit the server limit. Kept in lockstep by\n * apps/api/src/__tests__/lib/otp-resend-cooldown-sync.test.ts - change both\n * together.\n */\nexport const OTP_RESEND_COOLDOWN_SECONDS = 60;\n\n/**\n * Accepted shape of a form share_id: more generous than the real 9-char hex slug, but it excludes\n * `/`, `.` and everything else a URL path segment could use to escape (see apps/dashboard/lib/saveTemplate.ts).\n */\nexport const SHARE_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;\n\n/**\n * The real shape of a form share_id: exactly 9 lowercase hex characters (every prod\n * share id). Stricter than SHARE_ID_PATTERN, which only keeps a URL segment safe.\n * A form alias must never match it (#3278), so a name can't be mistaken for an id.\n */\nexport const SHARE_ID_SHAPE = /^[0-9a-f]{9}$/;\nexport function isShareIdShape(value) {\n return typeof value === 'string' && SHARE_ID_SHAPE.test(value);\n}\n\n/** The one `/try?template=<share id>` builder (formUrl and tryUrl both use it). */\nfunction templateTryUrl(shareId, base) {\n return `${base}/try?template=${shareId}`;\n}\n\n/**\n * The anonymous-builder entry point (`FEATURES.anonymous_builder`, #2979):\n * mints a guest session and drops straight into the builder, no signup gate.\n * With a share id, links to that template's copy instead of a blank form\n * (`/try?template=<id>`); with a valid alias name (`isValidFormAlias`, #3278) it\n * builds the readable `/try/<name>`. `base` overrides the host (default: this environment's dashboard) for tools that must\n * always link to production, e.g. `PROD_URLS.dashboard`.\n */\nexport function tryUrl(idOrName, base = BUSINESS.urls.dashboard) {\n if (idOrName && isValidFormAlias(idOrName)) return `${base}/try/${idOrName}`;\n return idOrName ? templateTryUrl(idOrName, base) : `${base}/try`;\n}\n\n/**\n * Readable template-link names (#3278): `app.clipform.io/try/<name>`. Mirrored by\n * the CHECKs on `form_alias` (drift-tested against the migration). Lowercase\n * letters, digits and single dashes; 3-50 characters (length is enforced in\n * `isValidFormAlias`, not the pattern).\n */\nexport const FORM_ALIAS_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/;\nexport const FORM_ALIAS_MIN_LENGTH = 3;\nexport const FORM_ALIAS_MAX_LENGTH = 50;\n\n/** Names that could clash with a current or future `/try/*` or top-level route. */\nexport const FORM_ALIAS_RESERVED = [\n 'new', 'edit', 'admin', 'settings', 'login', 'signup', 'api', 'templates', 'template',\n 'try', 'claim', 'auth', 'oauth', 'internal', 'help', 'docs',\n];\n\n/**\n * True for a usable alias: right shape and length, not reserved, and never a\n * 9-hex string (that is a share id - every prod share id has exactly that shape).\n */\nexport function isValidFormAlias(name) {\n return (\n typeof name === 'string' &&\n name.length >= FORM_ALIAS_MIN_LENGTH &&\n name.length <= FORM_ALIAS_MAX_LENGTH &&\n FORM_ALIAS_PATTERN.test(name) &&\n !SHARE_ID_SHAPE.test(name) &&\n !FORM_ALIAS_RESERVED.includes(name)\n );\n}\n\n/**\n * The Powered-by CTA's fork entry (#857/#3777): same anonymous-builder mint\n * as `tryUrl`, but carries the source form's shareId as `?fork=` instead of\n * `?template=` - `/try` resolves this into a blank NODE-SHAPE skeleton\n * (`POST /v1/forms/skeleton`) rather than a full content clone (`?template=`'s\n * `/v1/forms/save/:shareId` path). Mirrors `tryImportUrl`'s gating: with the\n * flag off, falls back to the plain dashboard link rather than a dead `/try`.\n */\nexport function tryForkUrl(shareId) {\n return FEATURES.anonymous_builder.enabled\n ? `${BUSINESS.urls.dashboard}/try?fork=${encodeURIComponent(shareId)}`\n : BUSINESS.urls.dashboard;\n}\n\n/**\n * Normalizes a scheme-less paste (\"docs.google.com/forms/...\", the common\n * copy from an address bar) by prepending https://. `new URL()` throws on a\n * bare host (so provider detection would reject a perfectly valid form link),\n * and the API's `z.string().url()` would reject it too. Call this before\n * validating/sending so both checks see the same value the request body will\n * actually carry.\n */\nexport function normalizeFormUrl(value) {\n return /^[a-zA-Z][a-zA-Z0-9+.-]*:\\/\\//.test(value) ? value : `https://${value}`;\n}\n\n/**\n * The form import widget's target URL (#3414 SSOT promotion of\n * #3402's marketing-only `getGoogleImportUrl`; Typeform and Tally too, #3705): redirects into the\n * dashboard's `/try` anonymous lane with the (already normalized) form URL\n * as a query param, which runs the same anon sign-in + captcha +\n * at-limit-gate flow as the template path before calling\n * `POST /v1/forms/import/<provider>`. Consumed by both marketing\n * (`FormImportSection`) and docs (`FormImporter`) - neither app\n * calls the API directly.\n *\n * Mirrors `formUrl`'s `FEATURES.anonymous_builder` gating - unlike the\n * template path, there is no legacy signup-gated fallback for importing, so\n * with the flag off this falls back to the plain dashboard link (same as\n * marketing's `getTemplateCtaUrl`'s missing-share-id case,\n * `apps/marketing/src/lib/template-cta.ts`) rather than a dead `/try`.\n */\nexport function tryImportUrl(url) {\n return FEATURES.anonymous_builder.enabled\n ? `${BUSINESS.urls.dashboard}/try?import=${encodeURIComponent(url)}`\n : BUSINESS.urls.dashboard;\n}\n\n/**\n * Embeddable viewer iframe — single source of truth for embedding a form on a\n * third-party page. Consumed directly by anything inside our bundler (e.g. the\n * oEmbed endpoint in `apps/api`). Two artifacts run OUTSIDE the bundler and so\n * cannot import this — the static SDK (`apps/marketing/public/embed.js`) and\n * the standalone Framer component (`apps/embeds/framer/Clipform.tsx`) — and\n * carry a verbatim copy of `iframeAllow`. A parity test\n * (`apps/api/src/__tests__/lib/embed-allow-parity.test.ts`) fails if either\n * copy drifts from this value, so this stays the source of truth.\n */\nexport const EMBED = {\n // Permissions delegated to the cross-origin viewer iframe: recording\n // (camera/microphone), video (autoplay/fullscreen), Stripe wallets\n // (payment), the end-screen share button (web-share + clipboard-write), and\n // keeping the respondent's screen from auto-dimming mid-session (#2859).\n iframeAllow: 'camera; microphone; autoplay; fullscreen; payment; web-share; clipboard-write; screen-wake-lock',\n // Default 9:16 portrait box — matches embed.js DEFAULT_MAX_WIDTH (460px).\n defaultWidth: 460,\n defaultHeight: 818, // round(460 * 16 / 9)\n};\n\n/** Embeddable viewer URL for a form (the viewer's `display=embed` mode). */\nexport function embedViewerUrl(shareId) {\n return `${BUSINESS.urls.viewer}/${shareId}?display=embed`;\n}\n\n/**\n * Brand assets and visual identity\n */\nexport const BRAND = {\n logo: {\n primary: \"/logo.svg\",\n withText: \"/logo_text.svg\",\n icon: \"/favicon.ico\",\n iconSvg: \"/icon.svg\",\n appleTouchIcon: \"/apple-touch-icon.png\",\n minWidth: \"120px\",\n maxWidth: \"200px\",\n spacing: \"16px\",\n },\n colors: {\n primary: \"#171717\",\n secondary: \"#404040\",\n accent: \"#3182CE\",\n background: \"#FAFAFA\",\n surface: \"#FFFFFF\",\n border: \"#E5E5E5\",\n muted: \"#737373\",\n destructive: \"#DC2626\",\n success: \"#16A34A\",\n },\n fonts: {\n body: \"Inter, sans-serif\",\n headings: \"'Satoshi', Inter, sans-serif\",\n logo: \"'Plus Jakarta Sans', sans-serif\",\n satoshiImport: \"https://api.fontshare.com/v2/css?f[]=satoshi@400,500,700,900&display=swap\",\n },\n};\n\n/**\n * Plan limits — shared between API (enforcement), dashboard (UI gating), and viewer (branding)\n *\n * Keyed by plan_version string (e.g. 'free_v1', 'pro_v1') so we can\n * grandfather old limits when pricing changes. New signups get the version\n * from CURRENT_PLAN_VERSIONS; existing companies keep theirs until\n * explicitly migrated.\n *\n * Per-version billing identity is provider-agnostic (#1027): `price_cents` is\n * the canonical machine-readable price (the `price` string is display-only);\n * `stripe_price_id` and `shopify_plan_handle` map the version to each biller.\n * `shopify_plan_handle` is null until the matching Shopify App Pricing plan is\n * created in the Partner Dashboard.\n */\nexport const PLAN_LIMITS = {\n free_v1: {\n tier: 0,\n name: 'Free',\n price: '$0',\n period: 'forever',\n price_cents: 0,\n stripe_price_id: { test: null, live: null },\n // Shopify App Pricing plan NAME (must match the Partner Dashboard plan\n // exactly - the app_subscriptions/update payload carries this name). Free\n // generates no subscription, so this is only used by the drift check.\n shopify_plan_handle: 'Free',\n // Platform commission on payments collected by a Free-plan creator, in\n // basis points (#3831). Live at 500 (5%) - paid tiers stay 0%. Retained\n // on refund by design (industry standard - Stripe keeps `application_fee`\n // unless `refund_application_fee` is set). See create-payment-intent.ts\n // for the fee gate.\n platform_fee_bps: 500,\n node_limit: null,\n form_limit: 5,\n workspace_limit: 1,\n show_branding: true,\n custom_theme: false,\n dynamic_links: false,\n custom_domain: false,\n response_limit: 100,\n features: [\n 'Up to 5 forms',\n 'Unlimited questions per form',\n // \"completed\" is not a tightening: response_limit has always been 100,\n // but the counter now excludes partials (#2618), so this wording is both\n // accurate and strictly more generous than what it replaced.\n '100 completed responses per month',\n 'Full AI tooling (TTS, media, video)',\n 'Clipform branding',\n ],\n },\n pro_v1: {\n tier: 1,\n name: 'Pro',\n price: '$25',\n period: '/month',\n price_cents: 2500,\n stripe_price_id: { test: 'price_1TZnmhCWdEPD0KoNWWJTc3B6', live: 'price_1TZnrZEJOD9ik3LhhFwGZ6ut' },\n // Must match the Partner Dashboard plan name exactly (drives webhook plan\n // mapping + the price drift check). Keep in step with price_cents above.\n shopify_plan_handle: 'Pro',\n // Paid tier - platform takes 0% (#3831). Free is the only tier with a\n // commission, and only once go-live flips it on.\n platform_fee_bps: 0,\n node_limit: null,\n form_limit: null,\n workspace_limit: null,\n show_branding: false,\n custom_theme: true,\n dynamic_links: true,\n custom_domain: true,\n response_limit: null,\n features: [\n 'Unlimited forms',\n 'Unlimited questions',\n 'Unlimited responses',\n 'Custom themes & colors',\n 'Remove Clipform branding',\n 'Dynamic links - repoint a printed URL to a new form',\n ],\n },\n\n // Banded Pro (#1937). pro_v2_1k IS the current tier-1 version (#2671) - new\n // Pro signups land here; pro_v1 is retained only to grandfather the accounts\n // that predate the flip.\n //\n // Billing is one subscription with TWO Stripe items: this licensed base\n // billed in advance, plus a volume-tiered metered top-up (STRIPE_BAND_PRICE_ID\n // below) billed in arrears - so the band a workspace lands in is decided by\n // usage, never by swapping plan version. Completed responses report to the\n // Stripe usage meter (#2651, apps/api/src/lib/usage-metering.ts) via\n // planMetersUsage below, and checkout appends the metered item whenever a band\n // price is configured for the mode (#2652). The band price now exists in BOTH\n // test and live (STRIPE_BAND_PRICE_ID), so a new Pro checkout is two-item and\n // usage above the base band IS charged once this deploys - the HUMAN LEGAL\n // REVIEW on LEGAL.billing below must clear before that go-live.\n //\n // `response_limit` counts COMPLETED submissions only (#4118: per completed\n // form_session, grandfathered pre-cutover as completed response sets - see\n // count_workspace_responses_this_month); partials never consume allowance.\n //\n // shopify_plan_handle is null until the matching Partner Dashboard plans\n // exist - so planVersionForShopifyPlan still maps Shopify's \"Pro\" to pro_v1\n // ($25 unlimited) while web signups get this band. Creating those plans is\n // what closes that cross-channel gap.\n pro_v2_1k: {\n tier: 1,\n name: 'Pro',\n price: '$24',\n period: '/month',\n price_cents: 2400,\n stripe_price_id: {\n test: 'price_1U0lA6EJOD9ik3Lhube5eBcK',\n live: 'price_1U115SEJOD9ik3LhOU9OkqJk',\n },\n shopify_plan_handle: null,\n // Paid tier - platform takes 0% (#3831).\n platform_fee_bps: 0,\n node_limit: null,\n form_limit: null,\n workspace_limit: null,\n show_branding: false,\n custom_theme: true,\n dynamic_links: true,\n custom_domain: true,\n response_limit: 1000,\n features: [\n 'Unlimited forms',\n 'Unlimited questions',\n '1,000 completed responses per month',\n 'Custom themes & colors',\n 'Remove Clipform branding',\n 'Dynamic links - repoint a printed URL to a new form',\n 'Send form events to Google Tag Manager and Meta Pixel',\n ],\n },\n pro_v2_5k: {\n tier: 1,\n name: 'Pro',\n price: '$49',\n period: '/month',\n price_cents: 4900,\n stripe_price_id: { test: null, live: null },\n shopify_plan_handle: null,\n // Paid tier - platform takes 0% (#3831).\n platform_fee_bps: 0,\n node_limit: null,\n form_limit: null,\n workspace_limit: null,\n show_branding: false,\n custom_theme: true,\n dynamic_links: true,\n custom_domain: true,\n response_limit: 5000,\n features: [\n 'Unlimited forms',\n 'Unlimited questions',\n '5,000 completed responses per month',\n 'Custom themes & colors',\n 'Remove Clipform branding',\n 'Dynamic links - repoint a printed URL to a new form',\n 'Send form events to Google Tag Manager and Meta Pixel',\n ],\n },\n pro_v2_20k: {\n tier: 1,\n name: 'Pro',\n price: '$99',\n period: '/month',\n price_cents: 9900,\n stripe_price_id: { test: null, live: null },\n shopify_plan_handle: null,\n // Paid tier - platform takes 0% (#3831).\n platform_fee_bps: 0,\n node_limit: null,\n form_limit: null,\n workspace_limit: null,\n show_branding: false,\n custom_theme: true,\n dynamic_links: true,\n custom_domain: true,\n response_limit: 20000,\n features: [\n 'Unlimited forms',\n 'Unlimited questions',\n '20,000 completed responses per month',\n 'Custom themes & colors',\n 'Remove Clipform branding',\n 'Dynamic links - repoint a printed URL to a new form',\n 'Send form events to Google Tag Manager and Meta Pixel',\n ],\n },\n};\n\n/**\n * Whether a workspace's response_limit counts only COMPLETED submissions -\n * i.e. an in-progress (not yet completed) response never consumes the cap.\n * True today for every plan (#4118, apps/api's\n * count_workspace_responses_this_month RPC is the actual enforcement). A\n * policy fact repeated here - NOT a mirror of the SQL - so marketing's\n * `partial_responses_free` claim (PRICING_CLAIMS below) has something to\n * assert against; keep this in step BY HAND with the RPC if that counting\n * rule ever changes.\n */\nexport const RESPONSE_LIMIT_COUNTS_COMPLETED_ONLY = true;\n\n/**\n * Pricing claims marketing copy may cite by key (ads `claims: string[]`,\n * #4338 - mirrors FEATURES for pricing facts, which have no\n * enabled/status lifecycle). Each key's truth is asserted directly against\n * PLAN_LIMITS (or another named config truth) in test/pricing-claims.test.js -\n * a plan change that breaks the assertion fails CI instead of leaving a\n * stale claim live in ad copy or content.\n */\nexport const PRICING_CLAIMS = {\n free_plan: {\n description: 'Clipform has a genuinely free plan, not a time-limited trial',\n },\n no_credit_card: {\n description: 'Signing up for the free plan never asks for a card',\n },\n partial_responses_free: {\n description: \"An in-progress response never counts against the free plan's response cap\",\n },\n unlimited_questions: {\n description: 'The free plan has no limit on questions per form',\n },\n};\n\n/**\n * Maps tier integer → version string assigned to new signups.\n *\n * Tier 1 is a BAND (#1937): new Pro signups get pro_v2_1k ($24 / 1,000\n * completed responses). Existing companies keep their stored plan_version, so\n * the pro_v1 accounts predating this stay on unlimited - grandfathered, never\n * migrated. Nothing charges for exceeding a band yet (#2651 meters usage,\n * #2652 makes checkout two-item); until then an over-band customer keeps\n * collecting, stays fully visible, and the excess is absorbed.\n */\nexport const CURRENT_PLAN_VERSIONS = { 0: 'free_v1', 1: 'pro_v2_1k' };\n\n/**\n * Ordered Pro bands for the pricing slider (#1937). DERIVED from PLAN_LIMITS -\n * never define band prices or limits here. Ascending by response_limit.\n *\n * The pricing page renders a final \"talk to us\" stop beyond the last band;\n * that is presentation, not a plan version, so it lives in the component.\n */\nexport const PRO_BANDS = ['pro_v2_1k', 'pro_v2_5k', 'pro_v2_20k'].map(\n (version) => ({ version, ...PLAN_LIMITS[version] })\n);\n\n/**\n * The single volume-tiered METERED Stripe price that carries banded Pro usage\n * (#1937 / #2652). ONE price spans every band: Stripe's `tiers_mode: 'volume'`\n * selects the band from the MAX usage in the period, so the band a customer\n * lands in is decided by usage, never by swapping plan_version. It is therefore\n * a tier-level fact and lives here ONCE, not on each pro_v2_* entry.\n *\n * Deliberately NOT any PLAN_LIMITS[*].stripe_price_id: it is metered and billed\n * in ARREARS (the licensed base is billed in advance), and it must NEVER resolve\n * through planVersionForStripePrice - that maps the LICENSED base price to a\n * plan version, and letting the band price match would reintroduce #2678 (the\n * webhook picking the band item as the \"plan\" item, writing the wrong\n * plan_version and billing period). Checkout appends it as a second\n * subscription item (#2652); the webhook plan projection ignores it.\n *\n * NEVER attach Stripe billing thresholds to this price: combined with volume\n * tiers they can produce NEGATIVE invoice line items (#1937).\n *\n * Both `test` and `live` are set: the live price (volume-tiered $0/$25/$75/$75,\n * metered against `mtr_61VAPLMBymP6O56H441EJOD9ik3LhCfA` on Pro product\n * `prod_UOCjM0hFrt0XYw`, tax_behavior exclusive) was created by hand in the\n * live Stripe dashboard. So LIVE checkout is two-item the moment this deploys -\n * see the deploy-gated HUMAN LEGAL REVIEW note on LEGAL.billing below.\n */\nexport const STRIPE_BAND_PRICE_ID = {\n test: 'price_1U0lEsEJOD9ik3Lhs4ttMplT',\n live: 'price_1U1RABEJOD9ik3LhBDfNGlfZ',\n};\n\n/**\n * Whether a plan hides over-limit responses behind the paygate.\n *\n * Only the free tier redacts. A PAID plan with a finite response_limit\n * (banded Pro - pro_v2_*) escalates the charge to the band reached and keeps\n * everything visible (#1937), so a numeric response_limit alone must never\n * imply redaction. See #2650.\n */\nexport function planRedactsOverLimit(limits) {\n return limits?.tier === 0 && limits?.response_limit != null;\n}\n\n/**\n * Whether a plan's completed responses should be reported to the Stripe usage\n * meter (#2651).\n *\n * A metered band is a PAID plan (tier > 0) with a finite response_limit -\n * i.e. banded Pro (pro_v2_*). Deliberately NOT a `pro_v2_*` string match:\n * config is the source of truth for which versions meter, so a future band\n * (or a grandfathered pro_v1 unlimited account, which must never meter)\n * follows from its shape alone. pro_v1 has `response_limit: null` (unlimited)\n * so it correctly never meters; free_v1 is tier 0 so it correctly never\n * meters either (its cap is enforced by paygate/redaction, not billing).\n */\nexport function planMetersUsage(limits) {\n return limits?.tier > 0 && limits?.response_limit != null;\n}\n\n/**\n * Pricing-card feature lines for a plan version - `PLAN_LIMITS[version].features`\n * plus a derived platform-commission line (#3831), single source so a pricing\n * card never hand-writes the fee copy. Lights up automatically off whatever\n * `platform_fee_bps` carries per tier - no caller change needed. Never\n * hardcode a percentage - always derive it from here.\n *\n * - A tier whose OWN `platform_fee_bps` is > 0 gets its real rate:\n * `${bps / 100}% commission on payments collected`.\n * - Once ANY tier in PLAN_LIMITS carries a commission, every OTHER (0-bps)\n * paid tier (`tier > 0`) gets the contrasting `Keep 100% of payments - no\n * platform fee` line, so Pro reads as the fee-free alternative the moment\n * Free's fee is live. A paid tier never gets its own commission line today\n * (every paid `platform_fee_bps` is permanently 0), but the check is written against\n * the tier's own bps first so a future paid-tier fee would still show its\n * real rate instead of the contrasting copy.\n */\nexport function planFeatureLines(version) {\n const limits = PLAN_LIMITS[version];\n if (!limits) return [];\n\n const bps = limits.platform_fee_bps ?? 0;\n if (bps > 0) {\n return [...limits.features, `${bps / 100}% commission on payments collected`];\n }\n\n const anyFeeActive = Object.values(PLAN_LIMITS).some((p) => (p.platform_fee_bps ?? 0) > 0);\n if (anyFeeActive && limits.tier > 0) {\n return [...limits.features, 'Keep 100% of payments - no platform fee'];\n }\n\n return [...limits.features];\n}\n\n/**\n * Product information and features\n */\nexport const PRODUCT = {\n features: {\n get core() {\n return getLiveFeatures()\n .filter(f => ['node-types', 'responses', 'builder', 'analytics', 'ai'].includes(f.category))\n .map(f => f.name);\n },\n get premium() {\n return getLiveFeatures()\n .filter(f => ['sharing', 'api'].includes(f.category))\n .map(f => f.name);\n },\n },\n // Derived from PLAN_LIMITS (source of truth)\n get pricing() {\n const free = PLAN_LIMITS[CURRENT_PLAN_VERSIONS[0]];\n const pro = PLAN_LIMITS[CURRENT_PLAN_VERSIONS[1]];\n return {\n free: { name: free.name, price: free.price, period: free.period, features: free.features },\n pro: { name: pro.name, price: pro.price, period: pro.period, features: pro.features },\n };\n },\n};\n\n/**\n * Social media links\n */\nexport const SOCIAL = {\n twitter: \"@clipform\",\n linkedin: \"company/clipform\",\n github: \"clipform\",\n urls: {\n twitter: \"https://twitter.com/clipform\",\n linkedin: \"https://linkedin.com/company/clipform\",\n github: \"https://github.com/clipform\",\n },\n};\n\n/**\n * Ad tracking switch (#4900). When false, nothing reaches an ad platform:\n * neither app loads the GTM container (Google Ads tag + Meta Pixel), and\n * `fireSignupConversion` neither pushes the `sign_up` event nor calls the\n * server relay for Meta CAPI / Google Ads (so no hashed email is sent).\n * NEXT_PUBLIC_GTM_ID and the META_CAPI_* / GOOGLE_ADS_* env vars can stay set.\n *\n * Before turning this on: add consent (banner or GTM Consent Mode - ad tags\n * aren't \"strictly necessary\" under UK GDPR/PECR) and update the privacy\n * policy, which says there are no advertising trackers and that Google user\n * data is never used for advertising.\n */\nexport const AD_TRACKING_ENABLED = false;\n\n/**\n * Legal and compliance\n */\n/**\n * Legal facts - single source of truth for /terms and /privacy (#459).\n * Pages derive entity names, contacts, dates, and numbers from here;\n * never hardcode them in page copy.\n *\n * Drafting principle: minimum legally-required disclosure only. No voluntary\n * commitments, no named vendors in public docs (categories of recipients\n * satisfy UK GDPR Art 13(1)(e)), no published DPA until a customer requests\n * one. Shortest legally-sufficient wording everywhere.\n */\nexport const LEGAL = {\n company: \"Reco Ventures Ltd.\",\n companyCountry: \"United Kingdom\",\n governingLaw: \"England and Wales\",\n copyright: \"© 2026 Clipform. All rights reserved.\",\n privacy: \"/privacy\",\n terms: \"/terms\",\n privacyEmail: \"hello@clipform.io\", // GDPR contact - no separate DPO mailbox\n termsUpdated: \"2026-09-08\",\n privacyUpdated: \"2026-11-12\",\n minAge: 18, // contract capacity; no parental-consent handling\n billing: {\n processor: \"Stripe\", // live\n // Banded Pro (#1937/#2652) is a hybrid charge on ONE subscription: a flat\n // monthly base billed in ADVANCE, plus variable usage-based charges for\n // completed responses above the base band, billed in ARREARS at period end\n // and auto-escalated to the band reached. Auto-renews; cancellation is\n // effective at the end of the current period.\n // HUMAN LEGAL REVIEW REQUIRED before go-live (#2652): the rendered /terms\n // prose does not yet describe variable/auto-escalating usage charges, and\n // UK consumer rules want express consent to variable charges captured at\n // checkout.\n model: \"base-plus-usage-recurring\",\n // HUMAN LEGAL REVIEW REQUIRED before go-live (#2652): \"none\" pairs badly\n // with auto-escalating usage charges - the first bot storm or viral spike\n // that inflates a bill needs discretion to exist in writing.\n refunds: \"none\", // except at our sole discretion\n },\n // Total liability capped at fees paid in the prior 12 months (free = zero),\n // plus standard as-is / no indirect damages wording.\n liabilityCapMonths: 12,\n // Account/data deletion completed within this window (incl. Mux assets +\n // Supabase storage; backups may persist briefly beyond).\n deletionDays: 30,\n // Aggregated/anonymized data: rights reserved via quiet drafting - folded\n // into the content licence (terms s5) and lawful-bases (privacy s3) rather\n // than a standalone billboard section. Covers product improvement,\n // benchmarks, published insights; never re-identified.\n //\n // Internal only - NOT rendered anywhere. Kept current so a DPA can be\n // produced the day a customer requests one. Public docs disclose\n // categories of recipients only.\n subprocessors: [\n { name: \"Supabase\", purpose: \"Database and file storage\" },\n { name: \"Mux\", purpose: \"Video hosting and streaming\" },\n { name: \"Vercel\", purpose: \"Web hosting\" },\n { name: \"Render\", purpose: \"API hosting\" },\n { name: \"AWS\", purpose: \"Video rendering (Lambda)\" },\n { name: \"PostHog\", purpose: \"Product analytics and error tracking\" },\n { name: \"Cloudflare\", purpose: \"DNS, CDN, email routing\" },\n { name: \"Stripe\", purpose: \"Payment processing\" },\n { name: \"Anthropic\", purpose: \"AI form generation\" },\n { name: \"OpenAI\", purpose: \"AI form generation; content moderation of responses\" },\n { name: \"Groq\", purpose: \"Transcription and AI summaries of voice and video responses\" },\n ],\n};\n\n/**\n * Standard contact form field definitions\n * Source of truth for both dashboard (field picker) and viewer (form rendering)\n */\nexport const CONTACT_FIELDS = [\n { id: 'first_name', label: 'First Name', type: 'text', placeholder: 'Enter first name', order: 1 },\n { id: 'last_name', label: 'Last Name', type: 'text', placeholder: 'Enter last name', order: 2 },\n { id: 'email', label: 'Email Address', type: 'email', placeholder: 'you@example.com', order: 3 },\n { id: 'phone', label: 'Phone Number', type: 'tel', placeholder: '(555) 123-4567', order: 4 },\n];\n\nexport const CONTACT_FIELDS_MAP = Object.fromEntries(\n CONTACT_FIELDS.map(f => [f.id, f])\n);\n\n// Fields that used to be standard; kept only so old forms keep readable names.\nconst RETIRED_CONTACT_FIELD_LABELS = {\n company: 'Company',\n job_title: 'Job Title',\n website: 'Website',\n linkedin: 'LinkedIn Profile',\n message: 'Message',\n};\n\n/**\n * The one name a details field shows on every creator surface (#5577): the\n * Responses table, the response panel and the CSV/Excel export. A standard\n * field (email, phone, ...) always shows its CONTACT_FIELDS label, whatever an\n * agent or import stored; a custom field shows its own label; any other id\n * config does not define falls back to its stored label, then the id. A blank\n * label, or one equal to the id, counts as no label.\n */\nexport function contactFieldLabel(field) {\n if (Object.hasOwn(CONTACT_FIELDS_MAP, field.id) && !field.is_custom) {\n return CONTACT_FIELDS_MAP[field.id].label;\n }\n const stored = typeof field.label === 'string' ? field.label.trim() : '';\n if (stored && stored !== field.id) return stored;\n if (!field.is_custom && Object.hasOwn(RETIRED_CONTACT_FIELD_LABELS, field.id)) {\n return RETIRED_CONTACT_FIELD_LABELS[field.id];\n }\n return field.id;\n}\n\n/**\n * The input type of a details field (#6267), the one rule the viewer and the dashboard share so they can't disagree\n * about which fields are emails: a custom field's own `type`, a standard field's config type, else `text`.\n */\nexport function contactFieldType(field) {\n if (field?.is_custom) return field.type || 'text';\n const def = Object.hasOwn(CONTACT_FIELDS_MAP, field?.id) ? CONTACT_FIELDS_MAP[field.id] : undefined;\n return def?.type || 'text';\n}\n\n/**\n * The one order details steps are named, laid out and read in: created_at,\n * then id. Returns a new array; callers pass nodes with `id` and `created_at`.\n */\nexport function sortDetailsSteps(detailsNodes) {\n const key = (n) => (typeof n?.created_at === 'string' ? n.created_at : '');\n return (Array.isArray(detailsNodes) ? [...detailsNodes] : []).sort((a, b) => {\n const x = key(a);\n const y = key(b);\n if (x !== y) return x < y ? -1 : 1;\n const i = String(a?.id ?? '');\n const j = String(b?.id ?? '');\n return i < j ? -1 : i > j ? 1 : 0;\n });\n}\n\n/**\n * One name per details step (#5535), the same on every surface (table, export,\n * response panel). Pass every details step to consider, in creation order:\n * that is the stable key, so rewiring the flow never renames a step. A step is\n * named by, first that applies: its label (unless blank or the default type\n * name), its config.title, else \"Details N\" (N = 1-based creation position).\n * Steps that end up with the same name each get \" N\" appended.\n * Steps are sorted here by created_at then id (a duplicated form inserts every\n * node with one now(), so created_at alone can tie), so no caller can drift.\n * Returns Map<nodeId, name>.\n * With `recall` (5696) a label or title holding recall codes shows its chip labels.\n */\nexport function detailsStepNames(detailsNodes, recall) {\n const defaultLabel = NODE_TYPE_DEFS.details.label;\n const clean = (v) => (typeof v === 'string' ? (recall ? recallDisplayText(v, recall) : v).trim() : '');\n const nodes = sortDetailsSteps(detailsNodes);\n const names = nodes.map((node, i) => {\n const label = clean(node?.label);\n if (label && label !== defaultLabel) return label;\n const title = clean(node?.config?.title);\n if (title) return title;\n return `${defaultLabel} ${i + 1}`;\n });\n const counts = new Map();\n for (const name of names) counts.set(name, (counts.get(name) ?? 0) + 1);\n const out = new Map();\n nodes.forEach((node, i) => {\n out.set(node.id, counts.get(names[i]) > 1 ? `${names[i]} ${i + 1}` : names[i]);\n });\n return out;\n}\n\n/**\n * The columns a form's details steps produce in the Responses table and the\n * CSV/Excel export (#5535). One rule for both: a field or agreement asked in\n * one step is one column (bare id, no nodeId); asked in more than one step it\n * is one column per step, named after the step. The first step keeps the bare\n * id (so an existing pin keeps working); later steps get `${id}:${nodeId}`.\n * `detailsNodes` are sorted here by created_at then id (the order\n * detailsStepNames numbers them in); `stepNames` is detailsStepNames'\n * map (node id -> step name), so every surface names a step the same way.\n * Returns { fields: [{ id, fieldId, label, nodeId? }],\n * consent: [{ id, itemId, label, hasDocument, nodeId? }] }.\n */\nexport function detailsColumns(detailsNodes, stepNames) {\n const nodes = sortDetailsSteps(detailsNodes);\n const fieldSteps = new Map();\n const itemSteps = new Map();\n for (const node of nodes) {\n for (const field of node?.config?.fields ?? []) {\n if (!field?.id) continue;\n const set = fieldSteps.get(field.id) ?? new Set();\n set.add(node.id);\n fieldSteps.set(field.id, set);\n }\n for (const item of node?.config?.consent_items ?? []) {\n if (!item?.id) continue;\n const set = itemSteps.get(item.id) ?? new Set();\n set.add(node.id);\n itemSteps.set(item.id, set);\n }\n }\n const fields = [];\n const consent = [];\n const seenField = new Map();\n const seenItem = new Map();\n nodes.forEach((node) => {\n const title = () => (stepNames?.get(node.id) ?? NODE_TYPE_DEFS.details.label);\n for (const field of node?.config?.fields ?? []) {\n if (!field?.id) continue;\n const seen = seenField.get(field.id) ?? new Set();\n if (seen.has(node.id)) continue;\n const first = seen.size === 0;\n seen.add(node.id);\n seenField.set(field.id, seen);\n const name = contactFieldLabel({ id: field.id, label: field.label, is_custom: field.is_custom });\n if (fieldSteps.get(field.id).size <= 1) {\n fields.push({ id: field.id, fieldId: field.id, label: name });\n } else {\n fields.push({\n id: first ? field.id : `${field.id}:${node.id}`,\n fieldId: field.id,\n label: `${name} - ${title()}`,\n nodeId: node.id,\n });\n }\n }\n for (const item of node?.config?.consent_items ?? []) {\n if (!item?.id) continue;\n const seen = seenItem.get(item.id) ?? new Set();\n if (seen.has(node.id)) continue;\n const first = seen.size === 0;\n seen.add(node.id);\n seenItem.set(item.id, seen);\n const name = item.name || 'Agreement';\n const hasDocument = !!item.document;\n if (itemSteps.get(item.id).size <= 1) {\n consent.push({ id: `consent:${item.id}`, itemId: item.id, label: name, hasDocument });\n } else {\n consent.push({\n id: first ? `consent:${item.id}` : `consent:${item.id}:${node.id}`,\n itemId: item.id,\n label: `${name} - ${title()}`,\n hasDocument,\n nodeId: node.id,\n });\n }\n }\n });\n return { fields, consent };\n}\n\n// The details steps whose answers a column reads: its own step when scoped,\n// else every details step in the caller's order.\nfunction stepsFor(detailsNodeIds, column) {\n return column.nodeId ? [column.nodeId] : detailsNodeIds;\n}\n\nfunction answerOf(nodeResponses, nodeId) {\n if (!nodeResponses || !Object.hasOwn(nodeResponses, nodeId)) return undefined;\n const value = nodeResponses[nodeId]?.value;\n return value && typeof value === 'object' ? value : undefined;\n}\n\n/**\n * A details column's answer text (#5535). Scoped column (nodeId): that step's\n * answer only. Unscoped: first non-empty match across the details steps.\n * `nodeResponses` is a submission's node_responses map. Returns '' when none.\n */\nexport function detailsFieldValue(nodeResponses, detailsNodeIds, column) {\n for (const nodeId of stepsFor(detailsNodeIds, column)) {\n const fields = answerOf(nodeResponses, nodeId)?.fields;\n if (!Array.isArray(fields)) continue;\n const match = fields.find((f) => f?.id === column.fieldId);\n if (match?.value) {\n return typeof match.value === 'object' ? JSON.stringify(match.value) : String(match.value);\n }\n }\n return '';\n}\n\n/**\n * A details agreement column's stored record (#5535), same scoping as\n * detailsFieldValue. Undefined when the respondent has no record for it.\n */\nexport function detailsConsentValue(nodeResponses, detailsNodeIds, column) {\n for (const nodeId of stepsFor(detailsNodeIds, column)) {\n const consent = answerOf(nodeResponses, nodeId)?.consent;\n if (!Array.isArray(consent)) continue;\n const match = consent.find((c) => c?.id === column.itemId);\n if (match) return match;\n }\n return undefined;\n}\n\n/**\n * The write-side half of contactFieldLabel (#5586): a standard details field\n * (first_name, last_name, email, phone) is always the standard field, so its\n * stored label is dropped; a non-custom field with an id config does not define\n * becomes a custom field so it still has a real name. Pure - returns a new\n * array and never mutates the input. Non-array input passes through unchanged.\n * Returns { fields, ignoredLabels, madeCustom }: the ids whose label was\n * dropped (only when it differed from the config name, ignoring case) and the\n * ids converted to custom fields.\n */\nexport function normalizeContactFields(fields) {\n if (!Array.isArray(fields)) return { fields, ignoredLabels: [], keptStandard: [], madeCustom: [] };\n const ignoredLabels = [];\n const keptStandard = [];\n const madeCustom = [];\n const out = fields.map((field) => {\n if (!field || typeof field !== 'object' || typeof field.id !== 'string') return field;\n if (Object.hasOwn(CONTACT_FIELDS_MAP, field.id)) {\n const { label, ...rest } = field;\n const stored = typeof label === 'string' ? label.trim() : '';\n const differs = stored !== '' && stored.toLowerCase() !== CONTACT_FIELDS_MAP[field.id].label.toLowerCase();\n if (differs) ignoredLabels.push(field.id);\n else if (field.is_custom === true) keptStandard.push(field.id);\n return { ...rest, is_custom: false };\n }\n // A blank id is not a field we can name: leave it for validation, unnoted.\n if (!field.is_custom && field.id.trim() !== '') {\n madeCustom.push(field.id);\n return { ...field, is_custom: true, label: contactFieldLabel(field) };\n }\n return field;\n });\n return { fields: out, ignoredLabels, keptStandard, madeCustom };\n}\n\n// Notes stay one sentence each and well under the openapi warnings maxLength (2000).\nconst NOTE_MAX_IDS = 5;\nconst NOTE_MAX_ID_LENGTH = 40;\nfunction noteIds(ids) {\n const unique = [...new Set(ids)];\n const shown = unique\n .slice(0, NOTE_MAX_IDS)\n .map((id) => `\"${id.length > NOTE_MAX_ID_LENGTH ? id.slice(0, NOTE_MAX_ID_LENGTH) + '...' : id}\"`);\n const more = unique.length - NOTE_MAX_IDS;\n return shown.join(', ') + (more > 0 ? ` and ${more} more` : '');\n}\nconst standardNames = (ids) => [...new Set(ids)].map((id) => `\"${CONTACT_FIELDS_MAP[id]?.label ?? id}\"`).join(', ');\n\n/** Tool-result note for standard-field labels dropped by normalizeContactFields. */\nexport function ignoredContactLabelNote(ids) {\n return `Standard field(s) ${noteIds(ids)} always show their config name (${standardNames(ids)}), so their labels were ignored. ` +\n 'For other wording or another language, add a custom field ({ id, is_custom: true, label, type }).';\n}\n\n/** Tool-result note for standard ids sent as custom, kept as the standard field. */\nexport function keptStandardContactNote(ids) {\n return `Standard field(s) ${noteIds(ids)} cannot be custom, so they were kept as the standard field (${standardNames(ids)}).`;\n}\n\n/** Tool-result note for unknown non-custom ids converted to custom fields. */\nexport function madeCustomContactNote(ids) {\n return `Field(s) ${noteIds(ids)} are not standard fields (first_name, last_name, email, phone), so they were saved as custom fields.`;\n}\n\n/** All notes for a normalizeContactFields result (empty when nothing changed). */\nexport function contactFieldNotes(result) {\n const notes = [];\n if (result.ignoredLabels.length) notes.push(ignoredContactLabelNote(result.ignoredLabels));\n if (result.keptStandard?.length) notes.push(keptStandardContactNote(result.keptStandard));\n if (result.madeCustom.length) notes.push(madeCustomContactNote(result.madeCustom));\n return notes;\n}\n\n/**\n * Details-node consent item types (#5614). A value in CONSENT_TYPES passes\n * through; 'optional' / 'opt-in' / 'optin' (case-insensitive) mean 'opt_in';\n * undefined / null stay as they are (a missing type is allowed); anything else\n * becomes 'consent' (a required agreement). Pure.\n */\nexport function normalizeConsentType(type) {\n if (type === undefined || type === null) return type;\n const v = typeof type === 'string' ? type.trim().toLowerCase() : type;\n if (CONSENT_TYPES.includes(v)) return v;\n if (['optional', 'opt-in', 'optin', 'opt in'].includes(v)) return 'opt_in';\n return 'consent';\n}\n\n/**\n * Normalize every consent item's type. Pure - returns new objects and never\n * mutates the input. Non-array input passes through. `coerced` lists only the\n * items whose type actually changed.\n */\nexport function normalizeConsentItems(items) {\n if (!Array.isArray(items)) return { items, coerced: [] };\n const coerced = [];\n const out = items.map((item) => {\n if (!item || typeof item !== 'object') return item;\n const to = normalizeConsentType(item.type);\n if (to === item.type) return { ...item };\n coerced.push({ id: item.id, from: item.type, to });\n return { ...item, type: to };\n });\n return { items: out, coerced };\n}\n\n/** All notes for a normalizeConsentItems result (empty when nothing changed). */\nexport function consentItemNotes(result) {\n if (!result.coerced.length) return [];\n const clip = (v) => {\n const t = typeof v === 'string' ? v : v === undefined || v === null ? '(none)' : JSON.stringify(v) ?? String(v);\n return t.length > NOTE_MAX_ID_LENGTH ? t.slice(0, NOTE_MAX_ID_LENGTH) + '...' : t;\n };\n const shown = result.coerced\n .slice(0, NOTE_MAX_IDS)\n .map((c) => `\"${clip(typeof c.id === 'string' ? c.id : '(no id)')}\" (\"${clip(c.from)}\" -> \"${clip(c.to)}\")`);\n const more = result.coerced.length - NOTE_MAX_IDS;\n return [\n `Consent item(s) ${shown.join(', ')}${more > 0 ? ` and ${more} more` : ''} had a type that is not a consent type, so they were saved as shown. ` +\n 'Use \"consent\" for a required agreement or \"opt_in\" for an optional one.',\n ];\n}\n\n/**\n * Details-node field icons — single source of truth (#2826). Both the Builder\n * (ContactNode) and the Responses table resolve through resolveContactFieldIcon\n * so a field shows the same icon on both surfaces. Values are Lucide component\n * name strings; each consumer maps the string to the component.\n */\nexport {\n CONTACT_FIELD_TYPE_ICONS,\n CONTACT_FIELD_STANDARD_ICONS,\n CONTACT_FIELD_ICON_FALLBACK,\n resolveContactFieldIcon,\n} from './field-icons.js';\n\n/**\n * The public \"Templates\" workspace. Curated template forms live here (promoted\n * via scripts/promote-form.ts); the template gallery (GET /v1/forms/templates)\n * is scoped to this workspace so a form flagged is_template in ANY other\n * workspace can't leak into it (#1370). Re-exported from\n * apps/api/src/lib/constants.ts so api and scripts/promote-form.ts share one\n * definition.\n */\nexport const CLIPFORM_TEMPLATES_WORKSPACE_ID = \"00000000-0000-4000-b000-000000000100\";\n\n/**\n * Curated allowlist for the dashboard \"New Form -> Select Template\" picker,\n * in display order (#3928). This is the single curation lever for the picker -\n * `is_live` no longer trims it. Every template in the Templates workspace stays\n * `is_live=true` (so its poster/embed/preview resolves via the is_live-gated\n * public path, and marketing pages that embed a template never break); which\n * ones a user sees when creating a form is decided here.\n *\n * PROD `share_id`s. Templates get a fresh share_id when promoted dev->prod\n * (scripts/promote-form.ts mints a new dynamic_link), so these match nothing in\n * dev - GET /v1/forms/templates falls back to showing all templates when the\n * allowlist matches none (see list-templates.ts). So this curates prod; dev\n * shows everything. Every id here MUST be is_live=true or its preview 404s.\n */\nexport const TEMPLATE_PICKER_SHARE_IDS = [\n \"78a5fc05c\", // Client Intake\n \"51e1b300b\", // Customer Feedback\n \"0f9c3f829\", // Event Registration\n \"3986f0fbb\", // Lead Capture\n \"14868ac21\", // Video Testimonial\n \"13fe6ff6a\", // Video Interview\n \"b9d64f65c\", // General Knowledge Quiz\n];\n\n/**\n * Node type definitions — re-exported from node-types.js\n */\nexport {\n NODE_TYPES,\n NODE_TYPES_LIST,\n getActiveNodeTypes,\n ACTIVE_NODE_TYPES,\n NODE_TYPE_KEYS,\n END_SCREEN_ICONS,\n resolveEndScreenIcon,\n OWNER_SCOPED_CONFIG_KEYS,\n gatedConfigKeys,\n gatedEnumValues,\n stripGatedConfigKeys,\n validateFeatureMarkers,\n RESPONSE_FORMATS,\n CONSENT_TYPES,\n CONTACT_FIELD_TYPES,\n CHOICE_MAX_OPTIONS,\n CHOICE_MAX_LETTERS_OPTIONS,\n CHOICE_MAX_OPTION_LENGTH,\n DRAW_GAME_DEFAULT_TIERS,\n isDarkPaper,\n inkFor,\n DEFAULT_OPTIONS_REVEAL_SECONDS,\n DEFAULT_MAX_RECORDING_SECONDS,\n BOOKING_WEEKDAYS,\n GOOGLE_MEET_BOOKING_DEFAULTS,\n MAX_RECORDING_SECONDS_MIN,\n MAX_RECORDING_SECONDS_MAX,\n cameraCaptureUnit,\n resolveCameraCaptureOrder,\n cameraCaptureSources,\n NODE_TYPE_METADATA,\n RESPONSE_SCHEMAS,\n CONFIG_SCHEMAS,\n OUTPUT_SCHEMAS,\n TERMINAL_TYPES,\n NON_COUNTABLE_TYPES,\n NON_COUNTABLE_FILTER,\n RESULTS_EXCLUDED_TYPES,\n PUBLIC_RESULTS_EXCLUDED_TYPES,\n PII_NODE_TYPES,\n RESPONDENT_MEDIA_NODE_TYPES,\n FILE_ANSWER_NODE_TYPES,\n RESPONSES_EXCLUDED_TYPES,\n STEP_COUNTED_TYPES,\n ANON_MCP_BLOCKED_NODE_TYPES,\n ANON_MCP_OUTBOUND_LINK_RULES,\n ANON_MCP_STRIPPED_FIELD_RULES,\n ANON_MCP_KEPT_TEXT_KEYS,\n isAnonMcpLockedNode,\n stripAnonMcpLockedNode,\n isTerminalType,\n countsAsStep,\n} from './node-types.js';\n\nexport {\n validateAgainstSchema,\n validateConfig,\n validateOptions,\n lettersCapError,\n maxOptionsError,\n validateResponse,\n validateOutput,\n collectsResponse,\n} from './validate.js';\n\nexport { FEATURE_FLAGS, FEATURES, getLiveFeatures, getPlannedFeatures, getFeaturesByCategory, getWhatsNew, getAnnouncements, getUnreadAnnouncements, getRecentAnnouncements, isNewFeature, WHATS_NEW_POPUP_LIMIT, ANNOUNCE_PALETTES, INTEGRATION_COMPANY_ALLOWLIST, companyHasIntegration, companyHasAnyIntegration, NODE_COMPANY_ALLOWLIST, companyHasNodeType, FEATURE_COMPANY_ALLOWLIST, companyHasPublicResults, companyHasCustomDomains, companyHasConsentDocuments, companyHasResponseSummary, companyHasMultiSelect, companyHasResponseTrash, companyHasVariables, companyHasTranscriptCopy, companyHasMediaPlayer, getFeatureAccess, getFeatureAllowlist, combineFeatureAccess } from './features.js';\n\nexport { DIGEST_EMAIL_KEY, ACTIVATION_STEP_EVENT, ACTIVATION_STEP_KINDS, ACTIVATION_STEP_SOURCES, USER_FAILURE_EVENT, USER_FAILURE_REASONS, PENDING_ACTION_CEILING_MS, ANALYTICS_METRICS, FORM_EVENTS, TEMPLATE_TOUR_EVENTS, RESULT_STAT_LABELS, ANALYTICS_INVARIANTS, ANALYTICS_BREAKDOWNS, ANALYTICS_FUNNEL_ORDER, ANALYTICS_EXCLUDED_TRIGGERS, LIFECYCLE_EVENTS, getMetricLabel, normalizeCountryFilter } from './analytics.js';\n\n/**\n * Form type definitions — re-exported from form-types.js\n */\nexport {\n FORM_TYPES,\n FORM_TYPES_LIST,\n FORM_TYPE_KEYS,\n WORKFLOW_TYPES,\n FORM_TYPE_ALIASES,\n ALL_VARIANTS,\n resolveFormType,\n getDiscoveryParams,\n isFormTypeAvailable,\n getAvailableFormTypes,\n} from './form-types.js';\n\nexport { validateFormForPublish, getNodeContentError, buildAdjacencyMap, getReachableIds, resolveRedirectUrl, resolveLinkListConfig } from './graph-validation.js';\n\n/**\n * Video template layer (#1736) — re-exported from video-templates.js. Data\n * + a pure expander that fills a curated control surface into Scene props;\n * video templates render through the existing Scene composition, never a\n * new primitive.\n */\nexport { VIDEO_TEMPLATE_REGISTRY, VIDEO_TEMPLATE_NAMES, buildVideoTemplate, exposedVideoTemplateNames, VIDEO_LOOK_NAMES, expandVideoLook, resolveVideoStyle, KEN_BURNS_RANDOM_POOL, SLIDESHOW_MAX_ITEMS, SLIDESHOW_COMPOSITION_TRANSITIONS, SLIDESHOW_TRANSITION_DURATION, NARRATION_TAIL_SECONDS, isHttpUrl, HTTP_URL_MESSAGE } from './video-templates.js';\n\n/**\n * Form update accept-list — re-exported from form-update-fields.js\n * (source of truth for the fields PATCH /v1/forms/:id accepts, #1219)\n */\nexport { FORM_UPDATE_FIELDS, FORM_UPDATE_FIELD_KEYS } from './form-update-fields.js';\n\n/**\n * Starter-form archetype resolver (#3600) — re-exported from starter-forms.js.\n * Maps a marketing page (use-case/for-page/blog) to a workflow archetype and\n * (once #3599 fills ARCHETYPE_STARTERS) a concrete starter form share_id for\n * \"Build\" CTAs. Blank-safe: every archetype's starter is 'TBD' until #3599\n * lands, so resolveStarterForm returns null everywhere in this PR.\n */\nexport {\n STARTER_ARCHETYPES,\n ARCHETYPE_STARTERS,\n USE_CASE_ARCHETYPE,\n PERSONA_ARCHETYPE,\n BLOG_CATEGORY_ARCHETYPE,\n BASIC_STARTER_SHARE_ID,\n STARTER_FORM_TITLE,\n UNTITLED_FORM_TITLE,\n IMPORTED_FORM_TITLES,\n DEFAULT_FORM_TITLES,\n isUnsetFormTitle,\n resolveArchetype,\n resolveStarterForm,\n} from './starter-forms.js';\n\n/**\n * Placement tag vocabulary (#2017) — re-exported from placement-tags.js. The\n * closed `for:*`/`usecase:*` namespace mirrored against active `/for/*` and\n * `/use-case/*` marketing pages; write-time enforcement lives in\n * apps/api's set-form-tags route.\n */\nexport {\n PLACEMENT_FOR_ROLES,\n PLACEMENT_USECASE_WORKFLOWS,\n PLACEMENT_TAGS,\n isPlacementNamespace,\n invalidPlacementTags,\n} from './placement-tags.js';\n\n/** Reserved vanity-link slugs (#3273, #4493) - API validation + dashboard client check. */\nexport { RESERVED_VANITY_SLUGS } from './reserved-slugs.js';\nexport { DRAW_PRESETS, DRAW_PRESET_GROUPS, DRAW_PRESET_IDS, DRAW_PRESET_PATH_PREFIX, getDrawPreset, drawPresetPath } from './draw-presets.js';\n\n/**\n * Signup origin vocabulary (#4026) — re-exported from signup-origin.js. The\n * first-touch acquisition dimension for account creation (MCP/bot channel,\n * direct web/email, or the /try anonymous builder).\n */\nexport {\n SIGNUP_ORIGINS,\n isSignupOrigin,\n} from './signup-origin.js';\n\n/**\n * Connector signup origin resolver (#4048) - resolves an OAuth `client_id`\n * string (ChatGPT/Claude contain the provider's own domain) to the\n * SignupOrigin a logged-out connector visitor's signup should be tagged\n * with, instead of the generic web/email default. Resolved from the\n * client_id string, NOT a DB lookup - `oauth_clients` RLS has no anon SELECT\n * policy, so a logged-out visitor can never read it.\n */\nexport { connectorOriginFromClientId, connectorNameFromClientId } from './connector-signup-origin.js';\n\nexport {\n ANON_MCP_RESPONSE_CAP,\n ANON_MCP_STARTED_SESSION_MULTIPLE,\n ANON_MCP_STARTED_SESSION_CAP,\n ANON_MCP_LIVE_TTL_DAYS,\n ANON_MCP_UPLOADS_PER_SESSION,\n} from './anon-mcp-limits.js';\n\n/** Builder chat turn time budget (#6139): server persona + dashboard client timeout. */\nexport { BUILDER_CHAT_TURN_TIMEOUT_MS, BUILDER_CHAT_CLIENT_TIMEOUT_MS } from './builder-chat-limits.js';\n\n/**\n * Node logic grammar constants — re-exported from logic-types.js\n */\nexport {\n LOGIC_ACTION_TYPES,\n LOGIC_CONDITION_OPS,\n LOGIC_VAR_TYPES,\n LOGIC_TARGET_TYPES,\n LOGIC_REMAPPABLE_VAR_TYPES,\n ROUTABLE_VARIABLES,\n getFormVariableIds,\n isBranchingActive,\n isMultiSelectChoice,\n gateSelectionMode,\n gateNodeSelectionMode,\n gateNodesSelectionMode,\n isAnswerKeyActive,\n isCorrectOption,\n isOptionEdge,\n isInactiveOptionEdge,\n isNodeLevelAction,\n replaceNodeLevelActions,\n dropStaleRefs,\n ensureNodeVarFallback,\n actionReferenceErrors,\n} from './logic-types.js';\n\n/**\n * Pure, branch-aware logic-chain graph helpers — re-exported from\n * logic-chain.js (#1058). apps/api's DB-backed chain ops (getOrderedNodes,\n * insertAfter, removeFromChain, findLastBeforeTerminal) call these.\n */\nexport {\n outgoingTargets,\n isBranched,\n defaultTarget,\n bfsOrder,\n computeRemovalRewrites,\n} from './logic-chain.js';\n\n/**\n * Template walkthrough notes and company checklists on node.config.guide (#6269, #6275) - re-exported from guide.js.\n */\nexport {\n GUIDE_CONFIG_KEY,\n GUIDE_LIMITS,\n GUIDE_TOUR_ANCHORS,\n GUIDE_SECTIONS,\n GUIDE_NODE_SECTIONS,\n guideSectionsFor,\n COMPANY_CHECKLIST_KINDS,\n checklistConnectableIntegrations,\n validateNodeGuide,\n mergeNodeGuide,\n stripNodeGuide,\n buildTemplateTourSteps,\n buildTemplateChecklist,\n buildTemplateTourIntro,\n} from './guide.js';\n\n/**\n * Integration catalog definitions — re-exported from integration-catalog.js\n */\nexport {\n INTEGRATION_CATALOG,\n INTEGRATION_CATALOG_LIST,\n INTEGRATION_SLUGS,\n getIntegrationsByCategory,\n getIntegrationsByTags,\n getIntegrationHubAccess,\n getHubIntegrations,\n} from './integration-catalog.js';\n\n/**\n * API key prefixes — shared between API (validation) and dashboard (generation)\n */\nexport const API_KEY_PREFIXES = ['cf_', 'cf_live_', 'cf_test_'];\nexport const API_KEY_PREFIX = 'cf_';\n\n/**\n * OAuth token prefixes — shared between the API's oauth.ts (minting/validation)\n * and api-key-auth.ts (distinguishing an OAuth token from a workspace API key)\n */\nexport const OAUTH_TOKEN_PREFIXES = ['cf_at_', 'cf_rt_', 'cf_code_'];\n\n/**\n * Input validation limits — shared between API routes and MCP server\n */\nexport const VALIDATION_LIMITS = {\n form: {\n title: { max: 1000 },\n nodes: { max: 100 },\n },\n node: {\n prompt: { max: 5000, media_max: 60 },\n options: { max: 50 },\n },\n workspace: {\n name: { max: 100 },\n },\n // company.name is varchar(255) (#4587: renamed from Company settings).\n company: {\n name: { max: 255 },\n },\n};\n\n/**\n * Theme defaults and colour validation — single source of truth\n * All colours must be 6-digit hex (#RRGGBB). No rgba, no shorthand.\n */\nexport const HEX_COLOR_REGEX = /^#[0-9A-Fa-f]{6}$/;\n\nexport const THEME_DEFAULTS = {\n primary_color: '#374151',\n background_color: '#F3F4F6',\n font_family: 'Inter',\n};\n\n/**\n * AI-protected form fields — fields the AI must NOT set unless the user\n * explicitly requests it. Everything else is AI-mutable (set freely).\n *\n * Used by MCP tools to guard descriptions and omit defaults.\n */\nexport const AI_PROTECTED_FIELDS = {\n font_family: {\n reason: 'Brand/design decision — do not set unless the user explicitly requests a different font.',\n },\n author: {\n reason: 'Brand identity — do not invent. Only set when the user provides a value.',\n },\n brand_name: {\n reason: 'Brand identity — do not invent. Only set when the user provides a value.',\n },\n logo_url: {\n reason: 'Brand identity — do not invent. Only set when the user provides a value.',\n },\n is_live: {\n reason: 'Going live is a deliberate action. Never auto-publish unless the user asks.',\n },\n};\n\n/**\n * Ken Burns / Slideshow constants — single source of truth.\n * Used by Remotion compositions, API slideshow route, and MCP tools.\n */\nexport const KEN_BURNS_EFFECTS = [\n 'pan-left',\n 'pan-right',\n 'pan-up',\n 'pan-down',\n 'zoom-in-pan-left',\n 'zoom-in-pan-right',\n 'zoom-in',\n 'zoom-out',\n 'static',\n];\n\nexport const KEN_BURNS_PRESETS = [\n 'cinematic',\n 'dramatic',\n 'calm',\n 'documentary',\n 'dreamy',\n 'moody',\n 'energetic',\n];\n\nexport const KEN_BURNS_EASINGS = ['ease-in-out', 'ease-in', 'ease-out', 'linear'];\n\nexport const KEN_BURNS_FIT_MODES = ['cover', 'blur-pad', 'auto'];\n\nexport const SLIDESHOW_TRANSITIONS = [\n 'fade',\n 'fadeblack',\n 'fadewhite',\n 'slideleft',\n 'slideright',\n 'circlecrop',\n 'circleopen',\n 'circleclose',\n 'dissolve',\n 'pixelize',\n 'radial',\n 'smoothleft',\n 'smoothright',\n 'wipeleft',\n 'wiperight',\n 'diagtl',\n 'diagbr',\n 'hblur',\n];\n\n// SLIDESHOW_COMPOSITION_TRANSITIONS (the narrow set Slideshow actually\n// renders, distinct from the broad ffmpeg list above) is DEFINED in\n// video-templates.js, next to the VIDEO_LOOKS code that consumes it, and\n// re-exported below - see that file for why. Defining it here and having\n// video-templates.js import it back created a real index.js <-> video-templates.js\n// import cycle (index.js already re-exports FROM video-templates.js), fixed\n// in #4038 review.\n\n/**\n * Composition IDs that require a Mapbox access token.\n * Map is the primitive (#453); GlobeToCity/CityToGlobe/MapPin are its\n * presets/aliases.\n */\nexport const MAP_COMPOSITIONS = ['Map', 'GlobeToCity', 'CityToGlobe', 'MapPin'];\n\n/**\n * Composition registry - single source of truth for which compositions the MCP\n * server exposes and at what access tier, plus their kind (for docs/tooling).\n *\n * - `tier`: 'public' (everyone) | 'labs' (non-prod, power users/dogfooding) |\n * 'social' (non-prod, marketing templates). The MCP PUBLIC/LABS/SOCIAL\n * lists derive from this (see packages/mcp-server/src/lib/config.ts).\n * - `kind`: 'bed' (full-bleed Scene layer 0) | 'overlay' (Scene asset layer) |\n * 'container' (Scene itself) | 'video' (whole standalone pre-baked video).\n * - `scene_layer`: usable as a Scene layer (#652). SCENE_LAYER_IDS in\n * packages/remotion derives from this - never hand-list layer ids there.\n * `kind` says where a comp sits when layered; `scene_layer` says whether it\n * may be (most beds render standalone only).\n *\n * Variant presets (e.g. a 'neon' Text) are NOT separate entries - they\n * are the base composition + a `preset` prop. Render-only/dev compositions\n * (test cards, Map preset-aliases, StatOverlay) are intentionally absent: they\n * are registered in Remotion but not advertised on the MCP. The GridList/\n * FourImageGrid/OddOneOutReveal Grid layout-aliases that used to live here\n * were deleted outright (#1615) - a list is just Grid with\n * `layout: { columns: 1 }`, not its own primitive. FlagReveal, ColorCards and\n * TitleCard were folded the same way (#1736) - they are VIDEO_TEMPLATE_REGISTRY\n * entries (video-templates.js) that expand onto Slideshow/Grid/Text through Scene,\n * not COMPOSITION_REGISTRY primitives.\n */\nexport const COMPOSITION_REGISTRY = [\n // Beds (full-bleed backgrounds)\n { id: 'Slideshow', tier: 'public', kind: 'bed', scene_layer: true },\n { id: 'Map', tier: 'public', kind: 'bed', scene_layer: true },\n { id: 'Grid', tier: 'public', kind: 'bed', scene_layer: true },\n { id: 'Timeline', tier: 'labs', kind: 'bed' },\n { id: 'Silhouette', tier: 'labs', kind: 'bed', scene_layer: true },\n // Overlays (assets layered on a bed)\n { id: 'Text', tier: 'labs', kind: 'overlay', scene_layer: true },\n { id: 'Rebus', tier: 'labs', kind: 'overlay', scene_layer: true },\n // Container\n { id: 'Scene', tier: 'labs', kind: 'container' },\n // Social marketing templates (gated)\n { id: 'ShortFormQuiz', tier: 'social', kind: 'video' },\n { id: 'ScorecardQuiz', tier: 'social', kind: 'video' },\n { id: 'ScorecardGK', tier: 'social', kind: 'video' },\n { id: 'CountrySilhouetteQuiz', tier: 'social', kind: 'video' },\n];\n\nconst compositionIdsByTier = (tier) =>\n COMPOSITION_REGISTRY.filter((c) => c.tier === tier).map((c) => c.id);\n\nexport const PUBLIC_COMPOSITION_IDS = compositionIdsByTier('public');\nexport const LABS_COMPOSITION_IDS = compositionIdsByTier('labs');\nexport const SOCIAL_COMPOSITION_IDS = compositionIdsByTier('social');\n\n/**\n * The composition surface exposed for a given environment (#1674, #1789).\n * `labs`/`social` are a pure environment gate - not a per-workspace/billing\n * concept - so this takes a single boolean rather than reading `process.env`\n * itself (this package stays dependency-free; callers resolve NODE_ENV at\n * their own edge). Single derivation shared by the MCP server\n * (packages/mcp-server/src/lib/config.ts) and the API's render gate\n * (apps/api/src/routes/internal/render.ts) - never hand-roll a second copy\n * of this list.\n */\nexport function exposedCompositionIds(includeNonPublic) {\n return [\n ...PUBLIC_COMPOSITION_IDS,\n ...(includeNonPublic ? LABS_COMPOSITION_IDS : []),\n ...(includeNonPublic ? SOCIAL_COMPOSITION_IDS : []),\n ];\n}\n\n/** Compositions usable as Scene layers (#652) - the single source for\n * SCENE_LAYER_IDS in packages/remotion and (via sync-schemas) the API's\n * per-layer validation allowlist. */\nexport const SCENE_LAYER_COMPOSITION_IDS = COMPOSITION_REGISTRY\n .filter((c) => c.scene_layer)\n .map((c) => c.id);\n\n/**\n * Minimum plan tier for an MCP tool to appear in tools/list on the remote\n * (OAuth) MCP server (#471). Tools not listed default to 0 (every plan).\n * Presentation-level only - real enforcement (rate limits, plan checks)\n * stays in the API routes. stdio/API-key sessions always see all tools.\n *\n * To gate a tool, add e.g. `clipform_render_composition: 1`.\n */\nexport const MCP_TOOL_TIERS = {};\n\n/**\n * Connect-time MCP toolset partition (#3309). A client may opt into a subset\n * of tools via `/mcp?features=account,forms,media` (apps/api/src/mcp/handler.ts),\n * so `tools/list` only ships the schemas it needs - a form-only client drops\n * the media-tool payload entirely instead of downloading it and ignoring it.\n * Every registered clipform_* tool maps to exactly ONE toolset here - enforced\n * by a parity test that statically walks packages/mcp-server/src (same\n * pattern as MCP_TOOL_TIERS' sibling tests).\n *\n * This is a DIFFERENT axis than apps/api/src/lib/tool-phases.ts: tool-phases\n * groups tools by build STEP (research/build/attach) for the dashboard bot's\n * dynamic per-turn filtering, and its RESEARCH_TOOLS list straddles both\n * `forms` and `media` below. Toolsets group by connect-time CLIENT INTENT\n * (account/forms/research/media) and are static for the life of a session -\n * one grouping per axis, not a re-label of the other.\n *\n * `research` (#3681) holds the content-research helpers that proxy third\n * parties or exist only for generation workflows (news lookup, generation\n * audit log). They are excluded from the Claude Connectors Directory surface\n * (mcp.clipform.io/forms = account + forms) so that surface is pure first\n * party form building - a client with native web search has no use for them.\n */\nexport const MCP_TOOLSETS = ['account', 'forms', 'research', 'media'];\n\n/**\n * Tools registered only per session, not by default (#6052): dark behind a company allowlist, so\n * `createServer()` / stdio leave them out and apps/api opts in per request. Parity tests that\n * compare MCP_TOOL_TOOLSETS with the default surface skip these.\n * clipform_set_node_guide: template walkthrough notes (#6269), template_walkthrough allowlist.\n */\nexport const MCP_SESSION_GATED_TOOLS = Object.freeze(['clipform_set_link_variables', 'clipform_set_node_guide']);\n\nexport const MCP_TOOL_TOOLSETS = {\n // account: workspace/account-scoped read + admin tools.\n clipform_list_forms: 'account',\n clipform_get_form: 'account',\n clipform_delete_form: 'account',\n clipform_whoami: 'account',\n clipform_get_results: 'account',\n clipform_get_responses: 'account',\n\n // forms: form/node structure + craft guidance used while building.\n clipform_create_form: 'forms',\n clipform_import_form: 'forms',\n clipform_add_node: 'forms',\n clipform_update_node: 'forms',\n clipform_delete_node: 'forms',\n clipform_update_form: 'forms',\n clipform_set_logic: 'forms',\n clipform_set_link_variables: 'forms',\n clipform_set_node_guide: 'forms',\n clipform_get_guide: 'forms',\n clipform_get_workflow: 'forms',\n\n // research: third-party content lookup + generation-workflow audit.\n clipform_search_news: 'research',\n clipform_log_generation: 'research',\n\n // media: creative/render/asset tools. fetch_boundary only feeds the Map\n // composition's `boundary` prop, so it lives with the render tools.\n clipform_fetch_boundary: 'media',\n clipform_generate_tts: 'media',\n clipform_render_composition: 'media',\n clipform_render_video_template: 'media',\n clipform_check_render: 'media',\n clipform_upload_media_asset: 'media',\n clipform_complete_media_upload: 'media',\n clipform_attach_node_media: 'media',\n clipform_get_node_media: 'media',\n clipform_delete_node_media: 'media',\n clipform_search_media: 'media',\n clipform_search_music: 'media',\n clipform_list_compositions: 'media',\n clipform_list_assets: 'media',\n clipform_list_video_templates: 'media',\n};\n\n/**\n * Per-tool OAuth security declaration (#4088) - the OpenAI Apps SDK\n * convention for telling a host \"anonymous calls work, linking unlocks\n * privileged behaviour.\" This is NOT part of the MCP core spec (the Tool\n * type has no `securitySchemes` field), but the Apps SDK's own reference\n * implementation emits it as a TOP-LEVEL `securitySchemes` key on each\n * `tools/list` entry (not an `mcp/`-namespaced `_meta` key - no host reads\n * one). OpenAI's own reference docs (developers.openai.com/plugins/reference,\n * tool descriptor `_meta` table) separately document an un-namespaced\n * `_meta.securitySchemes` as a back-compat MIRROR of the same array, for a\n * client that only reads `_meta` - packages/mcp-server's server.ts sets\n * BOTH (top-level + the `_meta` mirror) from this one array via its\n * `tools/list` wrapper, so they can never drift from each other. See\n * api-client.ts's `authChallengeMeta` for the separate runtime half of the\n * contract (a tool result's own `_meta[\"mcp/www_authenticate\"]` carries the\n * matching WWW-Authenticate challenge when a feature actually needs an\n * account).\n *\n * Every tool that can run anonymously declares the mixed scheme `noauth` +\n * `oauth2`; a `sign_in` tool (MCP_ANON_TOOLS below, #4657) declares\n * `oauth2` only, because it has nothing to show an anonymous caller.\n * `scopes` matches apps/api/src/mcp/handler.ts's REQUIRED_SCOPE (\"mcp\").\n *\n * Derived off MCP_TOOL_TOOLSETS's own key set (every registered tool already\n * has exactly one toolset entry there) so the two tables structurally can't\n * drift apart - a newly registered clipform_* tool that's missing from\n * MCP_TOOL_TOOLSETS fails that table's own parity test first. A static\n * parity test mirroring toolset-parity.test.ts additionally re-derives the\n * registered-tool list directly from packages/mcp-server/src/tools, so a\n * tool can never ship with no MCP_TOOL_SECURITY entry at all.\n */\nexport const MCP_TOOL_SECURITY_SCHEMES = Object.freeze([\n Object.freeze({ type: 'noauth' }),\n Object.freeze({ type: 'oauth2', scopes: ['mcp'] }),\n]);\n\n/** The `oauth2`-only declaration for a `sign_in` tool (#4657). */\nexport const MCP_TOOL_SECURITY_SCHEMES_SIGN_IN = Object.freeze([\n Object.freeze({ type: 'oauth2', scopes: ['mcp'] }),\n]);\n\n/**\n * Anonymous-access classification of every registered MCP tool (#4657) - the\n * ONE allowlist behind the anonymous boundary. Before this the boundary was a\n * denylist of one (the publish gate, since removed in #4847), so every other anonymous tools/call\n * without a form_id minted a throwaway workspace just to answer from an empty\n * one (list_forms, whoami, get_results ...).\n *\n * - `anon`: runs for an anonymous caller inside the caller's own anon\n * workspace (build tools, `get_form` by form_id, media + research tools -\n * media keeps the existing expensive-op throttle).\n * - `anon_no_workspace`: runs anonymously but needs NO workspace (static craft\n * content and the static creative-asset catalog), so a request made only of\n * these never mints and runs with no credential at all.\n * - `sign_in`: needs a signed-in account. An anonymous call is refused before\n * any mint (apps/api/src/mcp/handler.ts).\n *\n * `sign_in` is the DEFAULT (see `getMcpAnonAccess`): a tool with no entry is\n * refused to anonymous callers. The parity test\n * (packages/mcp-server/src/__tests__/anon-tools-parity.test.ts) still demands\n * an explicit entry per registered tool so the choice is always deliberate.\n */\nexport const MCP_ANON_ACCESS_LEVELS = ['anon', 'anon_no_workspace', 'sign_in'];\n\nexport const MCP_ANON_TOOLS = Object.freeze({\n // account\n clipform_list_forms: 'sign_in',\n clipform_get_form: 'anon',\n clipform_delete_form: 'sign_in',\n clipform_whoami: 'sign_in',\n clipform_get_results: 'sign_in',\n clipform_get_responses: 'sign_in',\n\n // forms\n clipform_create_form: 'anon',\n clipform_import_form: 'anon',\n clipform_add_node: 'anon',\n clipform_update_node: 'anon',\n clipform_delete_node: 'anon',\n clipform_update_form: 'anon',\n clipform_set_logic: 'anon',\n clipform_set_link_variables: 'sign_in',\n clipform_set_node_guide: 'sign_in',\n clipform_get_guide: 'anon_no_workspace',\n clipform_get_workflow: 'anon_no_workspace',\n\n // research\n clipform_search_news: 'anon',\n clipform_log_generation: 'anon',\n\n // media\n clipform_fetch_boundary: 'anon',\n clipform_generate_tts: 'anon',\n clipform_render_composition: 'anon',\n clipform_render_video_template: 'anon',\n clipform_check_render: 'anon',\n clipform_upload_media_asset: 'anon',\n clipform_complete_media_upload: 'anon',\n clipform_attach_node_media: 'anon',\n clipform_get_node_media: 'anon',\n clipform_delete_node_media: 'anon',\n clipform_search_media: 'anon',\n clipform_search_music: 'anon',\n clipform_list_compositions: 'anon',\n clipform_list_assets: 'anon_no_workspace',\n clipform_list_video_templates: 'anon',\n});\n\n/**\n * Virtual tools the `@posthog/mcp` wrapper injects into tools/list (e.g.\n * `get_more_tools`, packages/mcp-server's instrumentServer) - never registered\n * by packages/mcp-server/src/tools, so deliberately not in MCP_ANON_TOOLS. They\n * need no API or workspace, so they are `anon_no_workspace` (#4657).\n */\nexport const MCP_VIRTUAL_TOOLS = Object.freeze(['get_more_tools']);\n\n/** Anonymous access level for a tool; an unclassified tool is `sign_in`. */\nexport function getMcpAnonAccess(toolName) {\n if (MCP_VIRTUAL_TOOLS.includes(toolName)) return 'anon_no_workspace';\n return Object.prototype.hasOwnProperty.call(MCP_ANON_TOOLS, toolName)\n ? MCP_ANON_TOOLS[toolName]\n : 'sign_in';\n}\n\nexport const MCP_TOOL_SECURITY = Object.freeze(\n Object.fromEntries(\n Object.keys(MCP_TOOL_TOOLSETS).map((name) => [\n name,\n getMcpAnonAccess(name) === 'sign_in'\n ? MCP_TOOL_SECURITY_SCHEMES_SIGN_IN\n : MCP_TOOL_SECURITY_SCHEMES,\n ])\n )\n);\n\n/**\n * Workspace-library MCP tools with no form_id of their own to resolve a\n * workspace off (#4621) - they write/read the workspace media library\n * directly, never a node. An anonymous MCP request made up ENTIRELY of\n * calls to these tools, with no form_id anywhere in it, would otherwise\n * mint a brand-new throwaway workspace (same mint branch as create_form),\n * so the result lands somewhere clipform_attach_node_media can never find\n * it - apps/api/src/mcp/anon-form-context.ts's requiresFormContext() blocks\n * that shape before the mint runs. Each tool here must declare a `form_id`\n * input (packages/mcp-server's formIdTargetInput, workspace-target.ts) -\n * form-context-schema.test.ts asserts it off this SAME array, so the two\n * halves of this fix can never drift apart. clipform_list_assets is\n * deliberately excluded: it serves static, non-workspace-scoped creative\n * assets (handleAssets - apps/api/src/lib/creative-handlers.ts), so gating\n * it would 400 an anon agent for simply listing available fonts/sfx, with\n * no orphan-asset bug to fix.\n */\nexport const MCP_TOOLS_REQUIRING_FORM_CONTEXT = [\n 'clipform_upload_media_asset',\n 'clipform_generate_tts',\n 'clipform_complete_media_upload',\n];\n\n/**\n * Form-scoped MCP tools whose input REQUIRES a form_id (#4717): they edit or\n * read an existing form or node, so a call without one can never succeed in a\n * freshly minted (empty) anonymous workspace. Same treatment as\n * MCP_TOOLS_REQUIRING_FORM_CONTEXT above: an anonymous request made up entirely\n * of these, with no form_id and no session binding (#4652), is refused before\n * the mint instead of creating a throwaway account. Kept separate because these\n * tools' form_id is required (the #4621 tools take an optional target form_id).\n * form-context-schema.test.ts asserts each declares a required form_id, and that\n * every anon tool with a required form_id input is listed here.\n */\nexport const MCP_TOOLS_REQUIRING_FORM_ID = [\n 'clipform_get_form',\n 'clipform_add_node',\n 'clipform_update_node',\n 'clipform_delete_node',\n 'clipform_update_form',\n 'clipform_set_logic',\n 'clipform_log_generation',\n 'clipform_attach_node_media',\n 'clipform_get_node_media',\n 'clipform_delete_node_media',\n];\n\n/**\n * Documentation RAG embeddings (the `docs.chunks` vector store powering the\n * dashboard docs chatbot). SINGLE SOURCE OF TRUTH for the OpenAI embedding\n * model + dimensions.\n *\n * BOTH sides must use these or retrieval silently breaks: the ingest side\n * (`scripts/embed-docs.mjs`, which writes the chunk vectors) and the query\n * side (`apps/api/src/routes/v1/docs/chat.ts`, which embeds the user's\n * question). If they drift, questions get embedded in a different vector\n * space than the stored chunks and `match_chunks` returns garbage.\n *\n * Pinned to 1536 dims (not text-embedding-3-large's native 3072) so the\n * vectors fit the `docs.chunks vector(1536)` column AND stay under pgvector's\n * 2000-dim HNSW index limit - no schema migration needed. Changing either\n * value requires a full re-embed (`FULL_REEMBED=1 node scripts/embed-docs.mjs`):\n * a model/dim swap doesn't change content hashes, so the incremental path\n * would skip every chunk.\n */\nexport const DOCS_EMBEDDING_MODEL = 'text-embedding-3-large';\nexport const DOCS_EMBEDDING_DIMENSIONS = 1536;\n\n/**\n * Effective response-moderation setting for a form (#1835, #1837). The form's\n * `moderate_responses` wins when set (true or false); null/undefined inherits\n * the workspace default. A missing workspace value defaults to true (moderation\n * on), matching the workspaces column's `NOT NULL DEFAULT true`. Shared by the\n * API (what gets checked) and the dashboard (whether flagged answers blur).\n */\nexport function resolveEffectiveModeration(form, workspace) {\n const formValue = form?.moderate_responses;\n if (formValue === true || formValue === false) return formValue;\n return workspace?.moderate_responses ?? true;\n}\n\n/**\n * Clip caps (#4622). A render or voiceover is for ONE step node in a Clipform\n * form, so it is short. Single source for the API checks (production) and the\n * MCP tool copy. 400 chars of narration is about 27s of speech.\n */\nexport const MAX_CLIP_SECONDS = 30;\nexport const MAX_NARRATION_CHARS = 400;\n\n/**\n * Grid cadence defaults and animation floor (#4622). Single source: remotion's\n * grid-timing imports these, and the API's clip-length gate mirrors Grid's real\n * length with them (a caller-set stagger/entrance/reveal stretches the clip).\n */\nexport const GRID_DEFAULT_STAGGER_SECONDS = 0.45;\nexport const GRID_DEFAULT_ENTRANCE_SECONDS = 0.5;\nexport const GRID_DEFAULT_REVEAL_SECONDS = 0.5;\n\n/** The animation's own end (entrances + reveal + a short settle) - the clip never shortens below it. */\nexport function gridMinSeconds(cellCount, timing) {\n const stagger = timing?.staggerSeconds ?? GRID_DEFAULT_STAGGER_SECONDS;\n const entrance = timing?.entranceSeconds ?? GRID_DEFAULT_ENTRANCE_SECONDS;\n const reveal = timing?.revealSeconds ?? GRID_DEFAULT_REVEAL_SECONDS;\n return (cellCount - 1) * stagger + entrance + reveal + 0.5;\n}\n\n/**\n * Custom form variables (#5647) - key rules, coercion and the shared\n * deriveVariables engine, re-exported from variables.js.\n */\nexport {\n VARIABLE_KEY_MAX_LENGTH,\n VARIABLE_KEY_PATTERN,\n VARIABLE_TYPES,\n VARIABLE_TEXT_MAX_LENGTH,\n VARIABLE_LABEL_MAX_LENGTH,\n VARIABLE_NUMBER_MAX,\n VARIABLE_MAX_CUSTOM_PER_FORM,\n SAVE_TO_NODE_TYPES,\n SAVE_TO_OPS,\n RESERVED_VARIABLE_KEYS,\n RESERVED_VARIABLE_KEY_PREFIXES,\n isReservedVariableKey,\n validateVariableKey,\n coerceVariableValue,\n validateSaveTo,\n optionValueError,\n deriveVariables,\n pointsAvailable,\n scoreLinePreset,\n hasPointOptions,\n choiceQuestionKind,\n choicePoints,\n CHOICE_POINTS_MAX,\n qualifiesForScoreWiring,\n withScoreVariable,\n isWiredToVariable,\n nodeHasPointsMap,\n findScoreVariableId,\n customNumberKeys,\n findScoreVariable,\n nodeHasPointsFor,\n pointsDormantFor,\n withoutVariableRefs,\n addTargetVariable,\n optionPoints,\n legacyCategoryScores,\n pointsMapError,\n VARIABLE_MAX_LINK_PER_FORM,\n normalizeLinkValue,\n pickLinkValues,\n capRawLinkPairs,\n isUnsafeLinkChar,\n hasUnsafeLinkChar,\n stripUnsafeLinkChars,\n LINK_UNSAFE_RANGES,\n LINK_RAW_VALUE_MAX,\n LINK_RAW_KEY_MAX,\n LINK_RAW_PAIRS_MAX,\n LINK_RAW_TOTAL_MAX,\n VARIABLE_LINK_WARN_CHARS,\n isPersonalLinkKey,\n LINK_VARIABLE_PRESETS,\n linkVariablePreset,\n buildVariableLink,\n} from './variables.js';\n\n/** Third-party deep links (#6216), re-exported from third-party-links.js. */\nexport { THIRD_PARTY_LINKS } from './third-party-links.js';\nexport { KLAVIYO_KX_KEY, KLAVIYO_KX_MAX_LENGTH, isKlaviyoKx } from './klaviyo-kx.js';\nexport { EMAIL_LINK_IDS, isKitSubscriberId, emailLinkIdByStoreKey, emailLinkIdByVendor, isValidEmailLinkId } from './email-link-ids.js';\n\n/** Email tool tagging vocabulary (#6174), re-exported from email-tools.js. */\nexport {\n EMAIL_TOOL_TRIGGERS,\n EMAIL_TOOL_TRIGGER_IDS,\n EMAIL_TOOL_TAG_NAME_MAX,\n defaultEmailToolTagName,\n normalizeTagRules,\n respondentEmailPick,\n} from './email-tools.js';\n\n/**\n * Variable recall (#5671) - `{{key}}` short codes in node text, re-exported from recall.js.\n */\nexport {\n RECALL_TOKEN_SOURCE,\n RECALL_TOKEN_PATTERN,\n RECALL_RESERVED_LABELS,\n RECALL_FALLBACK_MAX_LENGTH,\n RECALL_CHIP_DISPLAY_LENGTH,\n parseRecallRef,\n parseRecallToken,\n sanitizeRecallFallback,\n RECALL_FIELD_ID_MAX_LENGTH,\n findRecallRefs,\n findRecallAnswerRefs,\n textUsesRecallAnswer,\n nodeUsesRecallAnswer,\n nodeRecallAnswerRefs,\n recallDisplayLength,\n recallAnswerText,\n formatRecallValue,\n findRecallKeys,\n textUsesRecallKey,\n valueUsesRecallKey,\n nodeUsesRecallKey,\n interpolateRecall,\n interpolateRecallParts,\n startingRecallValues,\n} from './recall.js';\n\n/**\n * What a recalled answer is called on every surface (#5696): the builder chip, owner tables, exports, webhooks. The node's\n * trimmed `label`, else its type's name; a Details field appends ` - <field label>`. `node` is a plain\n * `{ type, label, config }`.\n */\nexport function recallAnswerLabel(node, fieldId) {\n const label = typeof node?.label === 'string' ? node.label.trim() : '';\n const type = node?.type ?? '';\n const base = label || NODE_TYPE_DEFS[type]?.label || type;\n if (!fieldId) return base;\n const fields = Array.isArray(node?.config?.fields) ? node.config.fields : [];\n const f = fields.find((x) => x?.id === fieldId);\n return `${base} - ${contactFieldLabel({ id: fieldId, is_custom: f?.is_custom, label: f?.label })}`;\n}\n\nfunction variableDisplayName(key, variables) {\n const list = Array.isArray(variables) ? variables : [];\n const v = list.find((x) => x?.key === key);\n const label = typeof v?.label === 'string' ? v.label.trim() : '';\n if (label) return label;\n if (Object.hasOwn(RECALL_RESERVED_LABELS, key)) return RECALL_RESERVED_LABELS[key];\n return key;\n}\n\n/**\n * Owner-facing text for stored text with recall codes (#5696): each code becomes its chip label in square brackets\n * (`[Name]`, `[Score]`, `[Question - Email]`, `[Deleted question]`, `[Label · fallback]`). Surfaces that cannot show a\n * chip (tables, exports, webhooks) use it. A node label that itself holds codes renders one level deep, variables only\n * (a nested answer code is `[Earlier answer]`). Text without `{{` comes back as the same string.\n */\nexport function recallDisplayText(text, ctx) {\n if (typeof text !== 'string' || !text.includes('{{')) return text;\n const variables = ctx?.variables;\n const nodes = Array.isArray(ctx?.nodes) ? ctx.nodes : [];\n const render = (input, nested) =>\n input.replace(new RegExp(RECALL_TOKEN_SOURCE, 'g'), (_whole, ref, fallback) => {\n const parsed = parseRecallRef(ref);\n let name;\n if (parsed?.kind === 'answer') {\n if (nested) {\n name = 'Earlier answer';\n } else {\n const node = nodes.find((n) => n?.id === parsed.nodeId);\n if (!node) {\n name = 'Deleted question';\n } else {\n name = recallAnswerLabel(node, parsed.fieldId);\n if (name.includes('{{')) name = render(name, true);\n }\n }\n } else {\n name = variableDisplayName(parsed?.key ?? ref, variables);\n }\n return fallback !== undefined ? `[${name} · ${fallback}]` : `[${name}]`;\n });\n return render(text, false);\n}\n\n// Step pastel (NODE_TYPES[type].color) -> What's new palette family.\nexport const STEP_COLOR_PALETTE = {\n '#E9D5FF': 'violet',\n '#ECFCCB': 'lime',\n '#D1FAE5': 'lime',\n '#DBEAFE': 'sky',\n '#FFEDD5': 'peach',\n '#E0E7FF': 'indigo',\n};\n\n// FEATURES.category -> palette for launches that are not a step.\nconst CATEGORY_PALETTE = {\n builder: 'violet',\n ai: 'violet',\n analytics: 'sky',\n responses: 'sky',\n sharing: 'peach',\n integrations: 'indigo',\n api: 'lime',\n};\n\n/**\n * The mesh-gradient palette ({ name, stops, ink }) for a launch's pop-up hero:\n * an explicit `announce.palette`, else the step colour family for `node_<type>`\n * keys, else the feature's category, else sky.\n */\nexport function getAnnouncementPalette(key) {\n const feature = FEATURES[key];\n let name = feature?.announce?.palette;\n if (!name && key.startsWith('node_')) {\n name = STEP_COLOR_PALETTE[NODE_TYPE_DEFS[key.slice('node_'.length)]?.color];\n }\n if (!name) name = CATEGORY_PALETTE[feature?.category];\n if (!name) name = 'sky';\n return { name, ...ANNOUNCE_PALETTES[name] };\n}\n","import { BUSINESS } from \"@vid-master/config\";\nimport {\n getMcpAuth,\n MCP_ANONYMOUS_HEADER,\n MCP_AUTH_VIA_HEADER,\n MCP_MINT_PROOF_HEADER,\n MCP_SESSION_ID_HEADER,\n MCP_SESSION_PROOF_HEADER,\n} from \"./auth-context.js\";\nimport { reportError, isServerFault, isAuthFault } from \"./telemetry.js\";\nimport { ERROR_KIND_META_KEY } from \"./error-kind.js\";\n\nfunction getApiBaseUrl(): string {\n const url = process.env.API_URL;\n if (!url) {\n const message =\n \"API_URL must be set (e.g. http://localhost:3003 or https://api.clipform.io)\";\n // Reachable in production only through the in-process reporter\n // (apps/api/src/lib/mcp-telemetry-bridge.ts) - the default HTTP reporter\n // needs this same API_URL to know where to POST, so it can never fire\n // here on its own (telemetry.ts's reportError, #2599 blocker 5).\n reportError({\n error_type: \"config_error\",\n error_message: message,\n tool_name: getMcpAuth()?.tool_name,\n });\n throw new Error(message);\n }\n return url;\n}\n\n\nfunction getAuthHeaders(): Record<string, string> {\n const authCtx = getMcpAuth();\n // #4657: the no-workspace anon lane has no credential by design. Fail\n // closed: never fall back to the process's CLIPFORM_API_KEY either.\n if (authCtx?.loadInternalContent && !authCtx.api_key) {\n throw new Error(\"The anonymous no-workspace lane cannot call the API.\");\n }\n const apiKey = authCtx?.api_key || process.env.CLIPFORM_API_KEY;\n if (!apiKey) {\n const message = \"CLIPFORM_API_KEY must be set.\";\n reportError({\n error_type: \"config_error\",\n error_message: message,\n tool_name: authCtx?.tool_name,\n });\n throw new Error(message);\n }\n\n const headers: Record<string, string> = { \"Authorization\": `Bearer ${apiKey}` };\n // Propagate anonymity into the bot-key lane (#2983): the app-chat persona\n // for an anonymous Supabase session runs as an API-key caller under the\n // hood (ensureBotApiKey), so without this marker the API can't tell that\n // request apart from a real integration's key and would let it publish /\n // mint credentials that a direct anonymous-JWT call is denied. See\n // MCP_ANONYMOUS_HEADER's own doc comment for why trusting it is safe.\n if (authCtx?.is_anonymous) {\n headers[MCP_ANONYMOUS_HEADER] = \"1\";\n }\n // #3716: propagate the OAuth-connected label onto the bot-key lane's\n // request so /v1/me reports auth_mode \"oauth\" instead of \"api_key\" - see\n // MCP_AUTH_VIA_HEADER's own doc comment for why trusting it is safe.\n if (authCtx?.auth_via === \"oauth\") {\n headers[MCP_AUTH_VIA_HEADER] = \"oauth\";\n }\n // #3330 review fix: propagate the mint proof (if this request's anon lane\n // freshly minted an identity) so create-form.ts can safely offer a\n // same-UID claim link - see MCP_MINT_PROOF_HEADER's doc comment.\n if (authCtx?.mcp_mint_proof) {\n headers[MCP_MINT_PROOF_HEADER] = authCtx.mcp_mint_proof;\n }\n // #4090: session-reuse sibling of the mint proof.\n if (authCtx?.mcp_session_proof) {\n headers[MCP_SESSION_PROOF_HEADER] = authCtx.mcp_session_proof;\n }\n if (authCtx?.mcp_session_id) {\n headers[MCP_SESSION_ID_HEADER] = authCtx.mcp_session_id;\n }\n return headers;\n}\n\ninterface ApiOptions {\n method?: string;\n body?: Record<string, unknown>;\n params?: Record<string, string>;\n timeoutMs?: number;\n}\n\ntype ApiResult =\n | { ok: true; data: Record<string, unknown> }\n // code/reason are the API's own `{ code, error }` body fields (errorCode\n // below) and `details.reason` - optional because not every failure path\n // (network error, a 204/timeout) has a parsed error body to read them\n // from. Pure addition: every existing consumer reads status/error only.\n // apiMessage is the API's own message WITHOUT the recoveryHint `error`\n // appends - for surfaces (the OAuth challenge's error_description) that\n // must carry only the API text (#4649).\n | { ok: false; status: number; error: string; apiMessage?: string; code?: string; reason?: string };\n\nexport async function callApi(\n path: string,\n options: ApiOptions = {}\n): Promise<ApiResult> {\n const { body, params, timeoutMs = 30_000 } = options;\n const method = options.method || (body ? \"POST\" : \"GET\");\n\n const base = getApiBaseUrl();\n const prefix = path.startsWith(\"/internal/\") ? \"\" : \"/v1\";\n let url = `${base}${prefix}${path}`;\n if (params) {\n const searchParams = new URLSearchParams(params);\n url += `?${searchParams.toString()}`;\n }\n\n // Creative endpoints (/internal/*) authenticate with the same Bearer API\n // key as everything else. The X-Service-Secret header the MCP used to send\n // is webhook-trigger auth only and was dropped here (#412 F7).\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n ...getAuthHeaders(),\n };\n\n const fetchOptions: RequestInit = {\n method,\n headers,\n signal: AbortSignal.timeout(timeoutMs),\n };\n\n if (body && method !== \"GET\") {\n fetchOptions.body = JSON.stringify(body);\n }\n\n let response: Response;\n try {\n response = await fetch(url, fetchOptions);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n // A client-side AbortSignal.timeout() abort is a genuine post-ceiling\n // timeout, not a network drop - classify it separately so it doesn't get\n // misfiled as connection_error (#4070). Node 18+/undici names this\n // DOMException \"TimeoutError\"; also match \"AbortError\" / the message\n // substring as a fallback in case the runtime differs. Still reported\n // either way (#2976), just bucketed distinctly.\n const isTimeout =\n err instanceof Error &&\n (err.name === \"TimeoutError\" ||\n err.name === \"AbortError\" ||\n /aborted due to timeout/i.test(message));\n // Full error stays in our own telemetry (internal, never returned to the\n // model) - the tool response gets a stable, friendly message with no\n // internal URL or raw fetch error text (response hygiene, #2976).\n reportError({\n error_type: isTimeout ? \"timeout\" : \"connection_error\",\n error_message: message,\n tool_name: getMcpAuth()?.tool_name,\n api_path: `${prefix}${path}`,\n });\n return {\n ok: false,\n status: 0,\n error: \"Unable to reach the Clipform API right now. Please try again in a moment.\",\n };\n }\n\n if (response.status === 204) {\n return { ok: true, data: {} };\n }\n\n const data = (await response.json()) as Record<string, unknown>;\n\n if (!response.ok) {\n const apiMsg = (data.error as string) || `API error (${response.status})`;\n const details = data.details as Record<string, unknown> | undefined;\n const reason = details && typeof details.reason === \"string\" ? details.reason : undefined;\n const hint = recoveryHint(response.status, path, reason);\n const errorMsg = hint ? `${apiMsg} - ${hint}` : apiMsg;\n // The API's own error `code` (index.ts's onError: `{ code, error }`) is\n // what tells a genuine auth 403 (FORBIDDEN) apart from an ordinary\n // business-logic 403 (e.g. PLAN_LIMIT) - see isAuthFault (#2599).\n const errorCode = typeof data.code === \"string\" ? data.code : undefined;\n if (isServerFault(response.status) || isAuthFault(response.status, errorCode)) {\n reportError({\n error_type: `http_${response.status}`,\n error_message: errorMsg,\n tool_name: getMcpAuth()?.tool_name,\n status_code: response.status,\n api_path: `${prefix}${path}`,\n });\n }\n return {\n ok: false,\n status: response.status,\n error: errorMsg,\n apiMessage: apiMsg,\n code: errorCode,\n reason,\n };\n }\n\n return { ok: true, data };\n}\n\n/** Next-step hint by status + path so an agent can recover instead of\n * retrying blind (#651). The raw API message stays first, hint second. */\nexport function recoveryHint(status: number, path: string, reason?: string): string | undefined {\n if (status === 401 || status === 403) {\n // An anonymous caller has no key to check (#4653): point at the claim URL\n // from clipform_create_form / sign-up instead.\n if (reason === \"anonymous_not_allowed\" || getMcpAuth()?.is_anonymous) {\n return \"This session is anonymous - open the claim URL from clipform_create_form (or sign up) to claim your workspace, then retry.\";\n }\n return \"Check credentials: the key comes from CLIPFORM_API_KEY or the OAuth session - read clipform://context/session for the active workspace and auth mode.\";\n }\n if (status === 404) {\n if (/^\\/forms\\/[^/]+\\/nodes\\//.test(path)) {\n return \"Call clipform_get_form to list this form's nodes and their IDs.\";\n }\n if (/^\\/forms\\/[^/]+/.test(path)) {\n return \"Call clipform_list_forms to find valid form IDs (UUIDs, not the share_id from a form URL).\";\n }\n }\n return undefined;\n}\n\nexport function errorResult(message: string, meta?: Record<string, unknown>) {\n return {\n content: [{ type: \"text\" as const, text: message }],\n isError: true,\n ...(meta ? { _meta: meta } : {}),\n };\n}\n\n/**\n * An error the caller can fix (missing/conflicting args, a broken rule),\n * labelled for telemetry (#5917, see error-kind.ts). It stays `isError: true`:\n * the MCP spec makes input-validation and business-logic errors tool execution\n * errors so the model can see the call failed and self-correct.\n */\nexport function refusedResult(message: string, meta?: Record<string, unknown>) {\n return errorResult(message, { ...meta, [ERROR_KIND_META_KEY]: \"refused\" });\n}\n\n/**\n * True when an API failure refused the caller's request rather than broke:\n * any 4xx except auth faults (401, a FORBIDDEN 403), a timeout (408) or rate\n * limiting (429). A PLAN_LIMIT 403, 404, 409 or 422 is a refusal.\n */\nexport function isRefusedStatus(status: number, code?: string): boolean {\n if (status < 400 || status >= 500) return false;\n if (status === 408 || status === 429) return false;\n return !isAuthFault(status, code);\n}\n\n/** Error result for a callApi failure, labelled refused when the API refused the request. */\nexport function apiErrorResult(\n failure: { status: number; code?: string; error: string },\n message: string = failure.error,\n meta?: Record<string, unknown>\n) {\n return isRefusedStatus(failure.status, failure.code) ? refusedResult(message, meta) : errorResult(message, meta);\n}\n\n// The bare-endpoint Protected Resource Metadata document (RFC 9728) - same\n// URL apps/api/src/mcp/handler.ts derives for its own HTTP-level\n// WWW-Authenticate challenge on the non-forms-surface lane. Derived from\n// config, never hardcoded, so a domain change can't drift the two apart.\nconst PROTECTED_RESOURCE_METADATA_URL = `${BUSINESS.urls.mcp}/.well-known/oauth-protected-resource`;\n\n/**\n * Escapes a value destined for an RFC 6750 quoted-string auth-param\n * (`error=\"...\"`, `error_description=\"...\"`). Strips `\\r`/`\\n` (RFC 6750\n * quoted-string forbids CTLs, and this value is API error text that could\n * contain one) and escapes embedded backslashes/double quotes - without the\n * latter, a value containing a double quote could break out of its quoted\n * segment and inject extra auth-params into the challenge. Mirrors the\n * OpenAI Apps SDK reference implementation, which escapes the same way for\n * the same reason.\n */\nfunction escapeChallengeValue(value: string): string {\n return value.replace(/[\\r\\n]/g, \"\").replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"');\n}\n\n/**\n * True exactly when a callApi failure is the `assertNotAnonymous` account\n * gate (apps/api/src/lib/anonymous-guard.ts) - triple-keyed on status + code\n * + reason so an ordinary 403 (PLAN_LIMIT, a genuine authorization denial, a\n * 500) never escalates an already-logged-in caller into a pointless OAuth\n * re-auth (#4088 over-escalation guard). The only MCP-reachable trigger\n * today is `clipform_update_form`'s `is_live: true` (publish) - see that\n * tool's own comment for why `clipform_create_form`'s use of this same\n * predicate is currently dead code.\n */\nexport function isAnonymousAccountRequired(result: {\n status: number;\n code?: string;\n reason?: string;\n}): boolean {\n return result.status === 403 && result.code === \"FORBIDDEN\" && result.reason === \"anonymous_not_allowed\";\n}\n\n/**\n * Builds the `_meta[\"mcp/www_authenticate\"]` array a tool result carries to\n * trigger the Apps SDK's tool-level OAuth escalation (#4088): an array of\n * RFC 6750 Bearer challenge strings, the runtime half of the two-part\n * contract (the other half is the static MCP_TOOL_SECURITY declaration) -\n * per the Apps SDK auth docs, metadata alone never triggers the flow,\n * only a runtime error carrying this `_meta` key does. Same challenge shape\n * `apps/api/src/mcp/handler.ts` already emits as a real `WWW-Authenticate`\n * HTTP header for a bad/missing Bearer - this is the tool-result equivalent\n * for a caller that reached a tool (anonymously) but hit a feature that\n * requires an account.\n *\n * Callers pass \"insufficient_scope\" (#4844): OpenAI's Apps SDK auth doc\n * (developers.openai.com/plugins/build/auth) shows exactly that code, with a\n * scope, for the no-token tool-result case; \"invalid_token\" reads to the host\n * as a token that went bad and shows a \"connection expired\" card to a user who\n * never connected. This is the tool-RESULT path only - the real HTTP 401\n * headers in apps/api/src/mcp/handler.ts stay \"invalid_token\" (Claude's doc).\n */\n/** OAuth scope named in the tool-result challenge - matches handler.ts REQUIRED_SCOPE. */\nconst CHALLENGE_SCOPE = \"mcp\";\n\nexport function authChallengeMeta(\n errorCode: string,\n description: string,\n resourceMetadata: string = PROTECTED_RESOURCE_METADATA_URL\n): Record<string, unknown> {\n const challenge = [\n `Bearer error=\"${escapeChallengeValue(errorCode)}\"`,\n `error_description=\"${escapeChallengeValue(description)}\"`,\n `resource_metadata=\"${escapeChallengeValue(resourceMetadata)}\"`,\n `scope=\"${CHALLENGE_SCOPE}\"`,\n ].join(\", \");\n return { \"mcp/www_authenticate\": [challenge] };\n}\n\nexport function textResult(text: string) {\n return {\n content: [{ type: \"text\" as const, text }],\n };\n}\n\n/** Like textResult, but also carries a machine-readable `structuredContent`.\n * A tool that declares an `outputSchema` MUST return `structuredContent` on\n * every non-error result (the MCP SDK validates it and throws otherwise) - use\n * this for every success/empty path, and `errorResult` (exempt) for failures.\n * Project to the schema's explicit field set here - never pass raw API rows\n * (response-hygiene invariant, #797). */\nexport function structuredResult(\n text: string,\n structuredContent: Record<string, unknown>\n) {\n return {\n content: [{ type: \"text\" as const, text }],\n structuredContent,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA8BO,IAAM,WAAW;AAAA;AAAA,EAEtB,qBAAqB;AAAA,IACnB,MAAM;AAAA,IACN,aAAa;AAAA,IACb,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,UAAU;AAAA,EACZ;AAAA,EACA,aAAa;AAAA,IACX,MAAM;AAAA,IACN,aAAa;AAAA,IACb,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,UAAU;AAAA,EACZ;AAAA,EACA,eAAe;AAAA,IACb,MAAM;AAAA,IACN,aAAa;AAAA,IACb,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,UAAU;AAAA,EACZ;AAAA,EACA,mBAAmB;AAAA,IACjB,MAAM;AAAA,IACN,aAAa;AAAA,IACb,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,UAAU;AAAA,IACV,YAAY;AAAA,IACZ,UAAU;AAAA,MACR,UAAU;AAAA,MACV,SAAS;AAAA,IACX;AAAA,EACF;AAAA,EACA,YAAY;AAAA,IACV,MAAM;AAAA,IACN,aAAa;AA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/features.js","../../config/help-links.js","../../config/draw-presets.js","../../config/logic-types.js","../../config/variables.js","../../config/node-types.js","../../config/recall.js","../../config/validate.js","../../config/form-types.js","../../config/anon-mcp-limits.js","../../config/logic-chain.js","../../config/guide.js","../../config/index.js","../src/lib/api-client.ts"],"sourcesContent":["/**\n * Feature registry - single source of truth for what Clipform can and cannot do.\n *\n * enabled: runtime gate - does the dashboard/viewer expose this feature?\n * status:\n * 'live' - shipped and working in production\n * 'beta' - available but not fully polished\n * 'planned' - on the roadmap, not yet usable\n *\n * Rules:\n * - Marketing copy, blog posts, and landing pages must only claim features with status 'live'\n * - 'planned' features can be mentioned as \"coming soon\" but never as current capability\n * - When a feature ships: set enabled to true, status to 'live', and stamp wentLiveAt\n * - Everything else derives from this file (PRODUCT.features, FEATURE_FLAGS, content claims)\n *\n * wentLiveAt (optional, 'YYYY-MM-DD'): the date a feature flipped planned -> live. It is\n * the dated capability event the What's New changelog renders (getWhatsNew) and the SEO/GTM\n * skills key off (\"live-but-uncovered -> content backlog\"). Best-effort: features that were\n * already live at this registry's baseline have no known date and stay undated - they're\n * simply absent from the dated timeline until backfilled, never stamped with a wrong date.\n *\n * announce (optional): the dashboard \"What's new\" pop-up slide ({ headline, benefit, href?,\n * palette?, media? }). Benefit-first, sentence case, no em dashes. href is a workspace-relative\n * dashboard path (no leading slash or protocol); without it the action falls back to the\n * feature's help link. palette names an ANNOUNCE_PALETTES entry (default: step colour, then\n * category). media is a real screenshot or clip under apps/dashboard/public/whats-new/ with its\n * pixel width/height. Needs wentLiveAt.\n *\n * @type {Record<string, { name: string, description: string, enabled: boolean, status: 'live' | 'beta' | 'planned', category: string, wentLiveAt?: string, announce?: { headline: string, benefit: string, href?: string, palette?: string, media?: { kind: 'image' | 'video', src: string, width: number, height: number, poster?: string } } }>}\n */\nexport const FEATURES = {\n // -- Builder --\n visual_form_builder: {\n name: 'Visual form builder',\n description: 'Drag-and-drop node-based form builder powered by React Flow',\n enabled: true,\n status: 'live',\n category: 'builder',\n },\n form_themes: {\n name: 'Form themes',\n description: 'Customise primary colour, background colour, and font',\n enabled: true,\n status: 'live',\n category: 'builder',\n },\n media_prompts: {\n name: 'Media prompts',\n description: 'Attach video, audio, or images to any question node',\n enabled: true,\n status: 'live',\n category: 'builder',\n },\n consent_documents: {\n name: 'Agreement documents',\n description: 'Attach a PDF agreement to a consent item, read inline in the viewer with scroll-to-accept',\n enabled: true,\n status: 'live',\n category: 'builder',\n wentLiveAt: '2026-10-02',\n announce: {\n headline: 'Attach a PDF agreement to consent',\n benefit: 'Respondents read it inline and scroll to accept before they continue.',\n },\n },\n node_logic: {\n name: 'Node routing logic',\n description: 'Define the order nodes appear in - currently supports linear paths (A to B to C)',\n enabled: true,\n status: 'live',\n category: 'builder',\n },\n // Backfilled (#4338): apps/viewer/components/FormViewer.tsx renders exactly\n // one node at a time (`currentNode = nodes[currentIndex]`, single\n // `AnimatePresence` block gating on `currentNode`) and transitions to the\n // next on answer - never a scrollable list of every question. No\n // enabled/status change (this has always been the viewer's shape), so no\n // wentLiveAt.\n one_question_at_a_time: {\n name: 'One question at a time',\n description: 'The viewer shows a single question and transitions to the next, never a scrollable list of every question',\n enabled: true,\n status: 'live',\n category: 'builder',\n },\n branching: {\n name: 'Conditional branching',\n description: 'Choice nodes route to different destinations based on which option is picked',\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-06-25',\n category: 'builder',\n },\n funnel: {\n name: 'Lead qualification funnels',\n description: 'Multi-step funnels with conditional routing built on branching',\n enabled: false,\n status: 'planned',\n category: 'builder',\n },\n custom_scores: {\n name: 'Custom scoring',\n description: 'Assign scores to choice options for quizzes and assessments',\n enabled: false,\n status: 'planned',\n category: 'builder',\n },\n text_response: {\n name: 'Text response option',\n description: 'Allow free-text input alongside choice options',\n enabled: false,\n status: 'planned',\n category: 'builder',\n },\n multi_select: {\n name: 'Multi-select choices',\n description: 'Pick-all-that-apply choice questions (checkbox-style selection)',\n // Dogfood-only (#151): invisible beta - enabled:false, never 'live'/'planned' so\n // no public surface lists it. Available to FEATURE_COMPANY_ALLOWLIST.multi_select\n // via companyHasMultiSelect; the global flip (+ wentLiveAt) is the launch step.\n enabled: false,\n status: 'beta',\n category: 'builder',\n },\n variables: {\n name: 'Custom variables',\n description: 'Save answers to named number or text variables and use them in logic and results',\n // Dogfood-only (#5242): invisible beta - enabled:false, never 'live'/'planned' so\n // no public surface lists it. Available to FEATURE_COMPANY_ALLOWLIST.variables\n // via companyHasVariables; the global flip (+ wentLiveAt) is the launch step.\n enabled: false,\n status: 'beta',\n category: 'builder',\n },\n response_trash: {\n name: 'Response trash',\n description: 'Move responses to the trash and restore them from the Responses tab',\n // Dogfood-only (#2862): invisible beta - enabled:false, never 'live'/'planned' so\n // no public surface lists it. Available to FEATURE_COMPANY_ALLOWLIST.response_trash\n // via companyHasResponseTrash; the global flip (+ wentLiveAt) is the launch step.\n enabled: false,\n status: 'beta',\n category: 'builder',\n },\n staged_video_upload: {\n name: 'Large video uploads',\n description: 'Upload long videos and iPhone HDR clips to Clipform storage so they start fast for respondents',\n // Dogfood-only (#6197): invisible beta - enabled:false, never 'live'/'planned' so\n // no public surface lists it. Available to FEATURE_COMPANY_ALLOWLIST.staged_video_upload\n // via getFeatureAccess (the API's upload handshake, apps/api/src/lib/staged-video.ts,\n // and the dashboard's on-device compression). Everyone else keeps the stream route.\n // The flip waits for the media worker host (#5980).\n enabled: false,\n status: 'beta',\n category: 'builder',\n },\n template_walkthrough: {\n name: 'Template walkthrough',\n description: 'A walkthrough written for a company, shown when someone opens their copy of a template in the builder',\n // Dogfood-only (#6269): invisible beta - enabled:false, never 'live'/'planned' so\n // no public surface lists it. Gates AUTHORING only (writing node.config.guide through\n // the API and the MCP's clipform_set_node_guide), via getFeatureAccess for\n // FEATURE_COMPANY_ALLOWLIST.template_walkthrough. Display needs no flag: only copies of\n // a Clipform Public form show a walkthrough.\n enabled: false,\n status: 'beta',\n category: 'builder',\n },\n custom_fonts: {\n name: 'Custom fonts',\n description: 'Upload and use custom fonts in forms',\n enabled: false,\n status: 'planned',\n category: 'builder',\n },\n brand_name: {\n name: 'Custom brand name',\n description: 'Replace Clipform branding with your own brand name',\n enabled: false,\n status: 'planned',\n category: 'builder',\n },\n allow_resume: {\n name: 'Session resume',\n description: 'Respondents can continue a form where they left off',\n enabled: true,\n status: 'live',\n category: 'builder',\n },\n anonymous_builder: {\n name: 'Anonymous builder',\n description: 'Try the builder without an account via /try - an anonymous Supabase session, converted to a real account at publish time',\n // Desktop v1 (#2979) shipped flag-dark: the entry route, publish wall, and\n // conversion modal all land behind this flag. Enabled at launch rollout -\n // the prod Supabase Anonymous Sign-Ins toggle must stay on for /try guest\n // sessions to mint (dev first, then prod after #3016).\n enabled: true,\n status: 'beta',\n category: 'builder',\n },\n try_cohort_landing: {\n name: 'Cohort landing on /try',\n description: 'A UTM-tagged /try visit holds on a cohort-specific landing with a click-to-proceed CTA instead of going straight into the builder',\n // Flagged off (#4816): the landing (#4296) isn't finished, and the viewer's\n // Powered-by link carries utm_* params, so signed-in owners were landing\n // on it too. Off -> a UTM-tagged /try behaves exactly like the no-UTM path.\n enabled: false,\n status: 'planned',\n category: 'builder',\n },\n // Built in #5148 (PR #5155), shipped dark. When off: no builder switch, viewer ignores\n // stored allow_skip, and the MCP hides/drops allow_skip via the config_schema `feature` marker.\n optional_questions: {\n name: 'Optional questions',\n description: 'Builders can mark a draw, camera or booking question optional so respondents can skip it',\n enabled: false,\n status: 'planned',\n category: 'builder',\n },\n draw_target_shape: {\n name: 'Draw target shape',\n description: 'Score a drawing against a builder-drawn target outline (match-to-shape game)',\n // Flagged off for the Draw GA pass (#5052/#5060): existing config.game data\n // is left in place and returns when the flag flips.\n enabled: false,\n status: 'beta',\n category: 'builder',\n },\n\n // -- Node types --\n node_start: {\n name: 'Start node',\n description: 'Entry point for every form',\n enabled: true,\n status: 'live',\n category: 'node-types',\n },\n node_choice: {\n name: 'Multiple choice',\n description: 'Single-select questions with configurable options (multi-select is gated by the multi_select feature)',\n enabled: true,\n status: 'live',\n category: 'node-types',\n },\n node_open: {\n name: 'Open-ended questions',\n description: 'Free-form responses via text, audio, or video',\n enabled: true,\n status: 'live',\n category: 'node-types',\n },\n node_details: {\n name: 'Details',\n // Widened (#4338): the checkbox items are typed 'consent' (required,\n // blocks submission until checked) or 'opt_in' (optional) - see\n // CONSENT_TYPES in node-types.js and the viewer's Contact.tsx. Both are\n // plain text checkboxes available to every creator with no gate. Attaching\n // a PDF agreement document is the separate consent_documents feature (live).\n description: 'Structured fields (name, email, phone, company) with consent and opt-in checkboxes',\n enabled: true,\n status: 'live',\n category: 'node-types',\n },\n node_button: {\n name: 'Button',\n description: 'Simple navigation or statement node',\n enabled: true,\n status: 'live',\n category: 'node-types',\n },\n node_redirect: {\n name: 'Redirect',\n description: 'Terminal node that sends respondents to an external URL',\n enabled: true,\n status: 'live',\n category: 'node-types',\n },\n node_end_screen: {\n name: 'End screen',\n description: 'Configurable thank-you screen with messaging, CTAs, and share button',\n enabled: true,\n status: 'live',\n category: 'node-types',\n },\n node_scale: {\n name: 'Scale / rating',\n description: 'Numerical rating questions (1-10, stars, etc.)',\n enabled: false,\n status: 'planned',\n category: 'node-types',\n },\n node_file_upload: {\n name: 'File upload',\n description: 'Collect files from respondents',\n enabled: false,\n status: 'planned',\n category: 'node-types',\n },\n node_booking: {\n name: 'Booking',\n description: 'Calendly scheduling inside the form',\n // GA 2026-11-08 with Calendly only (#5310). Google Meet stays dark behind\n // integration_google_calendar until #5308/#5309 ship. The\n // NODE_COMPANY_ALLOWLIST.node_booking entry below stays as a safety valve:\n // flip enabled back to false to pull it behind the allowlist again.\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-11-08',\n category: 'node-types',\n announce: {\n headline: 'Let people book a call right in your form',\n benefit: 'Add a Booking step and respondents pick a Calendly time slot without leaving the form.',\n },\n },\n node_draw: {\n name: 'Drawing',\n description: 'Drawing canvas; respondents draw and it is saved as a PNG image',\n // First GA 2026-06-27 (#1012), pulled back behind the allowlist 2026-07-20\n // (#2289), back to GA 2026-10-26 (#5052). The NODE_COMPANY_ALLOWLIST.node_draw\n // entry below stays as a safety valve: flip enabled back to false to pull it\n // behind the allowlist again (creation-gated only - existing nodes render).\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-10-26',\n category: 'node-types',\n announce: {\n headline: 'Let respondents draw their answer',\n benefit: 'Add a Drawing step and each sketch is saved as an image you can view in Responses.',\n },\n },\n node_camera: {\n name: 'Camera',\n // Description mirrors NODE_TYPES.camera.description (the node SSOT) - the\n // node captures photo OR video (allowed_capture, #2759), not photo only.\n description: 'Capture a photo or video from the device camera',\n // GA 2026-10-26 (#5017). The NODE_COMPANY_ALLOWLIST.node_camera entry\n // below stays as a safety valve: flip enabled back to false to pull it\n // behind the allowlist again (draw precedent).\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-10-26',\n category: 'node-types',\n announce: {\n headline: 'Ask for a photo or video from the camera',\n benefit: 'Respondents capture it on their device and it lands with their answers.',\n },\n },\n node_conditional: {\n name: 'If / then',\n description: 'Route the flow to different branches based on a score, max score, or category variable.',\n // Scaffolded disabled (#4105, phase 1 of the #4104 variables engine): code\n // lands ready, but node.type's DB check constraint doesn't accept\n // 'conditional' yet - that's a separate parked holds-migration PR. Flip\n // once the migration has merged (= applied to prod) and the apps have\n // deployed (camera precedent, #2097).\n enabled: false,\n status: 'planned',\n category: 'node-types',\n },\n node_payment: {\n name: 'Payment',\n description: 'Collect payments via Stripe or Paddle inline',\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-09-07',\n category: 'node-types',\n },\n node_binary: {\n name: 'Binary choice',\n description: 'Two-option choice node (yes/no, this/that)',\n enabled: false,\n status: 'planned',\n category: 'node-types',\n },\n node_link_list: {\n name: 'Link list',\n description: 'Terminal node showing a list of links to choose from',\n enabled: false,\n status: 'planned',\n category: 'node-types',\n },\n node_file_download: {\n name: 'File download',\n description: 'Provide files for respondents to download',\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-07-12',\n category: 'node-types',\n },\n node_shopping: {\n name: 'Shopping',\n description: 'Product recommendations with direct checkout',\n enabled: false,\n status: 'planned',\n category: 'node-types',\n },\n\n // -- Response formats --\n text_responses: {\n name: 'Text responses',\n description: 'Respondents type free-form text answers',\n enabled: true,\n status: 'live',\n category: 'responses',\n },\n audio_responses: {\n name: 'Audio responses',\n description: 'Respondents record audio directly in the browser',\n enabled: true,\n status: 'live',\n category: 'responses',\n },\n video_responses: {\n name: 'Video responses',\n description: 'Respondents record video directly in the browser',\n enabled: true,\n status: 'live',\n category: 'responses',\n },\n transcription: {\n name: 'Auto-transcription',\n description: 'Whisper-powered transcription for audio and video responses',\n enabled: true,\n status: 'live',\n category: 'responses',\n },\n // Backfilled (#4338): the respondent-facing recorder (packages/media-recorder)\n // already device-detects and adapts - mobile-first cover framing by default,\n // front/back camera flip control shown only on mobile, iOS Safari getUserMedia\n // quirks handled (browser-detection.ts) - so recording on a phone has always\n // worked and been tuned for it. No enabled/status change, so no wentLiveAt.\n mobile_recording: {\n name: 'Mobile-optimized recording',\n description: 'Respondents recording audio/video/photo on a phone get a mobile-first layout and a front/back camera flip control',\n enabled: true,\n status: 'live',\n category: 'responses',\n },\n\n // -- Analytics --\n analytics_overview: {\n name: 'Analytics dashboard',\n // Widened #4338: views/starts/completions update live (useInsightRealtime,\n // apps/dashboard's analytics page) and NodeResultCard computes a per-node\n // drop-off count (`total_views - answeredCount`, \"N people dropped off\"),\n // not just an aggregate form-level funnel.\n description: 'Real-time views, starts, and completions with daily time series, plus per-question drop-off',\n enabled: true,\n status: 'live',\n category: 'analytics',\n },\n analytics_demographics: {\n name: 'Demographic breakdown',\n description: 'Country, browser, device, and referrer source analytics',\n enabled: true,\n status: 'live',\n category: 'analytics',\n },\n utm_tracking: {\n name: 'UTM parameter tracking',\n description: 'Track utm_source, utm_medium, utm_campaign on form views',\n enabled: false,\n status: 'planned',\n category: 'analytics',\n },\n csv_export: {\n name: 'CSV export',\n description: 'Export response data to CSV, including transcriptions and media links',\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-06-07',\n category: 'analytics',\n },\n excel_export: {\n name: 'Excel export',\n description: 'Export response data to an Excel file, with the same columns as the CSV export',\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-11-05',\n category: 'analytics',\n announce: {\n headline: 'Download responses as an Excel file',\n benefit: 'Get the same columns as the CSV export, ready to open in Excel.',\n },\n },\n // Backfilled (#4338): the Responses table's search box (DataSpreadsheet's\n // globalFilter, TanStack default `includesString` across every visible\n // column) already searches every node-response column's displayed value -\n // for audio/video answers that value falls back to the transcription text\n // (list_form_submissions / get_latest_responses_for_session's\n // response_data->'transcription'->>'text', supabase/migrations\n // 20260920190000_submission_grain_per_completion.sql) before the generic\n // \"Video/Audio response\" label. So a transcribed response is genuinely\n // full-text searchable today - this key just gives that existing behaviour\n // a name marketing can cite. No enabled/status change (search has always\n // been on), so deliberately no wentLiveAt.\n //\n // Scoped honestly (review follow-up, #4338): this is ONE form's Responses\n // table, filtered client-side (TanStack's globalFilter over the rows\n // already loaded for that form) - never cross-form, and a video/audio\n // answer's transcript only becomes searchable once transcription finishes\n // (checked: no write path ever sets response_data.display or .text on a\n // media answer at submit time - only the async transcription pipeline\n // adds `transcription.text` later, so nothing hides the transcript once it\n // lands; transcription itself is not plan-gated, it runs on every\n // audio/video response regardless of plan). It also never jumps playback\n // to the matched moment in the recording - it only surfaces the row.\n response_search: {\n name: 'Response search',\n description: 'Filter one form\\'s responses table by keyword, including transcript text once transcription finishes - not cross-form, and does not jump to a moment in the recording',\n enabled: true,\n status: 'live',\n category: 'analytics',\n },\n tracked_links: {\n name: 'Tracked links',\n description: 'URL tracking and click-through analytics for shared form links',\n enabled: false,\n status: 'planned',\n category: 'analytics',\n },\n\n // -- Sharing & embedding --\n public_share_links: {\n name: 'Public share links',\n description: 'Share forms via a public URL',\n enabled: true,\n status: 'live',\n category: 'sharing',\n },\n share_node: {\n name: 'Share individual nodes',\n description: 'Share a direct link to a specific node within a form',\n // Pulled back 2026-09-30 (#3791): hides the node-menu Share (copy\n // ?node_id= link) item. Re-enable by flipping back to enabled true +\n // status 'live', and restore the per-step share paragraph in\n // apps/docs/content/docs/help/sharing.mdx.\n enabled: false,\n status: 'beta',\n wentLiveAt: '2026-07-17',\n category: 'sharing',\n },\n public_results: {\n name: 'Public results portal',\n description: 'Share a live, read-only results page with anyone via a link',\n // Ships dark (#2129): code lands ready, gated server-side (apps/api) on\n // this flag OR the FEATURE_COMPANY_ALLOWLIST.public_results company\n // allowlist below (companyHasPublicResults) for per-company dogfood ahead\n // of the global flip - same flag-or-allowlist pattern as node_camera /\n // companyHasNodeType. Flip enabled/status together for GA - the API\n // re-checks this flag on every enable/rotate/read, so flipping it on/off\n // (or editing the allowlist) takes effect immediately, no redeploy needed.\n enabled: false,\n status: 'planned',\n category: 'sharing',\n },\n embed_inline: {\n name: 'Inline embed',\n description: 'Embed forms on external websites via script tag or JavaScript API',\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-05-27',\n category: 'sharing',\n },\n embed_widget: {\n name: 'Embed widget',\n description: 'Floating button that opens a form in a modal overlay',\n enabled: false,\n status: 'planned',\n category: 'sharing',\n },\n dynamic_link: {\n name: 'Dynamic links',\n description: 'A named link that points at a form, so the target can be swapped from the dashboard without changing the embed code or printed link',\n enabled: true,\n status: 'live',\n category: 'sharing',\n wentLiveAt: '2026-08-27',\n },\n custom_domains: {\n name: 'Custom domains',\n description: 'Serve your forms on your own subdomain (forms.yourbrand.com) with vanity paths, instead of a clipform.io link',\n enabled: false,\n status: 'planned',\n category: 'sharing',\n },\n branded_qr: {\n name: 'Branded QR codes',\n description: \"Render a form's share QR in its theme color with the logo centered, instead of plain black\",\n enabled: false,\n status: 'planned',\n category: 'sharing',\n },\n email_share: {\n name: 'Add to an email',\n description: 'Copy-paste image + link snippet for pasting a Clipform into an email campaign',\n enabled: false,\n status: 'planned',\n category: 'sharing',\n },\n remove_branding: {\n name: 'Remove branding',\n description: 'Hide Clipform watermark (Pro plan)',\n enabled: true,\n status: 'live',\n category: 'sharing',\n },\n // Backfilled (#4338): the public /templates gallery (apps/marketing/src/app/templates,\n // apps/marketing/src/components/template-gallery) lets anyone browse and start\n // from a real, live Clipform template - a curated core set, plus the rest\n // (project_template_gallery_curated_core6). No enabled/status change, no wentLiveAt.\n templates_gallery: {\n name: 'Template gallery',\n description: 'Browse and start a form from a real, prebuilt template',\n enabled: true,\n status: 'live',\n category: 'sharing',\n },\n\n // -- AI --\n ai_form_generation: {\n name: 'AI form generation',\n // Corrected twice (#4338): not MCP-only (round 4 found the public\n // web AI builder). In practice this mostly means the ChatGPT/Claude\n // connector (chat_connectors) - leading with that per the user.\n description: 'Generate complete forms from a text prompt, primarily via the ChatGPT and Claude connectors (see chat_connectors); also the public web AI builder on marketing pages; no in-dashboard entry point',\n enabled: true,\n status: 'live',\n category: 'ai',\n },\n // Confirmed live by the user 2026-09-27: both the ChatGPT App Directory and\n // Claude Connectors Directory listings are live. Implementation is\n // packages/mcp-server (the same MCP server surfaced as a connector in both\n // directories - see #797 /\n // #3681). No enabled/status change\n // pending, so no wentLiveAt.\n chat_connectors: {\n name: 'ChatGPT and Claude connectors',\n description: 'Build and edit forms from ChatGPT and Claude via the Clipform connector, listed in both the ChatGPT App Directory and the Claude Connectors Directory',\n enabled: true,\n status: 'live',\n category: 'ai',\n },\n ai_tts: {\n name: 'AI text-to-speech',\n description: 'Generate voiceover audio for form prompts',\n enabled: true,\n status: 'live',\n category: 'ai',\n },\n ai_builder_chat: {\n name: 'AI builder chat',\n description: 'Chat beside the builder canvas to add, reword and branch questions on the open form',\n // Dogfood-only (#6139): invisible beta - enabled:false, never 'live'/'planned' so\n // no public surface lists it. Available to FEATURE_COMPANY_ALLOWLIST.ai_builder_chat\n // via getFeatureAccess (the builder toolbar toggle and POST /v1/ai/builder-chat).\n // Undo (#6161) and a monthly per-plan cap (#6162) land before the global flip.\n enabled: false,\n status: 'beta',\n category: 'ai',\n },\n\n // -- API --\n public_api: {\n name: 'Public API',\n description: 'REST API for form creation, node management, and response collection',\n enabled: true,\n status: 'live',\n category: 'api',\n },\n api_keys: {\n name: 'API key management',\n description: 'Self-service API key creation in the dashboard',\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-06-22',\n category: 'api',\n },\n\n // -- Integrations --\n webhooks: {\n name: 'Webhooks',\n description: 'Send response data to external URLs on form completion',\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-06-24',\n category: 'integrations',\n },\n // Per-integration lifecycle (split from the old coarse `integrations` flag so\n // each can ship independently). integration-catalog.js carries the metadata\n // and derives is_active from these. None are live yet.\n integration_stripe: {\n name: 'Stripe',\n description: 'Accept payments directly in your forms',\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-09-07',\n category: 'integrations',\n },\n // Hub-only gate (#5482): manage Stripe (connect/disconnect) from the\n // Integrations hub. NOT an `integration_*` key on purpose - integration_stripe\n // is globally live (payment node GA), so it cannot gate a hub card that is\n // internal-first. Referenced by the catalog's `hub_feature` on `stripe`.\n stripe_hub_management: {\n name: 'Stripe on the Integrations hub',\n description: 'Connect and disconnect Stripe from the Integrations hub',\n enabled: false,\n status: 'beta',\n category: 'integrations',\n },\n integration_paddle: {\n name: 'Paddle',\n description: 'Accept payments with Paddle',\n enabled: false,\n status: 'planned',\n category: 'integrations',\n },\n integration_square: {\n name: 'Square',\n description: 'Accept payments with Square',\n enabled: false,\n status: 'planned',\n category: 'integrations',\n },\n integration_calendly: {\n name: 'Calendly',\n description: 'Schedule meetings directly in your forms',\n // GA 2026-11-08 with the Booking node (#5310); the allowlist entry below\n // stays as the safety valve.\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-11-08',\n category: 'integrations',\n },\n integration_google_calendar: {\n name: 'Google Meet',\n description: 'Google Calendar scheduling with Google Meet links for the Booking node',\n enabled: false,\n status: 'planned',\n category: 'integrations',\n },\n integration_calcom: {\n name: 'Cal.com',\n description: 'Open-source scheduling platform for booking meetings',\n enabled: false,\n status: 'planned',\n category: 'integrations',\n },\n integration_docusign: {\n name: 'DocuSign',\n description: 'Collect signatures in your forms',\n enabled: false,\n status: 'planned',\n category: 'integrations',\n },\n integration_zapier: {\n name: 'Zapier',\n description: 'Connect to 5,000+ apps and automate workflows',\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-06-21',\n category: 'integrations',\n },\n integration_make: {\n name: 'Make',\n description: 'Advanced automation and integrations',\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-06-22',\n category: 'integrations',\n },\n integration_n8n: {\n name: 'n8n',\n description: 'Open-source workflow automation - trigger flows on form responses',\n enabled: true,\n status: 'live',\n wentLiveAt: '2026-06-26',\n category: 'integrations',\n },\n integration_hubspot: {\n name: 'HubSpot',\n description: 'Sync responses to HubSpot CRM',\n enabled: false,\n status: 'planned',\n category: 'integrations',\n },\n integration_salesforce: {\n name: 'Salesforce',\n description: 'Sync responses to Salesforce CRM',\n enabled: false,\n status: 'planned',\n category: 'integrations',\n },\n integration_slack: {\n name: 'Slack',\n description: 'Post a summary of every completed response to a Slack channel',\n enabled: false,\n status: 'beta',\n category: 'integrations',\n },\n integration_klaviyo: {\n name: 'Klaviyo',\n description: \"Log a Form Completed event on the shopper's Klaviyo profile when they complete a form\",\n enabled: false,\n status: 'beta',\n category: 'integrations',\n },\n integration_kit: {\n name: 'Kit',\n description: \"Tag a subscriber in Kit when they complete a form they opened from a Kit email\",\n enabled: false,\n status: 'beta',\n category: 'integrations',\n },\n integration_shopify: {\n name: 'Shopify',\n description: 'Product recommendations from quiz results with direct checkout',\n enabled: false,\n status: 'planned',\n category: 'integrations',\n },\n integration_google_sheets: {\n name: 'Google Sheets',\n description: 'Sync form responses to a Google Sheet, one row per submission',\n enabled: false,\n status: 'beta',\n category: 'integrations',\n },\n notifications: {\n name: 'Response notifications',\n description: 'Email or webhook alerts when new responses arrive',\n enabled: false,\n status: 'planned',\n category: 'integrations',\n },\n // Intentionally undated: shipped incrementally (API import routes 2026-05-25,\n // /try paste lane #3409 2026-08-30), so it stays out of the What's New feed.\n import_google_forms: {\n name: 'Google Forms importer',\n description: 'Import forms from Google Forms into Clipform',\n enabled: true,\n status: 'live',\n category: 'integrations',\n },\n import_typeform: {\n name: 'Typeform importer',\n description: 'Import forms from Typeform into Clipform',\n enabled: true,\n status: 'live',\n category: 'integrations',\n wentLiveAt: '2026-11-12',\n announce: {\n headline: 'Import from Typeform and Tally',\n benefit: 'Paste a public Typeform or Tally link and get a Clipform you can add video to, no rebuilding.',\n },\n },\n import_tally: {\n name: 'Tally importer',\n description: 'Import forms from Tally into Clipform',\n enabled: true,\n status: 'live',\n category: 'integrations',\n wentLiveAt: '2026-11-12',\n },\n // Went live globally (#4929); gated in the dashboard via companyHasTranscriptCopy.\n transcript_copy: {\n name: 'Copy response transcripts',\n description: 'Copy a whole response transcript, or a single line, as plain text',\n enabled: true,\n status: 'live',\n category: 'responses',\n wentLiveAt: '2026-10-15',\n announce: {\n headline: 'Copy a transcript in one click',\n benefit: 'Copy a whole response transcript, or a single line, as plain text.',\n },\n },\n // Went live globally (#4920); gated in the dashboard via companyHasMediaPlayer\n // (kill switch: set enabled:false + status:'beta' - 'live' with enabled:false throws\n // at load - to fall back to the native audio/video controls).\n media_player: {\n name: 'Response media player',\n description: 'Play voice and video answers in the Responses view with playback speed, volume and seek controls',\n enabled: true,\n status: 'live',\n category: 'responses',\n wentLiveAt: '2026-10-16',\n announce: {\n headline: 'A better player for voice and video answers',\n benefit: 'Change the playback speed, adjust volume and seek through answers in Responses.',\n },\n },\n // -- Workspace --\n // Dashboard navigation, not a product capability: its own category keeps it\n // out of PRODUCT.features (#6211).\n settings_area: {\n name: 'One Settings area',\n description: 'Account, company and workspace settings in one place, each under the scope it applies to',\n enabled: true,\n status: 'live',\n category: 'workspace',\n wentLiveAt: '2026-11-21',\n announce: {\n headline: 'All your settings in one place',\n benefit: 'Account, company and workspace settings now sit together in Settings, and Esc takes you back to your forms.',\n // = DASHBOARD_SETTINGS_PAGES.workspace. index.js imports this file, so it\n // can't import the table back; test/dashboard-settings-paths.test.js pins it.\n href: 'settings/workspace',\n },\n },\n // Dashboard navigation too (#6241): the workspace category keeps it out of\n // PRODUCT.features. MCP itself is on every plan already.\n developers_page: {\n name: 'Developers page',\n description: 'Connect Claude, ChatGPT, Cursor or VS Code to Clipform, and manage API keys, webhooks and authorized apps, in one place',\n enabled: true,\n status: 'live',\n category: 'workspace',\n wentLiveAt: '2026-11-22',\n announce: {\n headline: 'Connect Clipform to Claude, ChatGPT, Cursor or VS Code',\n benefit: 'Add Clipform to your AI tool from the new Developers page, where API keys, webhooks and authorized apps now live too.',\n // = DASHBOARD_DEVELOPER_PAGES.developers, pinned by test/dashboard-settings-paths.test.js.\n href: 'developers',\n },\n },\n};\n\n/**\n * Mesh-gradient palettes for the dashboard What's new pop-up hero (#5763): three\n * stops blended as big blurred colour fields, plus the ink colour for text on\n * top. Named so an announcement can pick one (`announce.palette`); otherwise\n * `getAnnouncementPalette` (index.js) maps the feature by its step colour\n * family or its category. The dashboard never hardcodes these hexes.\n */\nexport const ANNOUNCE_PALETTES = {\n violet: { stops: ['#7C3AED', '#EC4899', '#60A5FA'], ink: '#2E1065' },\n lime: { stops: ['#84CC16', '#FACC15', '#22D3EE'], ink: '#1A2E05' },\n sky: { stops: ['#3B82F6', '#A78BFA', '#F9A8D4'], ink: '#172554' },\n peach: { stops: ['#FB923C', '#F43F5E', '#3B82F6'], ink: '#431407' },\n indigo: { stops: ['#4F46E5', '#A855F7', '#F472B6'], ink: '#1E1B4B' },\n};\n\n// `enabled` (runtime gate) and `status` (lifecycle) are two independent axes -\n// but two pairings are incoherent and almost always a dual-write slip:\n// - status 'live' with enabled:false -> shipped-but-hidden (marketing claims it, no one can use it)\n// - status 'planned' with enabled:true -> advertised as \"coming soon\" but actually exposed\n// 'beta' is intentionally free: enabled:true is a public beta, enabled:false a\n// dark beta (e.g. dynamic_link, #2552 - plumbing lands dark, exposed once the\n// share-surface rework #3104 ships). Catch the two bad pairings at module load\n// so a typo can't ship.\nfor (const [key, f] of Object.entries(FEATURES)) {\n if (f.status === 'live' && !f.enabled) {\n throw new Error(`FEATURES.${key}: status 'live' requires enabled:true (shipped features must be exposed)`);\n }\n if (f.status === 'planned' && f.enabled) {\n throw new Error(`FEATURES.${key}: status 'planned' requires enabled:false (planned features must not be exposed)`);\n }\n // wentLiveAt is the dated go-live event (see header). Only a shipped feature has\n // one, and it must be a real ISO date - a free-text slip would silently corrupt\n // the changelog sort order, so fail at load instead.\n if (f.wentLiveAt !== undefined) {\n if (f.status === 'planned') {\n throw new Error(`FEATURES.${key}: wentLiveAt set but status is 'planned' (only shipped features have a go-live date)`);\n }\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(f.wentLiveAt)) {\n throw new Error(`FEATURES.${key}: wentLiveAt must be 'YYYY-MM-DD' (got ${JSON.stringify(f.wentLiveAt)})`);\n }\n }\n // announce is the dashboard What's New copy: a malformed one would render a\n // blank row or a broken link, so fail at load.\n if (f.announce !== undefined) {\n const a = f.announce;\n if (!f.wentLiveAt) {\n throw new Error(`FEATURES.${key}: announce requires wentLiveAt (an announcement needs a go-live date)`);\n }\n for (const field of ['headline', 'benefit']) {\n if (typeof a?.[field] !== 'string' || !a[field].trim()) {\n throw new Error(`FEATURES.${key}: announce.${field} must be a non-empty string`);\n }\n if (/\\u2014/.test(a[field])) {\n throw new Error(`FEATURES.${key}: announce.${field} must not contain an em dash (use ' - ')`);\n }\n }\n if (a.palette !== undefined && !Object.prototype.hasOwnProperty.call(ANNOUNCE_PALETTES, a.palette)) {\n throw new Error(`FEATURES.${key}: announce.palette must be one of ${Object.keys(ANNOUNCE_PALETTES).join(', ')} (got ${JSON.stringify(a.palette)})`);\n }\n if (a.media !== undefined) {\n const m = a.media;\n if (!m || (m.kind !== 'image' && m.kind !== 'video')) {\n throw new Error(`FEATURES.${key}: announce.media.kind must be 'image' or 'video'`);\n }\n if (typeof m.src !== 'string' || !m.src.startsWith('/whats-new/')) {\n throw new Error(`FEATURES.${key}: announce.media.src must start with '/whats-new/'`);\n }\n // Media size rule: width/height are stored, never learned after load.\n if (!Number.isInteger(m.width) || m.width <= 0 || !Number.isInteger(m.height) || m.height <= 0) {\n throw new Error(`FEATURES.${key}: announce.media.width/height must be positive integers`);\n }\n if (m.poster !== undefined && (typeof m.poster !== 'string' || !m.poster.startsWith('/whats-new/'))) {\n throw new Error(`FEATURES.${key}: announce.media.poster must start with '/whats-new/'`);\n }\n }\n if (a.href !== undefined && (typeof a.href !== 'string' || !a.href || a.href.startsWith('/') || /^[a-z][a-z0-9+.-]*:/i.test(a.href))) {\n throw new Error(`FEATURES.${key}: announce.href must be a workspace-relative path (no leading slash or protocol)`);\n }\n }\n}\n\n/**\n * Backwards-compatible FEATURE_FLAGS object.\n * Maps the old flag names to FEATURES[key].enabled so existing dashboard code\n * keeps working without changes. Migrate consumers to FEATURES.x.enabled over time.\n */\nexport const FEATURE_FLAGS = {\n get ENABLE_BRANCHING() { return FEATURES.branching.enabled; },\n get ENABLE_CUSTOM_SCORES() { return FEATURES.custom_scores.enabled; },\n get ENABLE_TEXT_RESPONSE() { return FEATURES.text_response.enabled; },\n get ENABLE_MULTI_SELECT() { return FEATURES.multi_select.enabled; },\n get INLINE_EMBED() { return FEATURES.embed_inline.enabled; },\n get WIDGET_EMBED() { return FEATURES.embed_widget.enabled; },\n get WEBHOOKS() { return FEATURES.webhooks.enabled; },\n get INTEGRATIONS() { return Object.entries(FEATURES).some(([k, f]) => k.startsWith('integration_') && f.enabled); },\n get CUSTOM_FONTS() { return FEATURES.custom_fonts.enabled; },\n get TRACKED_LINKS() { return FEATURES.tracked_links.enabled; },\n get DYNAMIC_LINK() { return FEATURES.dynamic_link.enabled; },\n get CUSTOM_DOMAINS() { return FEATURES.custom_domains.enabled; },\n get BRANDED_QR() { return FEATURES.branded_qr.enabled; },\n get EMAIL_SHARE() { return FEATURES.email_share.enabled; },\n get SHARE_NODE() { return FEATURES.share_node.enabled; },\n get BRAND_NAME() { return FEATURES.brand_name.enabled; },\n get CSV_EXPORT() { return FEATURES.csv_export.enabled; },\n get ALLOW_RESUME() { return FEATURES.allow_resume.enabled; },\n get UTM_ANALYTICS() { return FEATURES.utm_tracking.enabled; },\n get API_KEYS() { return FEATURES.api_keys.enabled; },\n get NOTIFICATIONS() { return FEATURES.notifications.enabled; },\n get IMPORT_TYPEFORM() { return FEATURES.import_typeform.enabled; },\n get IMPORT_TALLY() { return FEATURES.import_tally.enabled; },\n get PUBLIC_RESULTS() { return FEATURES.public_results.enabled; },\n};\n\n/**\n * Per-integration limited-rollout allowlists - one entry per gated integration.\n * While an\n * integration's FEATURES flag is off, these companies get early access to test\n * it in live. Each integration switches on independently: flip its flag for\n * global GA, or allowlist a company to dogfood ahead of that. Dev + prod company\n * ids differ (separate Supabase projects).\n */\nexport const INTEGRATION_COMPANY_ALLOWLIST = {\n // Slack is built but not GA (#4141/#4154) - dogfood on the internal\n // \"Clipform Public\" company while FEATURES.integration_slack.enabled stays\n // off, so every other company sees the Coming Soon card until launch.\n integration_slack: ['00000000-0000-4000-b000-000000000001'],\n // Google Sheets is built but not GA (#848) - dogfood on the internal\n // \"Clipform Public\" company while FEATURES.integration_google_sheets.enabled\n // stays off, same as Slack above.\n integration_google_sheets: ['00000000-0000-4000-b000-000000000001'],\n // Klaviyo (#6148) ships dark: dogfood on Clipform Public while\n // FEATURES.integration_klaviyo.enabled stays off.\n integration_klaviyo: ['00000000-0000-4000-b000-000000000001'],\n // Kit (#6174) ships dark the same way: dogfood on Clipform Public while\n // FEATURES.integration_kit.enabled stays off.\n integration_kit: ['00000000-0000-4000-b000-000000000001'],\n // Calendly backs the Booking node (#5299) - dogfood on Clipform Public\n // (andy@clipform.io's company on dev + prod) alongside node_booking below.\n integration_calendly: ['00000000-0000-4000-b000-000000000001'],\n // Google Meet booking (#5308/#5309) - dogfood on Clipform Public while\n // FEATURES.integration_google_calendar stays off until Google verifies the\n // Calendar scopes (GA flip #5662).\n integration_google_calendar: ['00000000-0000-4000-b000-000000000001'],\n // integration_zapier + integration_make + integration_n8n removed - all\n // globally live (FEATURES.integration_*.enabled), so companyHasIntegration\n // short-circuits true for everyone; no allowlist needed. (n8n went live with\n // the published Clipform Trigger node, #976.)\n // integration_stripe removed - globally live (FEATURES.integration_stripe.enabled),\n // so companyHasIntegration short-circuits true for everyone; no allowlist needed\n // (payment node GA, #1438).\n};\n\n/**\n * Per-node-type limited-rollout allowlist - same pattern as\n * INTEGRATION_COMPANY_ALLOWLIST, one entry per gated node type (keyed by the\n * FEATURES key, e.g. 'node_payment'). While a node type's FEATURES flag is off,\n * these companies can build with it in live to dogfood ahead of the global flip.\n * Dev + prod company ids differ (separate Supabase projects).\n */\nexport const NODE_COMPANY_ALLOWLIST = {\n // node_payment removed - globally live (FEATURES.node_payment.enabled), so\n // companyHasNodeType short-circuits true for everyone; no allowlist needed\n // (payment node GA, #1438).\n // Camera node dogfood (#2097): build with it in live ahead of the global flip.\n // The node_type_check constraint already permits 'camera' in prod (migration\n // #2103 merged + applied 2026-07-17), so this is a pure app-config allowlist.\n node_camera: [\n '51aef9d0-b26d-4f17-bf6f-583dde728ac2', // prod - Andy's Company\n '00000000-0000-4000-b000-000000000001', // Clipform Public (system company; same id dev + prod)\n ],\n // Conditional node dogfood (#4105): build with it in live ahead of the\n // global flip. Creating a conditional node also needs the node_type_check\n // constraint widen (parked holds-migration PR) - applied on dev already,\n // prod at the next deploy.\n node_conditional: [\n '51aef9d0-b26d-4f17-bf6f-583dde728ac2', // prod - Andy's Company\n '00000000-0000-4000-b000-000000000001', // Clipform Public (system company; same id dev + prod)\n ],\n // File Upload node dogfood (#2905): the results/responses display now renders\n // uploaded files (PR #2907), so build with it in live ahead of the global flip.\n // The node_type_check constraint already permits 'file_upload' (added with the\n // camera migration), so no migration is needed - this is a pure app-config flip.\n node_file_upload: [\n '51aef9d0-b26d-4f17-bf6f-583dde728ac2', // prod - Andy's Company\n '00000000-0000-4000-b000-000000000001', // Clipform Public (system company; same id dev + prod)\n ],\n // Draw node: GA again 2026-10-26 (#5052), so this list is inert while\n // FEATURES.node_draw is enabled. Kept as the safety valve from the #2289\n // pull-back - it also carries the e2e auth user and a demo company so specs\n // and demo forms keep working if draw is ever pulled back again.\n node_draw: [\n '51aef9d0-b26d-4f17-bf6f-583dde728ac2', // prod - Andy's Company\n '00000000-0000-4000-b000-000000000001', // Clipform Public (system company; same id dev + prod)\n 'd9808c42-05ee-4830-9634-f0b1496bf484', // dev - andycsmith313@gmail.com's Company (e2e auth user; draw e2e specs create draw nodes)\n '9dcb32a1-b52f-4873-a099-ed44abd4959f', // dev - Clipform Zapier (demo company with a draw demo form)\n ],\n // Booking node dogfood (#5299): build with it in live ahead of the global\n // flip. node_type_check already permits 'booking' in prod, so this is a\n // pure app-config allowlist. Needs integration_calendly allowlisted too.\n node_booking: [\n '00000000-0000-4000-b000-000000000001', // Clipform Public (andy@clipform.io's company; same id dev + prod)\n ],\n};\n\n/**\n * General-purpose limited-rollout allowlist for a FEATURES-gated capability\n * that isn't a node type or an integration (same pattern as\n * NODE_COMPANY_ALLOWLIST / INTEGRATION_COMPANY_ALLOWLIST, keyed by the\n * FEATURES key). Dev + prod company ids differ (separate Supabase projects).\n */\nexport const FEATURE_COMPANY_ALLOWLIST = {\n // Stripe card + disconnect on the Integrations hub (#5482): internal first,\n // customers keep the \"Coming soon\" card until the launch flip.\n stripe_hub_management: [\n '51aef9d0-b26d-4f17-bf6f-583dde728ac2', // prod - Andy's Company\n '00000000-0000-4000-b000-000000000001', // Clipform Public (system company; same id dev + prod)\n ],\n // Public results portal dogfood (#2129): build with it in live ahead of the\n // global flip. Server-side gate only (apps/api) - see companyHasPublicResults.\n public_results: [\n '51aef9d0-b26d-4f17-bf6f-583dde728ac2', // prod - Andy's Company\n '00000000-0000-4000-b000-000000000001', // Clipform Public (system company; same id dev + prod)\n ],\n // Custom domains dogfood (#3443): build with it live ahead of the global\n // flip. Server-side gate only (apps/api) - see companyHasCustomDomains.\n custom_domains: [\n '51aef9d0-b26d-4f17-bf6f-583dde728ac2', // prod - Andy's Company\n '00000000-0000-4000-b000-000000000001', // Clipform Public (system company; same id dev + prod)\n ],\n // Agreement documents (#2760) went live globally (#4521); the allowlist is\n // intentionally empty and kept only so companyHasConsentDocuments stays valid.\n consent_documents: [],\n // AI answer summaries (#4678): dogfood-only until the benchmark + ZDR are\n // confirmed. Server-side gate only (apps/api) - see companyHasResponseSummary.\n response_summary: [\n '51aef9d0-b26d-4f17-bf6f-583dde728ac2', // prod - Andy's Company\n ],\n // Multi-select choice questions (#151): dogfood-only. Gate lives in\n // companyHasMultiSelect (builder control, API writes, every read that decides\n // behaviour from a stored selection_mode). Clipform Public holds Playground\n // and the templates (anonymous callers have their own companies since #4010):\n // a multi-select template previews as multi-select but copies as single into\n // a company off this list, until the launch flip (#5346).\n multi_select: [\n '51aef9d0-b26d-4f17-bf6f-583dde728ac2', // prod - Andy's Company\n '00000000-0000-4000-b000-000000000001', // Clipform Public (system company; same id dev + prod)\n ],\n // Custom variables (#5242): dogfood-only until the launch flip. Gate lives in\n // companyHasVariables (variables API writes now; viewer and builder later).\n variables: [\n '51aef9d0-b26d-4f17-bf6f-583dde728ac2', // prod - Andy's Company\n '00000000-0000-4000-b000-000000000001', // Clipform Public (system company; same id dev + prod)\n 'd9808c42-05ee-4830-9634-f0b1496bf484', // dev - andycsmith313@gmail.com's Company (e2e auth user)\n ],\n // Response trash (#2862): dogfood-only until the launch flip. Gate lives in\n // companyHasResponseTrash (Responses tab UI + the trash/restore POST routes and\n // the ?trashed reads). Clipform Public holds the dev dogfood logins.\n response_trash: [\n '51aef9d0-b26d-4f17-bf6f-583dde728ac2', // prod - Andy's Company\n '00000000-0000-4000-b000-000000000001', // Clipform Public (system company; same id dev + prod)\n ],\n // AI builder chat (#6139): dogfood-only until undo (#6161) and the per-plan cap\n // (#6162) land. Gate: getFeatureAccess('ai_builder_chat') in the builder toolbar\n // and POST /v1/ai/builder-chat. Clipform Public holds the dev dogfood logins;\n // the e2e auth user's company is Andy's dev login (and the e2e screenshots).\n ai_builder_chat: [\n '51aef9d0-b26d-4f17-bf6f-583dde728ac2', // prod - Andy's Company\n '00000000-0000-4000-b000-000000000001', // Clipform Public (system company; same id dev + prod)\n 'd9808c42-05ee-4830-9634-f0b1496bf484', // dev - andycsmith313@gmail.com's Company (e2e auth user)\n ],\n // Staged video upload (#6197): dogfood-only until the media worker host runs (#5980).\n // Gate: getFeatureAccess('staged_video_upload') in the API's upload handshake and the\n // dashboard's on-device compression. Clipform Public holds the dev dogfood logins;\n // the e2e auth user's company runs the dev e2e upload.\n staged_video_upload: [\n '00000000-0000-4000-b000-000000000001', // Clipform Public (system company; same id dev + prod)\n 'd9808c42-05ee-4830-9634-f0b1496bf484', // dev - e2e auth user's company\n ],\n // Template walkthrough (#6269): only the outbound templates can carry notes, and they\n // live in Clipform Public. Gate: getFeatureAccess('template_walkthrough') in the API's\n // guide writes and the MCP's clipform_set_node_guide registration.\n template_walkthrough: [\n '00000000-0000-4000-b000-000000000001', // Clipform Public (system company; same id dev + prod)\n ],\n // Copy response transcripts (#4890) went live globally (#4929); the allowlist is\n // intentionally empty and kept only so companyHasTranscriptCopy stays valid.\n transcript_copy: [],\n // Response media player (#4920) went live globally; the allowlist is\n // intentionally empty and kept only so companyHasMediaPlayer stays valid.\n media_player: [],\n};\n\n/**\n * Shared resolver for the flag-or-allowlist rollout pattern. Returns WHY a\n * capability is available: 'public' once its global FEATURES flag is on,\n * 'internal' while it is off but the company sits on the capability's\n * limited-rollout allowlist, else 'none'. Single source of truth for every\n * companyHas* helper and for the dashboard's \"Internal\" badge (#5132).\n */\nfunction resolveFeatureAccess(enabled, companyId, allowlist) {\n if (enabled) return 'public';\n return !!companyId && (allowlist || []).includes(companyId) ? 'internal' : 'none';\n}\n\n/**\n * Company ids allowlisted for a FEATURES-style key, routed by key prefix\n * (integration_* / node_* / else the feature allowlist). Empty when none.\n */\nexport function getFeatureAllowlist(featureKey) {\n if (featureKey.startsWith('integration_')) return INTEGRATION_COMPANY_ALLOWLIST[featureKey] || [];\n if (featureKey.startsWith('node_')) return NODE_COMPANY_ALLOWLIST[featureKey] || [];\n return FEATURE_COMPANY_ALLOWLIST[featureKey] || [];\n}\n\n/**\n * Access level of a FEATURES key for a company: 'public' | 'internal' | 'none'.\n * The allowlist is chosen by key prefix (integration_* / node_* / else the\n * feature allowlist).\n */\nexport function getFeatureAccess(featureKey, companyId) {\n return resolveFeatureAccess(!!FEATURES[featureKey]?.enabled, companyId, getFeatureAllowlist(featureKey));\n}\n\nconst ACCESS_RANK = { none: 0, internal: 1, public: 2 };\n\n/**\n * Combine access levels of a composite gate (e.g. a control shown when either\n * of two features is available): public > internal > none.\n */\nexport function combineFeatureAccess(...accesses) {\n return accesses.reduce((best, a) => (ACCESS_RANK[a] > ACCESS_RANK[best] ? a : best), 'none');\n}\n\nfunction gatedByFlagOrAllowlist(enabled, companyId, allowlist) {\n return resolveFeatureAccess(enabled, companyId, allowlist) !== 'none';\n}\n\n/**\n * Whether a company can use an integration: true once its FEATURES flag is\n * globally live, or while the company sits on that integration's allowlist\n * above. Keyed by the FEATURES key (e.g. 'integration_zapier').\n */\nexport function companyHasIntegration(companyId, integrationKey) {\n return gatedByFlagOrAllowlist(\n !!FEATURES[integrationKey]?.enabled,\n companyId,\n INTEGRATION_COMPANY_ALLOWLIST[integrationKey],\n );\n}\n\n/**\n * Whether a company can see the Integrations surface at all: true if ANY\n * integration is available to it (globally live or allowlisted). Gates the\n * Integrations nav tab - the bare\n * FEATURE_FLAGS.INTEGRATIONS getter ignores the per-integration allowlists, so\n * allowlisted companies would never see the tab while every flag is off.\n */\nexport function companyHasAnyIntegration(companyId) {\n return Object.keys(FEATURES)\n .filter((k) => k.startsWith('integration_'))\n .some((k) => companyHasIntegration(companyId, k));\n}\n\n/**\n * Whether a company can build with a node type: true once its FEATURES flag is\n * globally live, or while the company sits on that node type's allowlist above.\n * Takes the node type key (e.g. 'payment'); maps to the FEATURES key\n * `node_<type>`, the same mapping node-types.js uses to derive is_active.\n */\nexport function companyHasNodeType(companyId, nodeType) {\n const featureKey = `node_${nodeType}`;\n return gatedByFlagOrAllowlist(\n !!FEATURES[featureKey]?.enabled,\n companyId,\n NODE_COMPANY_ALLOWLIST[featureKey],\n );\n}\n\n/**\n * Whether a company can turn on the public results portal: true once the\n * FEATURES flag is globally live, or while the company sits on the\n * public_results allowlist above. Server-side gate only - see apps/api's\n * update-form / rotate-results-share / get-public-results routes.\n */\nexport function companyHasPublicResults(companyId) {\n return gatedByFlagOrAllowlist(\n !!FEATURES.public_results?.enabled,\n companyId,\n FEATURE_COMPANY_ALLOWLIST.public_results,\n );\n}\n\n/**\n * Whether a company can use custom domains: true once the FEATURES flag is\n * globally live, or while the company sits on the custom_domains allowlist\n * above. Server-side gate only - see apps/api's domains.ts customDomainsGate.\n */\nexport function companyHasCustomDomains(companyId) {\n return gatedByFlagOrAllowlist(\n !!FEATURES.custom_domains?.enabled,\n companyId,\n FEATURE_COMPANY_ALLOWLIST.custom_domains,\n );\n}\n\n/**\n * Whether a company can attach documents to consent agreements: true once the\n * FEATURES flag is globally live, or while the company sits on the\n * consent_documents allowlist above. Gates the builder's document-attach UI\n * (#2760) - see apps/dashboard ContactNode.\n */\nexport function companyHasConsentDocuments(companyId) {\n return gatedByFlagOrAllowlist(\n !!FEATURES.consent_documents?.enabled,\n companyId,\n FEATURE_COMPANY_ALLOWLIST.consent_documents,\n );\n}\n\n/**\n * Whether a company gets AI summaries of open answers (#4678): true once a\n * FEATURES.response_summary flag is globally live, or while the company sits on\n * the response_summary allowlist above. Server-side gate only - see apps/api's\n * answer-summary.ts.\n */\nexport function companyHasResponseSummary(companyId) {\n return gatedByFlagOrAllowlist(\n !!FEATURES.response_summary?.enabled,\n companyId,\n FEATURE_COMPANY_ALLOWLIST.response_summary,\n );\n}\n\n/**\n * Whether a company can use multi-select choice questions (#151): true once\n * FEATURES.multi_select is globally live, or while the company sits on the\n * multi_select allowlist above. A non-allowlisted company's stored\n * selection_mode 'multiple' must behave as single everywhere (see\n * gateSelectionMode in logic-types.js).\n */\nexport function companyHasMultiSelect(companyId) {\n return gatedByFlagOrAllowlist(\n !!FEATURES.multi_select?.enabled,\n companyId,\n FEATURE_COMPANY_ALLOWLIST.multi_select,\n );\n}\n\n/**\n * Whether a company can move responses to the trash and restore them (#2862):\n * true once FEATURES.response_trash is globally live, or while the company sits\n * on the response_trash allowlist above.\n */\nexport function companyHasResponseTrash(companyId) {\n return gatedByFlagOrAllowlist(\n !!FEATURES.response_trash?.enabled,\n companyId,\n FEATURE_COMPANY_ALLOWLIST.response_trash,\n );\n}\n\n/**\n * Whether a company gets the copy-transcript buttons on response transcripts\n * (#4890): true once FEATURES.transcript_copy is globally live, or while the\n * company sits on the transcript_copy allowlist above.\n */\nexport function companyHasTranscriptCopy(companyId) {\n return gatedByFlagOrAllowlist(\n !!FEATURES.transcript_copy?.enabled,\n companyId,\n FEATURE_COMPANY_ALLOWLIST.transcript_copy,\n );\n}\n\n/**\n * Whether a company gets the Video.js response media player (#4920) for audio\n * and video answers instead of the native controls: true once\n * FEATURES.media_player is globally live (flag off = kill switch), or while the\n * company sits on the media_player allowlist above.\n */\nexport function companyHasMediaPlayer(companyId) {\n return gatedByFlagOrAllowlist(\n !!FEATURES.media_player?.enabled,\n companyId,\n FEATURE_COMPANY_ALLOWLIST.media_player,\n );\n}\n\n/**\n * Whether a company can use custom variables (#5242): true once\n * FEATURES.variables is globally live, or while the company sits on the\n * variables allowlist above.\n */\nexport function companyHasVariables(companyId) {\n return gatedByFlagOrAllowlist(\n !!FEATURES.variables?.enabled,\n companyId,\n FEATURE_COMPANY_ALLOWLIST.variables,\n );\n}\n\nexport function getLiveFeatures() {\n return Object.values(FEATURES).filter(f => f.status === 'live');\n}\n\nexport function getPlannedFeatures() {\n return Object.values(FEATURES).filter(f => f.status === 'planned');\n}\n\nexport function getFeaturesByCategory(category) {\n return Object.values(FEATURES).filter(f => f.category === category);\n}\n\n/**\n * The What's New timeline: live features with a known go-live date, newest first.\n * The single machine-readable source for the user-facing changelog and the SEO/GTM\n * \"what shipped recently\" signal. Returns [key, feature] entries so consumers can\n * derive links/anchors from the key. Features live since the registry baseline have\n * no wentLiveAt and are intentionally excluded - a dated changelog never invents a date.\n */\nexport function getWhatsNew() {\n return Object.entries(FEATURES)\n .filter(([, f]) => f.status === 'live' && f.wentLiveAt)\n .sort(([, a], [, b]) => b.wentLiveAt.localeCompare(a.wentLiveAt));\n}\n\n/** Most launches the dashboard What's new pop-up carries (a carousel, one per slide). */\nexport const WHATS_NEW_POPUP_LIMIT = 5;\n\n/** Live features that carry dashboard announce copy, newest first, as [key, feature]. */\nexport function getAnnouncements() {\n return getWhatsNew().filter(([, f]) => f.announce);\n}\n\nfunction daysBetween(fromIso, now) {\n const from = Date.parse(`${fromIso}T00:00:00Z`);\n return Math.floor((now.getTime() - from) / 86400000);\n}\n\n/**\n * Announcements a user has not seen yet: within the window, live on or after\n * their signup date (new users never see launches from before they joined), and\n * not in their seen keys. Keys, not a timestamp: deploys are batched, so a\n * cursor would swallow a feature merged before the last look and deployed after.\n * Newest first.\n */\nexport function getUnreadAnnouncements({ seen = [], signedUpAt, now = new Date(), windowDays = 60 } = {}) {\n const signup = signedUpAt ? String(signedUpAt).slice(0, 10) : null;\n return getAnnouncements().filter(([key, f]) => {\n if (seen.includes(key)) return false;\n if (signup && f.wentLiveAt < signup) return false;\n const age = daysBetween(f.wentLiveAt, now);\n return age >= 0 && age <= windowDays;\n });\n}\n\n/** Every announcement still inside the window (the pop-up's recent mode), newest first. */\nexport function getRecentAnnouncements({ now = new Date(), windowDays = 60 } = {}) {\n return getAnnouncements().filter(([, f]) => {\n const age = daysBetween(f.wentLiveAt, now);\n return age >= 0 && age <= windowDays;\n });\n}\n\n/** True for a live feature that went live within `days` (drives the \"New\" pill). */\nexport function isNewFeature(key, now = new Date(), days = 30) {\n const f = FEATURES[key];\n if (!f || f.status !== 'live' || !f.wentLiveAt) return false;\n const age = daysBetween(f.wentLiveAt, now);\n return age >= 0 && age <= days;\n}\n","// @vid-master/config/help-links\n// Single source of truth for every in-product \"Learn more\" deep-link (#394).\n// In-product copy stays a short, actionable summary; the full explanation\n// lives in docs and we link to it, so the two can't drift.\n//\n// HELP_TOPICS is pure data (docs path + anchor, no base URL) so the docs\n// link-check script (apps/docs/scripts/check-help-links.mjs) can verify every\n// anchor resolves to a real heading without touching env. Consumers use\n// HELP_LINKS from the package root, which composes full URLs off\n// BUSINESS.urls.docs.\n\n/**\n * Keyed by concept. `path` is relative to the docs site root (which already\n * includes the /docs basePath); `anchor` must match a heading slug in the\n * target page (custom [#anchor] syntax or the auto-generated slug).\n */\nexport const HELP_TOPICS = {\n goLive: { path: '/help/sharing', anchor: 'go-live' },\n cantGoLive: { path: '/help/sharing', anchor: 'cant-go-live' },\n liveAndDraft: { path: '/help/managing-forms', anchor: 'live-and-draft' },\n publishingChanges: { path: '/help/managing-forms', anchor: 'publishing-changes' },\n embedding: { path: '/help/embed', anchor: null },\n embedTracking: { path: '/help/embed', anchor: 'track-form-events' },\n emailShare: { path: '/help/sharing', anchor: 'share-by-email' },\n publicResults: { path: '/help/public-results', anchor: null },\n trash: { path: '/help/managing-forms', anchor: 'trash' },\n customDomains: { path: '/help/domains', anchor: null },\n // Settings > Profile > Delete account (#6314): the 30-day processing time\n // and \"cancel Pro first\" live here, not on the card.\n deleteAccount: { path: '/help/account', anchor: 'delete-your-account' },\n customPath: { path: '/help/links', anchor: 'custom-path-on-your-domain' },\n // Per-node-type deep-links into help/node-types.mdx (#3963). Keyed\n // `node_<nodeType>` so nodeHelpLink() (index.js) can look one up straight\n // from a node's type id.\n node_choice: { path: '/help/node-types', anchor: 'choice' },\n node_open: { path: '/help/node-types', anchor: 'open-ended' },\n node_camera: { path: '/help/node-types', anchor: 'camera' },\n node_draw: { path: '/help/node-types', anchor: 'drawing' },\n node_details: { path: '/help/node-types', anchor: 'details' },\n node_button: { path: '/help/node-types', anchor: 'button' },\n node_end_screen: { path: '/help/node-types', anchor: 'end-screen' },\n node_redirect: { path: '/help/node-types', anchor: 'redirect' },\n node_file_download: { path: '/help/node-types', anchor: 'file-download' },\n node_booking: { path: '/help/node-types', anchor: 'booking' },\n node_payment: { path: '/help/node-types', anchor: 'payment' },\n // Keyed by FEATURES key so a non-node launch announcement (What's new, #3705) gets a\n // \"Learn more\" action: useWhatsNew falls back to HELP_LINKS[featureKey].\n import_typeform: { path: '/help/import-typeform', anchor: null },\n // The MCP setup guide (#6241): the Developers AI tab's one docs link. Claude\n // and ChatGPT's steps moved onto the tab itself (#6300), so their per-client\n // anchors went.\n mcp: { path: '/api/mcp', anchor: null },\n};\n\n/** Compose full HELP_LINKS URLs from a docs base URL (no trailing slash). */\nexport function buildHelpLinks(docsBaseUrl) {\n const links = {};\n for (const [key, { path, anchor }] of Object.entries(HELP_TOPICS)) {\n links[key] = `${docsBaseUrl}${path}${anchor ? `#${anchor}` : ''}`;\n }\n return links;\n}\n","// Built-in diagram presets for the draw node (#1828, #5051, #5263, #5331). A preset is a static\n// image shipped with the viewer and referenced BY NAME in node config\n// (`config.diagram.preset`), never a media asset - nothing is stored per workspace.\n// Files live in apps/viewer/public/viewer-static/draw-presets (the `viewer-static`\n// prefix is the apex-exclusion path: a root viewer path would 308 to www on clipform.io).\n\n/** Picker section order. A group with no presets renders nothing. */\nexport const DRAW_PRESET_GROUPS = [\n { id: 'body', label: 'Body' },\n { id: 'vehicle', label: 'Vehicle' },\n { id: 'animal', label: 'Animal' },\n];\n\n/** Public URL folder (relative to a viewer origin) the preset files are served from. */\nexport const DRAW_PRESET_PATH_PREFIX = '/viewer-static/draw-presets';\n\nexport const DRAW_PRESETS = [\n { id: 'body-front', label: 'Body diagram - front', shortLabel: 'Front', file: 'body-front.png', group: 'body' },\n { id: 'body-back', label: 'Body diagram - back', shortLabel: 'Back', file: 'body-back.png', group: 'body' },\n { id: 'hands-palms', label: 'Hands diagram - palms', shortLabel: 'Palms', file: 'hands-palms.png', group: 'body' },\n { id: 'hands-backs', label: 'Hands diagram - backs', shortLabel: 'Backs of hands', file: 'hands-backs.png', group: 'body' },\n { id: 'feet-soles', label: 'Feet diagram - soles', shortLabel: 'Soles', file: 'feet-soles.png', group: 'body' },\n { id: 'face-profile', label: 'Face diagram - profile', shortLabel: 'Face', file: 'face-profile.png', group: 'body' },\n { id: 'vehicle-sides', label: 'Vehicle diagram - sides', shortLabel: 'Sides', file: 'vehicle-sides.png', group: 'vehicle' },\n { id: 'vehicle-top', label: 'Vehicle diagram - top and ends', shortLabel: 'Top and ends', file: 'vehicle-top.png', group: 'vehicle' },\n { id: 'dog-sides', label: 'Dog diagram - sides', shortLabel: 'Dog', file: 'dog-sides.png', group: 'animal' },\n { id: 'cat-sides', label: 'Cat diagram - sides', shortLabel: 'Cat', file: 'cat-sides.png', group: 'animal' },\n];\n\nexport const DRAW_PRESET_IDS = DRAW_PRESETS.map((p) => p.id);\n\n/** The catalog entry for a preset id, or undefined for an absent/unknown id. */\nexport function getDrawPreset(id) {\n return typeof id === 'string' ? DRAW_PRESETS.find((p) => p.id === id) : undefined;\n}\n\n/** Relative URL of a preset image (`/viewer-static/draw-presets/<file>`), or null for an unknown id. */\nexport function drawPresetPath(id) {\n const preset = getDrawPreset(id);\n return preset ? `${DRAW_PRESET_PATH_PREFIX}/${preset.file}` : null;\n}\n","// @vid-master/config/logic-types\n// Canonical shape for node branching logic — the VideoAsk-pattern \"actions\" graph\n// stored in node_logic.actions (jsonb). Single source of truth shared by:\n// - apps/viewer (evaluates actions to pick the next node)\n// - apps/api (writes + validates actions)\n// - apps/dashboard (builder edges <-> actions)\n//\n// The types themselves live in logic-types.d.ts. This file exports the runtime\n// constant sets used for validation. The grammar is intentionally small today\n// (one action, one operator); richer branching extends these arrays without a\n// DB migration or API signature change.\n\n/** Action verbs a logic entry can perform. */\nexport const LOGIC_ACTION_TYPES = ['jump'];\n\n/**\n * Condition operators. 'is' is the original choice/binary equality op.\n * 'eq'/'ne'/'gt'/'gte'/'lt'/'lte' are the numeric comparison ops added for\n * the conditional node (#4105) - a branch condition compares a `variable`\n * var against a `constant` var.\n */\nexport const LOGIC_CONDITION_OPS = ['is', 'eq', 'ne', 'gt', 'gte', 'lt', 'lte'];\n\n/**\n * Variable types a condition can reference. 'variable' (#4105) references a\n * built-in routable variable (see ROUTABLE_VARIABLES, e.g. the generic\n * \"score\" number); 'constant' is a literal comparison value.\n */\nexport const LOGIC_VAR_TYPES = ['node', 'option', 'variable', 'constant'];\n\n/** Jump target types. */\nexport const LOGIC_TARGET_TYPES = ['node', 'end_screen', 'redirect', 'link_list'];\n\n/**\n * Operand types (from LOGIC_VAR_TYPES) whose `value` is an entity id that\n * must be REMAPPED when a form is cloned (save_form) - as opposed to\n * 'constant', a literal comparison value with no reference to remap. Single\n * source for the clone path's SQL (`remap_ids_in_actions`, extended for\n * `variable` in `supabase/migrations/20260922030000_save_form_copy_variables.sql`)\n * so a future id-bearing operand type added to LOGIC_VAR_TYPES fails the\n * config<->SQL drift guard until the clone path covers it too (#4192).\n */\nexport const LOGIC_REMAPPABLE_VAR_TYPES = ['node', 'option', 'variable'];\n\n/**\n * The static built-in routable variables (#4105 phase 1 of the #4104\n * variables engine): the generic cumulative number derived from\n * node_options.score -> ScoreState.cumulativeScore. A RESERVED key - never\n * stored as a form_variables row (no id), resolved specially by every\n * consumer (viewer, config, api). Every other routable variable (category\n * today, custom/text later) is a row in the form's own `form_variables`\n * table, identified by its stable `id` - see getFormVariableIds.\n *\n * V1 routes on a plain number vs a constant, so `max_score` (the score's\n * denominator) is NOT a routable variable (#4258) - it wasn't a variable in\n * its own right, just the \"out of\" facet of `score`, and the grammar can't\n * compare a variable against another variable anyway. Quiz score DISPLAY\n * (`maxPossibleScore`, EndScreen \"X out of Y\") is a separate concern and\n * keeps its denominator. If per-variable ceilings or percentage routing land,\n * model the operand as `{ ref, aggregate }` rather than re-adding `max_*`\n * twins (see #4252 discussion).\n */\nexport const ROUTABLE_VARIABLES = ['score'];\n\n/**\n * A form's full set of valid `variable` operand values (#4173, revised\n * stable-id variable registry): the static built-ins (ROUTABLE_VARIABLES)\n * UNION every one of the form's own `form_variables` row ids. Unlike the\n * superseded name-based `getFormRoutableVariables`, this does NOT look at\n * node_options.scores directly - category identity now lives in the\n * form_variables table (backfilled by migration 20260922020000, kept current\n * by the API on category authoring), so a `variable` operand is always\n * either a reserved built-in key or a form_variables.id - never a mutable\n * display name.\n *\n * @param {Array<{ id?: string }>} formVariables - the form's form_variables\n * rows (or the RPC's `variables` array - same {id,...} shape).\n * @returns {string[]} Built-ins first (ROUTABLE_VARIABLES order), then\n * variable ids in the order given.\n */\nexport function getFormVariableIds(formVariables) {\n const ids = (formVariables || [])\n .map((v) => v?.id)\n .filter((id) => typeof id === 'string' && id.length > 0);\n return [...ROUTABLE_VARIABLES, ...ids];\n}\n\n// ── Active-graph semantics ───────────────────────────────────────────────────\n// Toggling branching never deletes node_logic - it changes how the SAME actions\n// are interpreted. A per-option (option-var) edge is live only when its source\n// is a choice/binary node with branching enabled; otherwise it is \"parked\" and\n// the node routes via its node-var/default edge. These helpers are the single\n// source of truth for that rule, so every consumer that walks the logic graph -\n// the publish gate, viewer routing, node ordering and builder validation - reads\n// the identical active graph. (#1021 / #704)\n\n/**\n * Whether per-option (branch) edges are live for a node.\n *\n * Branching is OPT-IN: a choice/binary node routes per-option only when it\n * explicitly sets enable_branching:true. Unset / false -> off (the node routes\n * via its node-var/default edge). This is the single source the publish gate,\n * viewer routing, node ordering and builder validation all derive from, so they\n * read the identical active graph; off-by-default holds even if a brand-new\n * node's config isn't persisted yet. Non-choice nodes always route their edges.\n */\nexport function isBranchingActive(node) {\n if (!node) return true;\n // A multi-select choice has ONE route out (the node-level edge): per-option\n // routes stay stored but paused until the node is switched back to single.\n if (isMultiSelectChoice(node)) return false;\n return node.type === 'choice' || node.type === 'binary'\n ? node.config?.choice?.enable_branching === true\n : true;\n}\n\n/** True for a choice node set to pick more than one option (config.selection_mode). */\nexport function isMultiSelectChoice(node) {\n return node?.type === 'choice' && node.config?.selection_mode === 'multiple';\n}\n\n/**\n * The multi-select rollout gate (#151). When the company isn't allowed\n * multi-select (companyHasMultiSelect), a stored selection_mode 'multiple' must\n * behave as single everywhere: returns the config with selection_mode forced to\n * 'single'. Pure - never mutates the input, and the stored value is never\n * rewritten in the DB on read. Same reference when nothing changes.\n */\nexport function gateSelectionMode(config, allowed) {\n if (allowed || !config || config.selection_mode !== 'multiple') return config;\n return { ...config, selection_mode: 'single' };\n}\n\n/** gateSelectionMode applied to a node's `config` (same node reference when unchanged). */\nexport function gateNodeSelectionMode(node, allowed) {\n if (!node || allowed || node.config?.selection_mode !== 'multiple') return node;\n return { ...node, config: gateSelectionMode(node.config, allowed) };\n}\n\n/** gateNodeSelectionMode over a list (same array when nothing changes). */\nexport function gateNodesSelectionMode(nodes, allowed) {\n if (allowed || !Array.isArray(nodes)) return nodes;\n return nodes.some(n => n?.config?.selection_mode === 'multiple')\n ? nodes.map(n => gateNodeSelectionMode(n, allowed))\n : nodes;\n}\n\n/**\n * Whether a choice node's answer key (per-option scores / correct marks) counts.\n * Answer keys are single-select only: on a multi-select node the stored scores\n * stay put but are paused, so scoring, feedback, correctness and the publish\n * gate all ignore them until the node is switched back to single.\n */\nexport function isAnswerKeyActive(node) {\n return !isMultiSelectChoice(node);\n}\n\n/**\n * Whether a choice option is marked as a correct answer (#5726). Several options\n * may be correct. Reads `is_correct`; the `score === 1` fallback fires only on\n * JSON with no `is_correct` key (an old cached payload or a deploy-order window)\n * and goes away once every reader ships.\n */\nexport function isCorrectOption(option) {\n if (!option) return false;\n return option.is_correct ?? option.score === 1;\n}\n\n/** True if `action` routes per-option (its condition references an option var). */\nexport function isOptionEdge(action) {\n return !!action?.condition?.vars?.some(v => v.type === 'option');\n}\n\n/** True if `action` is the node-level (node-var, no option var) route out. */\nexport function isNodeLevelAction(action, nodeId) {\n const vars = action?.condition?.vars;\n if (!vars || vars.some(v => v.type === 'option')) return false;\n // With a nodeId, only a node-var naming THAT node counts (what the viewer's\n // buildLogicMap keys on); without, any node-var does.\n return vars.some(v => v.type === 'node' && (nodeId === undefined || v.value === nodeId));\n}\n\n/**\n * Replace a choice/binary node's live (node-level) route with `nextActions`\n * while KEEPING its parked per-option actions (branching off, or the node is\n * multi-select) - the single-path writers (header connect, set_logic) must never\n * wipe routes that return on switch-back. Scoped strictly to parked edges: a\n * live option edge (e.g. a legacy button option) is replaced like any other.\n * Optional `valid` ({ optionIds, nodeIds }, arrays or Sets) drops parked edges\n * whose option or jump target no longer exists: the logic write validates every\n * action's references, so one stale parked edge would otherwise 400 the whole\n * write. (#151)\n */\nexport function replaceNodeLevelActions(node, existingActions, nextActions, valid) {\n const parked = (Array.isArray(existingActions) ? existingActions : []).filter(a => {\n if (!isInactiveOptionEdge(node, a)) return false;\n return !hasStaleRef(a, valid);\n });\n return [...parked, ...nextActions];\n}\n\nconst hasId = (set, v) => (set instanceof Set ? set.has(v) : set.includes(v));\n\n/**\n * True if `action` references an option or node missing from `valid`\n * ({ optionIds?, nodeIds? }, arrays or Sets). A check is skipped when its set\n * is not given. Same references actionReferenceErrors checks (any jump-target\n * type, the top-level option anchor, and every node/option condition var).\n */\nfunction hasStaleRef(action, valid) {\n if (valid?.optionIds) {\n if (typeof action.option_id === 'string' && !hasId(valid.optionIds, action.option_id)) return true;\n for (const v of action.condition?.vars || []) {\n if (v.type === 'option' && typeof v.value === 'string' && !hasId(valid.optionIds, v.value)) return true;\n }\n }\n if (valid?.nodeIds) {\n const target = action.details?.to?.value;\n if (typeof target === 'string' && !hasId(valid.nodeIds, target)) return true;\n for (const v of action.condition?.vars || []) {\n if (v.type === 'node' && typeof v.value === 'string' && !hasId(valid.nodeIds, v.value)) return true;\n }\n }\n return false;\n}\n\n/**\n * Drop actions that reference an option or node that no longer exists.\n * `valid` is { optionIds?, nodeIds? } (arrays or Sets); a check is skipped when\n * its set is not given. Returns the SAME array reference when nothing is\n * dropped, so callers can detect a change with `!==`. Used by the API's\n * update-node (options removed) and the builder's choice-node logic writes:\n * the logic write validates every action's references, so one stale ref would\n * otherwise 400 the whole row. (#5345)\n */\nexport function dropStaleRefs(actions, valid) {\n if (!Array.isArray(actions)) return actions;\n const kept = actions.filter(a => !hasStaleRef(a, valid));\n return kept.length === actions.length ? actions : kept;\n}\n\n/**\n * Ensure a node keeps one route out when per-option routing stops being live\n * (branching switched off, or the node switched to multi-select). If the node\n * has per-option actions but no node-level action, append a node-level jump\n * to their target (the single shared target, else the first). Never deletes or\n * rewrites an existing action - per-option rows stay stored, parked. Returns\n * the SAME array reference when nothing needed adding. Shared by the builder\n * branching toggle / Single-Multiple switch and the API's update-node. (#151)\n */\nexport function ensureNodeVarFallback(actions, nodeId) {\n const existing = Array.isArray(actions) ? actions : [];\n if (existing.some(a => isNodeLevelAction(a, nodeId))) return actions;\n const targets = existing.filter(isOptionEdge).map(a => a.details?.to?.value).filter(Boolean);\n if (targets.length === 0) return actions;\n const uniq = Array.from(new Set(targets));\n const fallbackTarget = uniq.length === 1 ? uniq[0] : targets[0];\n return [\n ...existing,\n {\n action: 'jump',\n details: { to: { type: 'node', value: fallbackTarget } },\n condition: { op: 'is', vars: [{ type: 'node', value: nodeId }] },\n },\n ];\n}\n\n/**\n * True if `action` is a parked option edge on `node` - a per-option edge whose\n * source node has branching off. Such edges are excluded from the active graph.\n */\nexport function isInactiveOptionEdge(node, action) {\n return isOptionEdge(action) && !isBranchingActive(node);\n}\n\n// ── Reference integrity ──────────────────────────────────────────────────────\n// \"Every jump target / node-var / option-var must point to something that exists\n// in the form.\" Single source of the rule + message vocabulary, shared by the\n// write-time gate (set-node-logic) and the publish-time validator\n// (graph-validation's dangling_target / stale_option_ref / self_loop apply the\n// same rule at reachable-graph scope). Keeps the API 400 and the publish error\n// speaking the same language. (#1058 / #1270 / #1406)\n\n/**\n * Reference-integrity errors for a single logic action.\n *\n * @param {object} action - a node_logic action ({ details.to.value, condition.vars })\n * @param {Set<string>} nodeIds - all node ids in the form\n * @param {Set<string>} optionIds - option ids on the action's node\n * @param {string} [sourceNodeId] - the node this action lives on. When given, a\n * jump target that equals this node's own id is flagged as `self_loop` instead\n * of `dangling_target` (the target does exist - it's the node itself). Optional\n * for backward compatibility; existing 3-arg callers are unaffected.\n * @param {string[]} [routableVariables] - the set of valid `variable` operand\n * values for this form (see getFormVariableIds): built-in keys UNION the\n * form's own form_variables row ids. Defaults to the static built-ins\n * (ROUTABLE_VARIABLES) for backward compatibility with existing 3/4-arg\n * callers.\n * @returns {Array<{ kind: 'dangling_target' | 'stale_option_ref' | 'self_loop' | 'unresolved_variable', value: string, reason: string }>}\n * one entry per ref that doesn't resolve; [] when all refs exist.\n */\nexport function actionReferenceErrors(action, nodeIds, optionIds, sourceNodeId, routableVariables = ROUTABLE_VARIABLES) {\n const errors = [];\n\n const to = action?.details?.to?.value;\n if (typeof to === 'string') {\n if (sourceNodeId && to === sourceNodeId) {\n errors.push({ kind: 'self_loop', value: to, reason: `jump target ${to} connects the node to itself - remove the self-referencing connection` });\n } else if (!nodeIds.has(to)) {\n errors.push({ kind: 'dangling_target', value: to, reason: `jump target ${to} not found in this form` });\n }\n }\n\n // Explicit branch anchor (#4105): a conditional's branch edge carries its\n // option (node_options row) id as a top-level field rather than inferring\n // it from a condition var - see buildAdjacencyMap/buildLogicMap. Validated\n // the same way as a condition's option var below.\n if (typeof action?.option_id === 'string' && !optionIds.has(action.option_id)) {\n errors.push({ kind: 'stale_option_ref', value: action.option_id, reason: `references option ${action.option_id} not on this node` });\n }\n\n for (const v of action?.condition?.vars || []) {\n if (typeof v?.value !== 'string') continue;\n if (v.type === 'node' && !nodeIds.has(v.value)) {\n errors.push({ kind: 'dangling_target', value: v.value, reason: `references node ${v.value} not in this form` });\n } else if (v.type === 'option' && !optionIds.has(v.value)) {\n errors.push({ kind: 'stale_option_ref', value: v.value, reason: `references option ${v.value} not on this node` });\n } else if (v.type === 'variable' && !routableVariables.includes(v.value)) {\n errors.push({ kind: 'unresolved_variable', value: v.value, reason: `references variable \"${v.value}\" which is not a routable variable` });\n }\n }\n\n return errors;\n}\n","/**\n * Custom form variables (#5647, slice 1 of #5242) - the one shared engine.\n *\n * A custom variable is a named number or text value on a form. \"Save to a\n * variable\" lives ON THE NODE: `node.config.save_to = { variable_id, op,\n * field_id? }`. A Choice node saves the picked answer's text (`option.content`); only a legacy\n * `op: 'add'` marker reads the per-option `node_options.value`.\n * Routing (node_logic) is untouched.\n *\n * `deriveVariables` is pure and recomputes every value from the current answers,\n * so a re-answer replaces that node's contribution and can never double count.\n * The viewer runs it live; the API runs the same function over saved answers, so\n * nothing computed is trusted from the browser.\n */\n\nimport { isAnswerKeyActive } from './logic-types.js';\n\n/** Longest custom variable key. */\nexport const VARIABLE_KEY_MAX_LENGTH = 40;\n\n/** Custom variable key: lowercase letter first, then lowercase letters, digits or underscores, VARIABLE_KEY_MAX_LENGTH max. */\nexport const VARIABLE_KEY_PATTERN = new RegExp(`^[a-z][a-z0-9_]{0,${VARIABLE_KEY_MAX_LENGTH - 1}}$`);\n\n/** Variable value types. */\nexport const VARIABLE_TYPES = ['number', 'text'];\n\n/** Longest text a variable may hold (base, option value or saved answer). */\nexport const VARIABLE_TEXT_MAX_LENGTH = 500;\n\n/** Longest label a variable may carry (matches the form_variables label check). */\nexport const VARIABLE_LABEL_MAX_LENGTH = 200;\n\n/** Most custom variables one form can declare. */\nexport const VARIABLE_MAX_CUSTOM_PER_FORM = 50;\n\n/** Strict decimal: optional sign, digits with an optional fraction. No hex, binary or exponent forms. */\nconst DECIMAL_PATTERN = /^[+-]?(\\d+(\\.\\d*)?|\\.\\d+)$/;\n\n/** Largest absolute number a variable may hold (keeps sums exactly representable). */\nexport const VARIABLE_NUMBER_MAX = 1e12;\n\n/** Node types that can save an answer to a variable. */\nexport const SAVE_TO_NODE_TYPES = ['choice', 'details', 'open'];\n\n/** Save operations. `add` is for number variables only. */\nexport const SAVE_TO_OPS = ['set', 'add'];\n\n/**\n * Keys the platform already uses in links, sessions or the logic engine, so a\n * custom variable can never shadow them. Exact keys; prefixes are below.\n */\nexport const RESERVED_VARIABLE_KEYS = [\n 'node_id',\n 'rsid',\n 'rsid_ts',\n 'qr',\n 'pt',\n 'imp',\n 'display',\n 'max_score',\n 'fbclid',\n 'gclid',\n 'ttclid',\n // The viewer's own query params (a link variable must never shadow or strip them, #5650).\n 'mode',\n 'save',\n 'debug',\n 'play',\n 'sdk',\n 'source',\n 'platform',\n 'auto_height',\n];\n\n/** Reserved key prefixes (UTM parameters and Clipform's own `cf_` namespace). */\nexport const RESERVED_VARIABLE_KEY_PREFIXES = ['utm_', 'cf_'];\n\n/** True when a key is reserved by the platform. */\nexport function isReservedVariableKey(key) {\n if (typeof key !== 'string') return false;\n return (\n RESERVED_VARIABLE_KEYS.includes(key) ||\n RESERVED_VARIABLE_KEY_PREFIXES.some((p) => key.startsWith(p))\n );\n}\n\n/**\n * Validate a NEW custom variable key. Returns an error message, or null when valid.\n */\nexport function validateVariableKey(key) {\n if (typeof key !== 'string' || key === '') return 'Key is required';\n if (!VARIABLE_KEY_PATTERN.test(key)) {\n return `Key must start with a lowercase letter and use only lowercase letters, numbers and underscores (${VARIABLE_KEY_MAX_LENGTH} characters max)`;\n }\n if (isReservedVariableKey(key)) return `\"${key}\" is reserved`;\n return null;\n}\n\n/**\n * Coerce a raw value to a variable type. Returns the value, or undefined when it\n * cannot be represented. number: a finite number or a numeric string. text: a\n * string (a number is stringified) within VARIABLE_TEXT_MAX_LENGTH.\n */\nexport function coerceVariableValue(type, raw) {\n if (type === 'number') {\n let n;\n if (typeof raw === 'number') n = raw;\n else if (typeof raw === 'string' && DECIMAL_PATTERN.test(raw.trim())) n = Number(raw.trim());\n else return undefined;\n if (!Number.isFinite(n) || Math.abs(n) > VARIABLE_NUMBER_MAX) return undefined;\n return n;\n }\n if (type === 'text') {\n let s;\n if (typeof raw === 'string') s = raw;\n else if (typeof raw === 'number' && Number.isFinite(raw)) s = String(raw);\n else return undefined;\n // An empty string is no value (a blank field never overwrites the base), same as for numbers.\n if (s === '' || s.length > VARIABLE_TEXT_MAX_LENGTH) return undefined;\n return s;\n }\n return undefined;\n}\n\n/**\n * Validate a node's `config.save_to` against the form's variables. Returns an\n * error message, or null when valid. `variables` is the form's variable list\n * ({ id, type, kind }); only custom variables can be saved to.\n */\nexport function validateSaveTo(saveTo, nodeType, variables) {\n if (!saveTo || typeof saveTo !== 'object' || Array.isArray(saveTo)) return 'save_to must be an object';\n if (!SAVE_TO_NODE_TYPES.includes(nodeType)) {\n return `A ${nodeType} node cannot save to a variable`;\n }\n const { variable_id: variableId, op, field_id: fieldId, enabled } = saveTo;\n if (enabled !== undefined && typeof enabled !== 'boolean') return 'save_to.enabled must be a boolean';\n if (typeof variableId !== 'string' || variableId === '') return 'save_to.variable_id is required';\n const variable = (variables || []).find((v) => v.id === variableId && v.kind === 'custom');\n if (!variable) return 'save_to.variable_id does not match a custom variable on this form';\n if (!SAVE_TO_OPS.includes(op)) return 'save_to.op must be \"set\" or \"add\"';\n if (op === 'add' && variable.type !== 'number') return 'save_to.op \"add\" works on number variables only';\n if (nodeType === 'details') {\n if (typeof fieldId !== 'string' || fieldId === '') return 'save_to.field_id is required on a details node';\n } else if (fieldId !== undefined && fieldId !== null) {\n return 'save_to.field_id applies to details nodes only';\n }\n return null;\n}\n\n/**\n * Validate a Choice option `value` against a variable's type. null/undefined\n * (no value) is valid. Returns an error message, or null when valid.\n */\nexport function optionValueError(variableType, value) {\n if (value === null || value === undefined) return null;\n if (coerceVariableValue(variableType, value) === undefined) {\n return variableType === 'number' ? 'Option value must be a number' : 'Option value must be text';\n }\n return null;\n}\n\nfunction asArray(value) {\n return Array.isArray(value) ? value : [];\n}\n\nfunction optionsOf(node) {\n return asArray(node?.options ?? node?.node_options);\n}\n\n/** Most points one answer can give one variable (#5805); mirrors choice `config.points`. */\nexport const CHOICE_POINTS_MAX = 999;\n\n/**\n * `node_options.scores` holds two shapes (#5805). THE KEY IS RESOLVED AGAINST THE FORM'S VARIABLES (never a\n * pattern): a key naming a custom NUMBER variable is points toward that variable, keyed by the variable's\n * KEY (a copy keeps keys while it mints new ids); any other key (a category row, or no row) is a legacy\n * personality category NAME. Pass `variables` (or the Set from customNumberKeys) wherever scores are read.\n */\nexport function customNumberKeys(variables) {\n if (variables instanceof Set) return variables;\n const out = new Set();\n for (const v of asArray(variables)) if (v && v.kind === 'custom' && v.type === 'number' && typeof v.key === 'string') out.add(v.key);\n return out;\n}\n\n/** An option's per-variable points: the entries of its `scores` whose key is a custom number variable, `{ key: points }`. */\nexport function optionPoints(option, variables) {\n const scores = option?.scores;\n const out = {};\n if (variables == null || !scores || typeof scores !== 'object' || Array.isArray(scores)) return out;\n const keys = customNumberKeys(variables);\n for (const [k, v] of Object.entries(scores)) {\n if (keys.has(k) && typeof v === 'number' && Number.isFinite(v)) out[k] = v;\n }\n return out;\n}\n\n/** The legacy personality-category entries of a `scores` object: every key that is not a custom number variable's key. */\nexport function legacyCategoryScores(scores, variables) {\n const raw = scores && typeof scores === 'object' && !Array.isArray(scores) ? scores : null;\n const out = {};\n if (!raw) return out;\n const keys = variables == null ? new Set() : customNumberKeys(variables);\n for (const [k, v] of Object.entries(raw)) if (!keys.has(k)) out[k] = v;\n return out;\n}\n\n/** The form's Score variable (a custom number variable keyed `score`), or undefined. */\nexport function findScoreVariable(variables) {\n return asArray(variables).find((v) => v && v.kind === 'custom' && v.type === 'number' && v.key === 'score');\n}\n\n/** The id of the form's Score variable, or undefined. */\nexport function findScoreVariableId(variables) {\n return findScoreVariable(variables)?.id;\n}\n\n/** True when any option of the node carries a points entry (any custom number key). */\nexport function nodeHasPointsMap(node, variables) {\n return optionsOf(node).some((o) => Object.keys(optionPoints(o, variables)).length > 0);\n}\n\n/** True when some option of the node carries a points entry for the variable KEY. */\nexport function nodeHasPointsFor(node, key) {\n return optionsOf(node).some((o) => typeof o?.scores?.[key] === 'number');\n}\n\n/**\n * What deleting a variable changes on one node (#5971): the ONE strip rule the API's DELETE and the builder share.\n * Returns `config` (a copy without `save_to`, when `save_to` names the variable; else null) and `options`, one entry per\n * option that changes: `index`; `was`, its points map as read (null when none); `scores`, the map without the variable's KEY\n * (number variables only; an emptied map is `{}`, never null, so a write replaces the stored one) and `scoresChanged`; and\n * `clearValue` with the `value` it had. Like a Save to that is replaced or cleared, a node that loses its save_to also loses its\n * leftover option values, or they would revive under another setup (e.g. the Score sync turning them into points).\n * Nothing changes: `{ config: null, options: [] }`.\n */\nexport function withoutVariableRefs(node, variable) {\n const config = node?.config;\n const savesTo = !!config && typeof config === 'object' && config.save_to?.variable_id === variable.id;\n let nextConfig = null;\n if (savesTo) {\n nextConfig = { ...config };\n delete nextConfig.save_to;\n }\n const options = [];\n optionsOf(node).forEach((o, index) => {\n const scoresChanged = variable.type === 'number' && typeof o?.scores?.[variable.key] === 'number';\n const clearValue = savesTo && o?.value != null;\n if (!scoresChanged && !clearValue) return;\n const next = { ...(o.scores ?? {}) };\n if (scoresChanged) delete next[variable.key];\n options.push({ index, was: o.scores ?? null, scores: next, scoresChanged, clearValue, value: o.value });\n });\n return { config: nextConfig, options };\n}\n\n/** The node's save_to marker for the variable is switched off (#5649): its map entries then do not count (#5805). */\nexport function pointsDormantFor(node, variable) {\n const saveTo = node?.config?.save_to;\n return !!saveTo && saveTo.variable_id === variable.id && saveTo.enabled === false;\n}\n\n/**\n * The custom number variable a single-select node's ENABLED `save_to` op add points at, or undefined: the one rule for\n * which per-answer entries are live (the server's conversion and re-point, the builder's inputs, #5805). A switched-off\n * marker, op set, a non-number variable and a multi-select all give undefined.\n */\nexport function addTargetVariable(config, variables) {\n const saveTo = config?.save_to;\n if (!saveTo || saveTo.op !== 'add' || saveTo.enabled === false || config?.selection_mode === 'multiple') return undefined;\n return (Array.isArray(variables) ? variables : []).find((v) => v && v.id === saveTo.variable_id && v.kind === 'custom' && v.type === 'number');\n}\n\n/**\n * Validate a `scores` object against the form's variables (#5805). A key naming a custom NUMBER variable must hold\n * a whole number 0..CHOICE_POINTS_MAX; a key naming a custom non-number variable is an error. Any other key is a\n * legacy category (the API's category rule covers it). null when valid.\n */\nexport function pointsMapError(scores, variables) {\n if (scores === null || scores === undefined) return null;\n if (typeof scores !== 'object' || Array.isArray(scores)) return 'scores must be an object';\n for (const [key, value] of Object.entries(scores)) {\n const variable = asArray(variables).find((v) => v && v.key === key && v.kind === 'custom');\n if (!variable) continue;\n if (variable.type !== 'number') return `scores key ${key} is not a number variable`;\n if (!Number.isInteger(value) || value < 0 || value > CHOICE_POINTS_MAX) {\n return `Points must be a whole number from 0 to ${CHOICE_POINTS_MAX}`;\n }\n }\n return null;\n}\n\n/** Points the picked answers of a choice or binary node give the variable (undefined when none carry it, or its marker is dormant). */\nfunction mapContributionOf(node, responseData, variable) {\n if (node.type !== 'choice' && node.type !== 'binary') return undefined;\n if (pointsDormantFor(node, variable)) return undefined;\n const picked = Array.isArray(responseData) ? responseData : [responseData];\n const options = optionsOf(node);\n let total;\n for (const id of picked) {\n const option = options.find((o) => o.id === id);\n const pts = option && typeof option.scores?.[variable.key] === 'number' ? option.scores[variable.key] : undefined;\n if (pts !== undefined) total = (total ?? 0) + pts;\n }\n return total;\n}\n\n/**\n * What one answered node contributes to a variable, already coerced to the\n * variable's type; undefined when the node contributes nothing (no value picked,\n * empty field, non-coercible text).\n */\nfunction contributionOf(node, saveTo, responseData, variableType) {\n if (node.type === 'choice') {\n // Single-select stores a bare option id; multi-select an array of ids.\n const picked = Array.isArray(responseData) ? responseData : [responseData];\n const options = optionsOf(node);\n if (saveTo.op === 'add') {\n // Legacy marker path: the per-option value.\n const values = [];\n for (const id of picked) {\n const option = options.find((o) => o.id === id);\n const v = coerceVariableValue(variableType, option?.value);\n if (v !== undefined) values.push(v);\n }\n if (values.length === 0) return undefined;\n if (variableType === 'number') return values.reduce((a, b) => a + b, 0);\n return values[0];\n }\n // Set: the picked answer's text. Text joins several picks in pick order; a number takes the first that coerces.\n const values = [];\n for (const id of picked) {\n const option = options.find((o) => o.id === id);\n const v = coerceVariableValue(variableType, option?.content);\n if (v !== undefined) values.push(v);\n }\n if (values.length === 0) return undefined;\n if (variableType === 'text') {\n let joined = values.join(', ');\n if (joined.length > VARIABLE_TEXT_MAX_LENGTH) {\n joined = joined.slice(0, VARIABLE_TEXT_MAX_LENGTH);\n // Do not leave half of a surrogate pair.\n if (/[\\uD800-\\uDBFF]$/.test(joined)) joined = joined.slice(0, -1);\n joined = joined.trim();\n }\n return joined === '' ? undefined : joined;\n }\n return values[0];\n }\n if (node.type === 'details') {\n const fields = asArray(responseData?.fields);\n const field = fields.find((f) => f?.id === saveTo.field_id);\n return coerceVariableValue(variableType, field?.value);\n }\n if (node.type === 'open') {\n // Typed answer only: a recording (or its transcript) is never a variable value.\n if (responseData?.response_type !== 'text') return undefined;\n return coerceVariableValue(variableType, responseData?.text);\n }\n return undefined;\n}\n\n/**\n * Compute every custom variable's value from the current answers.\n *\n * @param {Array<{id: string, key: string, type: 'number'|'text', kind: string, base?: unknown, url_settable?: boolean}>} variables\n * @param {Array<{id: string, type: string, config?: {save_to?: {variable_id: string, op: 'set'|'add', field_id?: string}}, options?: Array<{id: string, content?: string, value?: unknown}>}>} nodes\n * @param {Array<{node_id: string, response_data: unknown}>} answers in first-answered order\n * @param {Record<string, unknown>} [linkValues] link-filled raw values keyed by variable key\n * @param {string[]} [path] ordered node ids the respondent actually took. When given,\n * only answers on the path count, applied in path order (an abandoned branch\n * contributes nothing). Omitted: every answer counts, in first-answered order.\n * @returns {Record<string, number|string>} variable id -> value. A number variable\n * always has a value (default 0); a text variable is absent until set.\n */\nexport function deriveVariables(variables, nodes, answers, linkValues, path) {\n const custom = asArray(variables).filter((v) => v && v.kind === 'custom');\n if (custom.length === 0) return {};\n\n const nodeById = new Map(asArray(nodes).map((n) => [n.id, n]));\n\n // One entry per node: a re-answer replaces the data but keeps its place.\n let answered = new Map();\n for (const a of asArray(answers)) {\n if (a && typeof a.node_id === 'string') answered.set(a.node_id, a.response_data);\n }\n if (Array.isArray(path)) {\n // Route taken only: walk the path in order, keep the nodes that have an answer.\n // A revisited node counts once, at its LATEST position (what happened last wins).\n const onPath = new Map();\n for (const id of path) {\n if (!answered.has(id)) continue;\n onPath.delete(id);\n onPath.set(id, answered.get(id));\n }\n answered = onPath;\n }\n\n const out = {};\n for (const variable of custom) {\n let value = coerceVariableValue(variable.type, variable.base);\n if (value === undefined && variable.type === 'number') value = 0;\n\n // A link-filled value replaces the base (only for a variable the link may set).\n if (variable.url_settable && linkValues && Object.hasOwn(linkValues, variable.key)) {\n const fromLink = coerceVariableValue(variable.type, linkValues[variable.key]);\n if (fromLink !== undefined) value = fromLink;\n }\n\n for (const [nodeId, responseData] of answered) {\n const node = nodeById.get(nodeId);\n if (!node) continue;\n const saveTo = node.config?.save_to;\n // enabled === false: the builder switched it off but kept the setup (#5649); it is dormant.\n if (saveTo && saveTo.enabled !== false && saveTo.variable_id === variable.id) {\n const adds = saveTo.op === 'add' && variable.type === 'number';\n // A node with map entries FOR THIS variable gets its points from the map: its save_to add must not count twice (#5805).\n if (!(adds && nodeHasPointsFor(node, variable.key))) {\n const contribution = contributionOf(node, saveTo, responseData, variable.type);\n if (contribution !== undefined) value = adds ? (value ?? 0) + contribution : contribution;\n }\n }\n if (variable.type === 'number') {\n const points = mapContributionOf(node, responseData, variable);\n if (points !== undefined) value = (value ?? 0) + points;\n }\n }\n\n if (value !== undefined) out[variable.id] = value;\n }\n return out;\n}\n\n/** Most link-fillable (`url_settable`) values one session may carry (#5650). */\nexport const VARIABLE_MAX_LINK_PER_FORM = 25;\n\n/**\n * Code point ranges a link value (and anything shown from it) must never carry:\n * C0/C1 controls, soft hyphen, bidi marks and isolates, line/paragraph separators,\n * zero-width and invisible format characters, filler characters, BOM and the tag block.\n * One list, shared by normalizeLinkValue and the viewer's recall guard (#5650).\n */\nexport const LINK_UNSAFE_RANGES = [\n [0x0, 0x1f],\n [0x7f, 0x9f],\n [0xad, 0xad],\n [0x61c, 0x61c],\n [0x115f, 0x1160],\n [0x180e, 0x180e],\n [0x200b, 0x200f],\n [0x2028, 0x202e],\n [0x2060, 0x2064],\n [0x2066, 0x2069],\n [0x3164, 0x3164],\n [0xfeff, 0xfeff],\n [0xe0000, 0xe007f],\n];\n\n/** True when a code point is in LINK_UNSAFE_RANGES. */\nexport function isUnsafeLinkChar(codePoint) {\n return LINK_UNSAFE_RANGES.some(([lo, hi]) => codePoint >= lo && codePoint <= hi);\n}\n\n/** True when the string contains any unsafe link character. */\nexport function hasUnsafeLinkChar(str) {\n for (const ch of String(str)) if (isUnsafeLinkChar(ch.codePointAt(0))) return true;\n return false;\n}\n\n/** The string without any unsafe link character. */\nexport function stripUnsafeLinkChars(str) {\n let out = '';\n for (const ch of String(str)) if (!isUnsafeLinkChar(ch.codePointAt(0))) out += ch;\n return out;\n}\n\n/** Longest raw (undecoded) link value, and key, one pair may carry. */\nexport const LINK_RAW_VALUE_MAX = 4000;\nexport const LINK_RAW_KEY_MAX = 64;\n/** Most raw pairs, and most total key + value characters, one session POST carries (keeps the body far under the 64 KiB keepalive limit). */\nexport const LINK_RAW_PAIRS_MAX = 50;\nexport const LINK_RAW_TOTAL_MAX = 16000;\n\n/**\n * The raw pairs both sides work from. Drops any pair whose key or value is over its cap, then\n * keeps `#` pairs first, then `?` pairs (each in captured order) until the pair cap or the total-size cap is reached. The viewer\n * posts exactly this and pickLinkValues runs it first, so client and server always agree.\n *\n * @template {{key: string, value: string}} T\n * @param {ReadonlyArray<T> | undefined} pairs\n * @returns {T[]}\n */\nexport function capRawLinkPairs(pairs) {\n const valid = [];\n for (const pair of asArray(pairs)) {\n if (!pair || typeof pair.key !== 'string' || typeof pair.value !== 'string') continue;\n if (pair.key.length > LINK_RAW_KEY_MAX || pair.value.length > LINK_RAW_VALUE_MAX) continue;\n valid.push(pair);\n }\n // `#` pairs win over `?` pairs, so when a cap cuts the list the `#` ones survive: hash pairs\n // first, then query pairs, each in captured order (accepts the viewer's fromHash or the wire's from_hash).\n const isHash = (p) => p.fromHash === true || p.from_hash === true;\n const ordered = [...valid.filter(isHash), ...valid.filter((p) => !isHash(p))];\n const out = [];\n let total = 0;\n for (const pair of ordered) {\n const size = pair.key.length + pair.value.length;\n if (out.length >= LINK_RAW_PAIRS_MAX || total + size > LINK_RAW_TOTAL_MAX) break;\n out.push(pair);\n total += size;\n }\n return out;\n}\n\nconst LINK_EMAIL_SHAPE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\nconst LINK_PLACEHOLDERS = [/^\\{\\{.*\\}\\}$/, /^\\{\\$.*\\}$/, /^\\*\\|.*\\|\\*$/, /^%%.*%%$/, /^x{3,}$/i];\n\n/** Percent-decode without throwing on malformed sequences (those stay as typed). */\nfunction safePercentDecode(s) {\n return s.replace(/(?:%[0-9a-fA-F]{2})+/g, (m) => {\n try {\n return decodeURIComponent(m);\n } catch {\n return m;\n }\n });\n}\n\nfunction isLinkPlaceholder(s) {\n return LINK_PLACEHOLDERS.some((re) => re.test(s));\n}\n\n/**\n * Clean one raw link value (the text after `key=` in `?` or `#`).\n * Percent-decodes; `+` is a space except in an email-shaped value; NFC; strips\n * control and bidi characters; trims. Empty or an unrendered merge-tag\n * placeholder is unset. Truncates to VARIABLE_TEXT_MAX_LENGTH.\n *\n * @param {unknown} raw\n * @returns {{ value: string | undefined, truncated: boolean }}\n */\nexport function normalizeLinkValue(raw) {\n if (typeof raw !== 'string') return { value: undefined, truncated: false };\n const keepPlus = LINK_EMAIL_SHAPE.test(safePercentDecode(raw).trim());\n // Turn `+` into a space BEFORE decoding so an encoded %2B stays a plus.\n let s = safePercentDecode(keepPlus ? raw : raw.replace(/\\+/g, ' '));\n // Strip BEFORE NFC so an invisible character between a base and a combining mark can't change\n // the result: the same value normalises identically on first capture and after a re-encode.\n s = stripUnsafeLinkChars(s).normalize('NFC').trim();\n if (s === '' || isLinkPlaceholder(s) || isLinkPlaceholder(raw.trim())) {\n return { value: undefined, truncated: false };\n }\n let truncated = false;\n if (s.length > VARIABLE_TEXT_MAX_LENGTH) {\n s = s.slice(0, VARIABLE_TEXT_MAX_LENGTH);\n // Do not leave half of a surrogate pair.\n if (/[\\uD800-\\uDBFF]$/.test(s)) s = s.slice(0, -1);\n s = s.trim();\n truncated = true;\n }\n return { value: s === '' ? undefined : s, truncated };\n}\n\n/**\n * Pick the link-fillable values out of raw URL pairs.\n * Only `kind === 'custom' && url_settable` variables can be set (builtin and\n * category never). Keys match case-insensitively and are stored under the\n * declared spelling. A `#` pair wins over a `?` pair. At most\n * VARIABLE_MAX_LINK_PER_FORM values. Values stay strings.\n *\n * @param {Array<{key: string, kind: string, url_settable?: boolean}>} variables\n * @param {Array<{key: string, value: string, fromHash?: boolean}>} pairs raw (undecoded) pairs\n * @returns {{ values: Record<string, string>, dropped: string[], truncated: string[] }}\n */\nexport function pickLinkValues(variables, pairs) {\n const declared = new Map();\n for (const v of asArray(variables)) {\n if (\n v &&\n v.kind === 'custom' &&\n v.url_settable === true &&\n typeof v.key === 'string' &&\n VARIABLE_KEY_PATTERN.test(v.key) &&\n !isReservedVariableKey(v.key)\n ) {\n declared.set(v.key.toLowerCase(), v.key);\n }\n }\n const values = {};\n const dropped = [];\n const truncated = [];\n const fromHashKeys = new Set();\n for (const pair of capRawLinkPairs(pairs)) {\n const key = declared.get(pair.key.toLowerCase());\n if (key === undefined) {\n dropped.push(pair.key);\n continue;\n }\n const fromHash = pair.fromHash === true;\n // A hash value is never replaced by a query value.\n if (!fromHash && fromHashKeys.has(key)) continue;\n const { value, truncated: wasTruncated } = normalizeLinkValue(pair.value);\n if (value === undefined) {\n dropped.push(key);\n continue;\n }\n if (!Object.hasOwn(values, key) && Object.keys(values).length >= VARIABLE_MAX_LINK_PER_FORM) {\n dropped.push(key);\n continue;\n }\n values[key] = value;\n if (fromHash) fromHashKeys.add(key);\n const at = truncated.indexOf(key);\n if (wasTruncated && at === -1) truncated.push(key);\n else if (!wasTruncated && at !== -1) truncated.splice(at, 1);\n }\n return { values, dropped, truncated };\n}\n\n/** A built link longer than this gets a warning (some tools and chats cut long links) (#5683). */\nexport const VARIABLE_LINK_WARN_CHARS = 2000;\n\n/**\n * True for a key that likely holds personal data (`email`, `phone`, `name`, as the whole key or a\n * `_`-separated token). Such values go after `#` in the link so they never reach a server log.\n * Warn only - never blocks.\n */\nexport function isPersonalLinkKey(key) {\n if (typeof key !== 'string') return false;\n return key\n .toLowerCase()\n .split('_')\n .some((token) => token === 'email' || token === 'phone' || token === 'name');\n}\n\n/**\n * Tools that can put an id into a link, so a respondent's id reaches the form (#5683).\n * Rule: major email tools only, one each, and only where the tag or setup is easy to get wrong.\n * `snippet` is the text to paste into the tool (null when the tool adds it itself).\n */\nexport const LINK_VARIABLE_PRESETS = [\n {\n id: 'mailchimp',\n tool: 'Mailchimp',\n key: 'mailchimp_id',\n type: 'text',\n snippet: '?mailchimp_id=*|UNIQID|*',\n note: 'Add this to the end of your form link in your Mailchimp campaign.',\n },\n {\n id: 'kit',\n tool: 'Kit',\n key: 'ck_subscriber_id',\n type: 'text',\n snippet: null,\n note: 'In Kit, turn on \"Add subscriber_id parameter in email links\" in advanced tracking. Kit then adds ck_subscriber_id to every link in your broadcasts and sequences.',\n help_url: 'https://help.kit.com/en/articles/9375532-global-advanced-tracking',\n },\n];\n\n/** The preset whose key is `key`, or undefined. */\nexport function linkVariablePreset(key) {\n return LINK_VARIABLE_PRESETS.find((p) => p.key === key);\n}\n\n/**\n * The form link with every link-fillable variable on it, for the builder's \"Your link\" box.\n * Custom `url_settable` variables with a non-reserved key, in panel order. Personal keys\n * (email, phone, name) go after `#`, the rest in the query. A missing value becomes `key=`.\n *\n * @param {string} shareUrl\n * @param {Array<{key: string, kind: string, url_settable?: boolean}>} variables\n * @param {(variable: object) => unknown} valueFor\n * @returns {string}\n */\nexport function buildVariableLink(shareUrl, variables, valueFor) {\n const query = [];\n const hash = [];\n for (const v of asArray(variables)) {\n if (!v || v.kind !== 'custom' || v.url_settable !== true) continue;\n if (typeof v.key !== 'string' || isReservedVariableKey(v.key)) continue;\n const raw = valueFor ? valueFor(v) : undefined;\n const value = raw === undefined || raw === null ? '' : String(raw);\n const pair = `${v.key}=${encodeURIComponent(value)}`;\n (isPersonalLinkKey(v.key) ? hash : query).push(pair);\n }\n let url = shareUrl;\n if (query.length) url += (url.includes('?') ? '&' : '?') + query.join('&');\n if (hash.length) url += `#${hash.join('&')}`;\n return url;\n}\n\n/**\n * The most points a respondent can score (#5727), for the End Screen \"out of N\" preset.\n * With a custom number variable keyed `score`: each choice node that adds to it counts\n * its top option value (single-select) or the sum of its positive values (multi-select).\n * Without one: the legacy denominator the viewer builds (top positive `score` per node\n * where the answer key is active, see apps/viewer/lib/scoring.ts).\n */\nexport function pointsAvailable(variables, nodes) {\n const scoreVar = asArray(variables).find((v) => v && v.kind === 'custom' && v.type === 'number' && v.key === 'score');\n let total = 0;\n for (const node of asArray(nodes)) {\n const options = optionsOf(node);\n if (options.length === 0) continue;\n if (scoreVar) {\n let values;\n if (nodeHasPointsFor(node, scoreVar.key)) {\n // Map entries for the Score are the node's points; its save_to add is not also counted (#5805).\n // A switched-off marker for the Score (#5649) makes the entries dormant: they count for nothing.\n if ((node.type !== 'choice' && node.type !== 'binary') || pointsDormantFor(node, scoreVar)) continue;\n values = options.map((o) => o?.scores?.[scoreVar.key]).filter((v) => typeof v === 'number' && v > 0);\n } else {\n const saveTo = node?.config?.save_to;\n if (node.type !== 'choice' || !saveTo || saveTo.enabled === false || saveTo.op !== 'add' || saveTo.variable_id !== scoreVar.id) continue;\n values = options.map((o) => o?.value).filter((v) => typeof v === 'number' && Number.isFinite(v) && v > 0);\n }\n if (values.length === 0) continue;\n total += node.config?.selection_mode === 'multiple'\n ? values.reduce((a, b) => a + b, 0)\n : Math.max(...values);\n } else {\n if (!isAnswerKeyActive(node)) continue;\n const top = Math.max(...options.map((o) => o?.score ?? 0));\n if (top > 0) total += top;\n }\n }\n return total;\n}\n\n/**\n * The End Screen score line preset (#5727, #5728): \"You scored {{score}} out of N\",\n * or \"You scored {{score}}\" when N is 0. Shared by the builder and the API.\n */\nexport function scoreLinePreset(points) {\n return Number.isFinite(points) && points > 0\n ? `You scored {{score}} out of ${points}`\n : 'You scored {{score}}';\n}\n\n/**\n * Whether a node's options carry real points (#5728): some option is a correct answer\n * (`is_correct === true`) or has a non-null, non-zero `score`. The builder sends\n * `{ score: null, is_correct: false }` on every option of an unscored question, which is NOT scored.\n */\nexport function hasPointOptions(options) {\n return asArray(options).some((o) => o && (o.is_correct === true || (o.score != null && o.score !== 0)));\n}\n\n/**\n * Whether a node should be wired to the form's Score variable (#5728): a single-select\n * choice with real points (see hasPointOptions) and no `save_to` key, or a `save_to` op SET (#5806: Save to is\n * independent of points; the Set marker is kept). A dormant add `save_to`\n * (`enabled: false`) counts as a key and is never rewired; multi-select, binary and\n * category-only nodes are left alone. `config` must already have the selection-mode gate applied.\n */\nexport function qualifiesForScoreWiring(type, config, options) {\n if (type !== 'choice') return false;\n // A SET marker (Save to capturing an answer) is independent of points (#5806): it does not block Score wiring.\n // Any other save_to (an add, switched on or off) does.\n if (config?.save_to != null && config.save_to.op !== 'set') return false;\n if (config?.selection_mode === 'multiple') return false;\n return hasPointOptions(options);\n}\n\n/**\n * Wire a scored choice node to the Score variable (#5728, #5805): writes the marker `save_to { variable_id, op: 'add' }`\n * (so the node shows as saving to Score) AND, on each option with a non-zero `score`, `scores[variable.key] = score`\n * (legacy category entries and an entry already set are kept). No `value` is written: the points live in the map,\n * the marker adds nothing twice (see deriveVariables). Pure. `variable` is `{ id, key }`. Returns the inputs untouched\n * with `wired: false` when the node does not qualify or is already wired (some option carries a `scores[key]` entry).\n */\nexport function withScoreVariable(type, config, options, variable) {\n if (!qualifiesForScoreWiring(type, config, options)) return { config, options, wired: false };\n if (isWiredToVariable(options, variable.key)) return { config, options, wired: false };\n return {\n // A Set marker stays as it is: the Score points ride the entries alone.\n config: config?.save_to != null ? config : { ...config, save_to: { variable_id: variable.id, op: 'add' } },\n options: options.map((o) =>\n o.score != null && o.score !== 0 ? { ...o, scores: { ...(o.scores ?? {}), [variable.key]: o.score } } : o,\n ),\n wired: true,\n };\n}\n\n/** True when some option carries a points entry for the variable KEY (#5805: that is what \"wired\" means). */\nexport function isWiredToVariable(options, key) {\n return asArray(options).some((o) => typeof o?.scores?.[key] === 'number');\n}\n\n// A stored value is points only when the node ADDS to a variable (a number, non-zero): under op set\n// (or text values, or no save_to) the values are labels or targets, never points.\nfunction carriesPoints(o, addsValues, variables) {\n if (!o) return false;\n if (o.score != null && o.score !== 0) return true;\n if (Object.values(optionPoints(o, variables)).some((n) => n !== 0)) return true;\n return addsValues && typeof o.value === 'number' && o.value !== 0;\n}\n\n/**\n * What kind of scored question a choice node is (#5764), the one rule behind the builder's\n * Points field, the tick and the per-option inputs:\n * - 'multi_select': several picks; no ticks, the answer key is paused.\n * - 'right_answer': at least one tick and every unticked option has no points. One Points\n * number (see choicePoints) covers the ticked options.\n * - 'points_per_answer': anything else carrying points (a mixed legacy node, or no tick with scores,\n * or values on a node that adds to a variable; text and op set values are not points). Keeps per-option inputs; the tick is off when nothing is ticked.\n * - 'unscored': no tick, no points, no values yet. A first tick makes it 'right_answer'.\n */\nexport function choiceQuestionKind(config, options, variables) {\n if (config?.selection_mode === 'multiple') return 'multi_select';\n const list = asArray(options);\n const ticked = list.filter((o) => o?.is_correct === true);\n if (ticked.length > 0) {\n const stray = list.some(\n (o) => o?.is_correct !== true && ((o?.score != null && o.score !== 0) || Object.values(optionPoints(o, variables)).some((n) => n !== 0)),\n );\n return stray ? 'points_per_answer' : 'right_answer';\n }\n const addsValues = config?.save_to?.op === 'add';\n return list.some((o) => carriesPoints(o, addsValues, variables)) ? 'points_per_answer' : 'unscored';\n}\n\n/**\n * The Points N of a right-answer question (#5764): the top ticked score, else\n * `config.points`, else 1. Read from the data so the field never drifts.\n */\nexport function choicePoints(config, options) {\n // Clamped to 0..CHOICE_POINTS_MAX: the stepper can't commit more, so it must never show more.\n const clamp = (n) => Math.min(CHOICE_POINTS_MAX, Math.max(0, n));\n const scores = asArray(options)\n .filter((o) => o?.is_correct === true && Number.isInteger(o.score))\n .map((o) => clamp(o.score));\n if (scores.length > 0) return Math.max(...scores);\n return Number.isInteger(config?.points) ? clamp(config.points) : 1;\n}\n","// @vid-master/config/node-types\n// Static node type definitions — single source of truth for all apps.\n// New node types require code changes (new component, renderer, etc.),\n// so this data is version-controlled rather than stored in the database.\n\nimport { FEATURES, companyHasNodeType } from './features.js';\nimport { DRAW_PRESETS } from './draw-presets.js';\nimport { CHOICE_POINTS_MAX } from './variables.js';\n\n// Canonical answer-format and consent enums (single source of truth). The node\n// schemas below reference these, and all apps import them, so they cannot drift.\nexport const RESPONSE_FORMATS = ['text', 'audio', 'video'];\nexport const CONSENT_TYPES = ['consent', 'opt_in'];\n// Choice option caps (#5411). List display takes up to CHOICE_MAX_OPTIONS; the A/B/C\n// letter chips share one row, so Letters display stays at CHOICE_MAX_LETTERS_OPTIONS.\n// Every other option-count literal (pick limit, response schema, builder, viewer,\n// API, MCP) derives from `choice.max_options` / `choice.max_letters_options`.\nexport const CHOICE_MAX_OPTIONS = 12;\nexport const CHOICE_MAX_LETTERS_OPTIONS = 6;\n// One option's text: about three lines on a phone. The row grows and the list scrolls.\nexport const CHOICE_MAX_OPTION_LENGTH = 80;\nexport const CONTACT_FIELD_TYPES = ['text', 'textarea', 'email', 'tel', 'url', 'date', 'number'];\n\n// Opinionated default tier bands for the draw node's optional match-to-shape\n// game (#2148) - a builder-authored target scores the respondent's drawing on\n// submit. Shipped as the config default (`config_schema.properties.game.\n// properties.tiers.default` below) so a node with a target but no custom tiers\n// still gets a sensible 5-band scale; the viewer's scorer (apps/viewer/lib/\n// matchShape.ts) falls back to this same list when `config.game.tiers` is\n// absent. No tier-editing UI in v1 (see the issue's Future section).\nexport const DRAW_GAME_DEFAULT_TIERS = [\n { min_score: 0, label: 'Scribble' },\n { min_score: 35, label: 'Warming up' },\n { min_score: 55, label: 'Nice try' },\n { min_score: 75, label: 'Great match' },\n { min_score: 92, label: 'Perfect' },\n];\n\n// Draw paper + ink (#5076). Pure so the builder and the viewer share one rule:\n// the first stock pen colour is \"ink\" and follows the paper, so a default pen\n// is always legible (dark ink on light paper, white ink on a chalkboard).\nconst DRAW_INK_ON_LIGHT = '#1F2937';\nconst DRAW_INK_ON_DARK = '#FFFFFF';\n\n/** True when the paper's relative luminance (WCAG) is below 0.5. Unparseable input counts as light. */\nexport function isDarkPaper(hex) {\n const m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(String(hex ?? '').trim());\n if (!m) return false;\n const h = m[1].length === 3 ? m[1].replace(/./g, (c) => c + c) : m[1];\n const lin = [0, 2, 4].map((i) => {\n const v = parseInt(h.slice(i, i + 2), 16) / 255;\n return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);\n });\n return 0.2126 * lin[0] + 0.7152 * lin[1] + 0.0722 * lin[2] < 0.5;\n}\n\n/** The pen colour that reads on this paper: white on dark paper, the stock dark ink otherwise. */\nexport function inkFor(paper) {\n return isDarkPaper(paper) ? DRAW_INK_ON_DARK : DRAW_INK_ON_LIGHT;\n}\n\n// Default number of seconds a video-backed node's answer options stay hidden\n// before revealing (#2794). Lives on `node_media.options_reveal_seconds`\n// (real, nullable) - null means \"use this default\", 0 means \"reveal\n// immediately\". Single source of truth for the viewer's RevealGate default\n// and the builder's placeholder/hint when the node has no stored value.\nexport const DEFAULT_OPTIONS_REVEAL_SECONDS = 3;\n\n// Default cap (seconds) on an open node's audio/video recorder (#2838).\n// Lives on `node.config.max_recording_seconds` (JSONB, not the media asset -\n// an open node can collect a video answer with no media asset attached).\n// Single source of truth for the viewer recorder's `maxDuration` fallback\n// and the builder's placeholder/hint when the node has no stored value.\nexport const DEFAULT_MAX_RECORDING_SECONDS = 120;\n\n// Bounds for `max_recording_seconds` - used directly as the config_schema's\n// minimum/maximum below AND exported so the builder's stepper (OpenNode.tsx)\n// clamps to the exact same numbers instead of a hardcoded local copy that\n// could drift from the schema. No unlimited/0 escape hatch (floor of 10).\nexport const MAX_RECORDING_SECONDS_MIN = 10;\n\n// 300 (restored from 180, #4023; was 300 before #4014 lowered it): at the\n// 720p/1.5Mbps recorder caps, 300s runs well under the now-200 MiB Supabase\n// storage ceiling (SUPABASE_STORAGE_MAX_BYTES), so the tighter #4014 cap is\n// no longer needed. The viewer clamps existing nodes storing a higher value\n// down to this at read time - no data migration.\nexport const MAX_RECORDING_SECONDS_MAX = 300;\n\n/**\n * The noun a camera node's cap/min copy uses for a capture, from what the node\n * accepts: photo(s), video(s), or item(s) when both (or neither) are allowed.\n * Shared by the viewer's errors and the builder's \"Number of <noun>\" row so the\n * two never drift. Library never changes the noun.\n */\nexport function cameraCaptureUnit(allowedCapture, count) {\n const types = Array.isArray(allowedCapture) ? allowedCapture : [];\n const photo = types.includes('photo');\n const video = types.includes('video');\n const plural = count !== 1;\n if (photo && !video) return plural ? 'photos' : 'photo';\n if (video && !photo) return plural ? 'videos' : 'video';\n return plural ? 'items' : 'item';\n}\n\n/**\n * The capture buttons a camera node offers, and what each accepts. Camera\n * buttons come from `camera_capture` (absent = `allowed_capture`, so existing\n * nodes are unchanged); the library button from `allow_library_upload`,\n * accepting `allowed_capture`. `types` is everything a respondent can submit\n * (upload validation, \"photos\" / \"videos\" / \"items\" copy). Shared by the\n * builder and the viewer so the two can't disagree.\n */\nexport function cameraCaptureSources(config) {\n const libraryTypes = Array.isArray(config?.allowed_capture) && config.allowed_capture.length ? config.allowed_capture : ['photo'];\n const camera = Array.isArray(config?.camera_capture) ? config.camera_capture : libraryTypes;\n const photo = camera.includes('photo');\n const video = camera.includes('video');\n const library = config?.allow_library_upload !== false;\n const types = ['photo', 'video'].filter(\n (t) => (t === 'photo' ? photo : video) || (library && libraryTypes.includes(t))\n );\n return { photo, video, library, libraryTypes, types };\n}\n\n/**\n * The display order of a camera node's capture buttons. A saved `capture_order`\n * is trusted only when it is a full permutation of photo/video/library; a\n * missing, partial, duplicated or unknown-key value is the default order.\n * Shared by the builder tiles and the viewer so the rule can't drift.\n */\nexport function resolveCameraCaptureOrder(captureOrder) {\n const fallback = ['photo', 'video', 'library'];\n if (\n Array.isArray(captureOrder) &&\n captureOrder.length === fallback.length &&\n fallback.every((k) => captureOrder.includes(k))\n ) {\n return [...captureOrder];\n }\n return fallback;\n}\n\n// Booking result: response_schema (what the viewer submits) and output_schema\n// (the webhook payload) share one shape. Only provider + status are required:\n// the viewer knows just the provider URIs until the server-side confirm (#5303)\n// fills in the times / links.\nconst BOOKING_PROVIDERS = ['calendly', 'google_meet'];\n\n/** Weekday keys of a Google Meet booking's `availability.weekly_hours`, Monday first. */\nexport const BOOKING_WEEKDAYS = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];\n\nconst WORKDAY_HOURS = [{ start: '09:00', end: '17:00' }];\n\n/**\n * Google Meet booking defaults (#5308/#5309). The builder asks only for the\n * meeting length, the weekly hours and the gap between meetings (#5856);\n * notice and window are fixed, and the timezone is the owner's Google\n * Calendar timezone, read at request time.\n */\nexport const GOOGLE_MEET_BOOKING_DEFAULTS = Object.freeze({\n calendar_id: 'primary',\n duration: 30,\n weekly_hours: Object.freeze({\n mon: WORKDAY_HOURS, tue: WORKDAY_HOURS, wed: WORKDAY_HOURS, thu: WORKDAY_HOURS, fri: WORKDAY_HOURS,\n sat: [], sun: [],\n }),\n buffer_minutes: 0,\n min_notice_minutes: 240,\n days_ahead: 14,\n});\n\nconst BOOKING_RESULT_SCHEMA = {\n type: 'object',\n required: ['provider', 'status'],\n properties: {\n provider: { type: 'string', enum: BOOKING_PROVIDERS },\n status: { type: 'string', enum: ['booked', 'skipped'] },\n start_time: { type: 'string', format: 'date-time' },\n end_time: { type: 'string', format: 'date-time' },\n timezone: { type: 'string' },\n join_url: { type: 'string' },\n reschedule_url: { type: 'string' },\n cancel_url: { type: 'string' },\n invitee: {\n type: 'object',\n properties: {\n name: { type: 'string' },\n email: { type: 'string' },\n },\n },\n provider_ids: {\n type: 'object',\n properties: {\n event_uri: { type: 'string' },\n invitee_uri: { type: 'string' },\n event_id: { type: 'string' },\n calendar_id: { type: 'string' },\n },\n },\n },\n description: 'Booking result',\n};\n\n// Webhook output: the flat result plus node_type, like every sibling output_schema.\nconst BOOKING_OUTPUT_SCHEMA = {\n ...BOOKING_RESULT_SCHEMA,\n required: ['node_type', ...BOOKING_RESULT_SCHEMA.required],\n properties: {\n node_type: { type: 'string', const: 'booking' },\n ...BOOKING_RESULT_SCHEMA.properties,\n },\n};\n\nexport const NODE_TYPES = {\n start: {\n label: 'Start',\n shorthand: 'Start',\n icon: 'ArrowRight',\n color: '#D1FAE5',\n description: 'Entry point for the form - connects to the first node',\n category: 'start',\n sort_order: 0,\n has_options: false,\n is_terminal: false,\n show_nav_bar: false,\n loading: 'eager',\n supports_prompt: false,\n supports_media: false,\n is_system: true,\n show_in_results: false,\n pii: false,\n respondent_media: null,\n // Never appears in a completed submission's answers (system node, no\n // output_schema) - false is a no-op default, set for guard-test coverage.\n notify_inline: false,\n owner_scoped_config_keys: [],\n default_config: null,\n config_schema: null,\n response_schema: null,\n output_schema: null,\n },\n choice: {\n label: 'Multiple Choice',\n shorthand: 'Multi',\n icon: 'CheckSquare',\n color: '#DBEAFE',\n description: 'Single or multiple choice node with predefined options',\n category: 'input',\n sort_order: 1,\n has_options: true,\n min_options: 1,\n max_options: CHOICE_MAX_OPTIONS,\n // Letters display (A/B/C chips on one row) stops here; List takes the full max_options.\n max_letters_options: CHOICE_MAX_LETTERS_OPTIONS,\n max_option_length: CHOICE_MAX_OPTION_LENGTH,\n is_terminal: false,\n show_nav_bar: true,\n loading: 'eager',\n supports_prompt: true,\n supports_media: true,\n is_system: false,\n show_in_results: true,\n pii: false,\n respondent_media: null,\n // Short selected-option label - safe to render inline in a notification (#4154).\n notify_inline: true,\n owner_scoped_config_keys: [],\n default_config: {\n selection_mode: 'single',\n choice: { enable_branching: false, record_scores: false },\n randomise_options: false,\n show_option_count: false,\n option_display: 'list',\n options: [\n { content: 'Option 1' },\n { content: 'Option 2' },\n ],\n },\n config_schema: {\n type: 'object',\n properties: {\n choice: {\n type: 'object',\n properties: {\n enable_branching: {\n type: 'boolean',\n label: 'Enable branching logic',\n default: true,\n description: 'Allow each option to have its own logic path. When disabled, all options share a single jump action.',\n },\n show_answer_feedback: {\n type: 'boolean',\n label: 'Show answer feedback',\n default: false,\n description: 'Show correct/incorrect feedback after selection (requires scored options).',\n },\n record_scores: {\n type: 'boolean',\n label: 'Mark correct answer',\n default: false,\n description: 'Select which option is the correct answer.',\n },\n },\n },\n selection_mode: {\n enum: ['single', 'multiple'],\n type: 'string',\n label: 'Multiple selection',\n default: 'single',\n description: 'Let respondents pick one option (single) or several (multiple). \"multiple\" is gated by the multi_select feature - while it is off, the API coerces it to \"single\" (the viewer renders single-select only).',\n },\n // Points for a correct answer (#5764). A memory for re-ticking: the live points live on the\n // ticked options' `score`; this only seeds a newly ticked option when it carries none.\n points: {\n type: 'number',\n min: 0,\n max: CHOICE_POINTS_MAX,\n default: 1,\n feature: 'variables',\n label: 'Points',\n description: `Points a correct answer is worth (a whole number from 0 to ${CHOICE_POINTS_MAX}). Applied to a ticked option that sets no score.`,\n },\n // Pick limits for multiple mode. Inert on single (kept stored, never read).\n min_selections: {\n type: 'number',\n min: 1,\n default: 1,\n feature: 'multi_select',\n label: 'Minimum picks',\n shortLabel: 'From',\n description: 'Fewest options a respondent must pick before continuing (multiple selection only)',\n },\n max_selections: {\n type: 'number',\n min: 1,\n max: CHOICE_MAX_OPTIONS,\n feature: 'multi_select',\n label: 'Limit',\n shortLabel: 'To',\n description: 'How many options a respondent can pick: any number, an exact number, or a range.',\n // Words for the builder's Limit dropdown (Unlimited / Exact / Range), shared with the docs.\n modeLabels: { unlimited: 'Unlimited', exact: 'Exact number', range: 'Range' },\n exactLabel: 'Number of picks',\n },\n allow_text_response: {\n type: 'boolean',\n label: 'Allow text response',\n default: false,\n description: 'Allow free-text response in addition to options (single choice only). Gated by the text_response feature - while it is off, the API coerces it to false (the viewer renders no free-text field yet).',\n },\n randomise_options: {\n type: 'boolean',\n label: 'Randomise options',\n default: false,\n description: 'Show options in random order',\n },\n show_option_count: {\n type: 'boolean',\n label: 'Show option count',\n default: false,\n description: 'Display number of options',\n },\n option_display: {\n enum: ['list', 'letters'],\n type: 'string',\n label: 'Option display',\n default: 'list',\n description: `How options render: full text rows (list), or compact A/B/C/D chips (letters) when the media already shows the labelled options - e.g. a Grid background. Letters allows up to ${CHOICE_MAX_LETTERS_OPTIONS} options; list allows up to ${CHOICE_MAX_OPTIONS}.`,\n },\n content_media_type: {\n enum: ['upload', 'recorded'],\n type: 'string',\n label: 'Content media type',\n description: 'How the node media was provided',\n },\n },\n },\n // Single-select = the bare option id; multi-select = a bare array of option ids\n // (#151). Readers key on the data shape, never on the node's current selection_mode.\n response_schema: {\n description: 'Selected option ID (single-select) or an array of selected option IDs (multi-select)',\n oneOf: [\n { type: 'string' },\n { type: 'array', items: { type: 'string' }, minItems: 1, maxItems: CHOICE_MAX_OPTIONS },\n ],\n },\n output_schema: {\n type: 'object',\n required: ['node_type', 'label'],\n oneOf: [\n { type: 'object', required: ['option_id'] },\n { type: 'object', required: ['labels', 'option_ids'] },\n ],\n properties: {\n node_type: { type: 'string', const: 'choice' },\n label: { type: 'string', description: 'Human-readable option label (multi-select: the picked labels joined with \", \" in option order)' },\n option_id: { type: 'string', format: 'uuid', description: 'Selected option UUID (single-select only)' },\n labels: { type: 'array', items: { type: 'string' }, description: 'Picked option labels in option order (multi-select only)' },\n option_ids: { type: 'array', items: { type: 'string', format: 'uuid' }, description: 'Picked option UUIDs in option order (multi-select only)' },\n },\n },\n },\n open: {\n label: 'Open Ended',\n shorthand: 'Open',\n icon: 'Type',\n color: '#DBEAFE',\n description: 'Free-form text responses from users',\n category: 'input',\n sort_order: 2,\n has_options: false,\n is_terminal: false,\n show_nav_bar: true,\n loading: 'eager',\n supports_prompt: true,\n supports_media: true,\n is_system: false,\n show_in_results: true,\n pii: false,\n respondent_media: 'recording',\n // True for the common short-text case; a channel notification (#4154)\n // still swaps a recorded audio/video answer for a typed placeholder\n // based on the answer's own media type, not this flag.\n notify_inline: true,\n owner_scoped_config_keys: [],\n default_config: {\n formats: [\n { order: 0, format: 'text' },\n { order: 1, format: 'audio' },\n { order: 2, format: 'video' },\n ],\n },\n config_schema: {\n type: 'object',\n properties: {\n formats: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n format: { enum: RESPONSE_FORMATS, type: 'string' },\n order: { type: 'number' },\n },\n },\n label: 'Allowed response formats',\n description: 'Which formats the user can respond with, in display order',\n },\n content_media_type: {\n enum: ['upload', 'recorded'],\n type: 'string',\n label: 'Content media type',\n description: 'How the node media was provided',\n },\n max_recording_seconds: {\n type: 'number',\n default: DEFAULT_MAX_RECORDING_SECONDS,\n minimum: MAX_RECORDING_SECONDS_MIN,\n maximum: MAX_RECORDING_SECONDS_MAX,\n label: 'Max recording length (seconds)',\n description: 'Cap on the audio/video recorder for this node, in seconds',\n },\n },\n },\n response_schema: {\n type: 'object',\n required: ['response_type'],\n properties: {\n text: {\n type: 'string',\n description: 'Text response (when response_type is text) or transcribed text from audio/video',\n },\n media: {\n type: 'object',\n properties: {\n type: { enum: ['audio', 'video'], type: 'string' },\n storage_path: { type: 'string' },\n original_storage_path: { type: 'string' },\n thumbnail_storage_path: { type: 'string' },\n mp3_storage_path: { type: 'string' },\n duration_s: { type: 'number' },\n // Pixel size of the final stored video, written by the processor (#5125). Video only.\n width: { type: 'number' },\n height: { type: 'number' },\n processed_at: { type: 'string' },\n // Processor-stamped: is the saved video mirrored (#5021)? Absent = legacy.\n saved_mirrored: { type: 'boolean' },\n facing_mode: { enum: ['user', 'environment'], type: 'string' },\n preview_crop: {\n type: 'object',\n properties: {\n stream_width: { type: 'number' },\n stream_height: { type: 'number' },\n preview_width: { type: 'number' },\n preview_height: { type: 'number' },\n },\n },\n },\n description: 'Media response (when response_type is audio or video)',\n },\n response_type: {\n enum: RESPONSE_FORMATS,\n type: 'string',\n },\n transcription: {\n type: 'object',\n properties: {\n text: { type: 'string' },\n language: { type: 'string' },\n duration: { type: 'number' },\n words: { type: 'array' },\n },\n description: 'Whisper transcription data for audio/video responses',\n },\n },\n },\n output_schema: {\n type: 'object',\n required: ['node_type'],\n properties: {\n node_type: { type: 'string', const: 'open' },\n text: { type: 'string', description: 'Text response or transcription' },\n media: {\n type: 'object',\n properties: {\n type: { enum: ['audio', 'video'], type: 'string' },\n content_type: { type: 'string', description: 'MIME type of the recording (e.g. audio/webm, video/mp4)' },\n filename: { type: 'string', description: 'Suggested download filename' },\n // Direct, time-limited signed URL to the recording (~48h, supports\n // HTTP range); minted per delivery, never the internal storage path.\n url: { type: 'string', format: 'uri' },\n download_url: { type: 'string', format: 'uri', description: 'Same link with a forced download (Content-Disposition: attachment)' },\n expires_at: { type: 'string', format: 'date-time', description: 'When url/download_url stop working' },\n },\n },\n transcription: {\n type: 'object',\n properties: {\n text: { type: 'string' },\n language: { type: 'string' },\n segments: {\n type: 'array',\n description: 'Timestamped segments (seconds) for captions/seeking.',\n items: {\n type: 'object',\n properties: {\n start: { type: 'number' },\n end: { type: 'number' },\n text: { type: 'string' },\n },\n },\n },\n },\n },\n },\n },\n },\n scale: {\n label: 'Scale',\n shorthand: 'Scale',\n icon: 'BarChart3',\n color: '#DBEAFE',\n description: 'Numerical rating or scale node (1-10, etc.)',\n category: 'input',\n sort_order: 3,\n has_options: false,\n is_terminal: false,\n show_nav_bar: true,\n loading: 'eager',\n supports_prompt: true,\n supports_media: true,\n is_system: false,\n show_in_results: true,\n pii: false,\n respondent_media: null,\n // A bare numeric value - short enough to render inline (#4154).\n notify_inline: true,\n owner_scoped_config_keys: [],\n default_config: null,\n config_schema: {\n type: 'object',\n properties: {\n max: { type: 'number', label: 'Maximum value', default: 10, required: true },\n min: { type: 'number', label: 'Minimum value', default: 1, required: true },\n step: { min: 0.1, type: 'number', label: 'Step increment', default: 1 },\n left_label: { type: 'string', label: 'Left label', placeholder: 'Not likely' },\n right_label: { type: 'string', label: 'Right label', placeholder: 'Very likely' },\n show_numbers: { type: 'boolean', label: 'Show numbers', default: true },\n },\n },\n response_schema: {\n type: 'number',\n description: 'Selected scale value',\n },\n output_schema: null,\n },\n booking: {\n label: 'Booking',\n shorthand: 'Booking',\n icon: 'Calendar',\n color: '#E9D5FF',\n description: 'Let respondents book a meeting on a connected Calendly account without leaving the form',\n category: 'action',\n sort_order: 8,\n has_options: false,\n is_terminal: false,\n show_nav_bar: true,\n loading: 'lazy',\n // Like Payment: no generic prompt; the heading + description are config title/description\n // (NodeHeadingFields in the builder, shown above the scheduler in the viewer).\n supports_prompt: false,\n supports_media: false,\n // The interaction takes the stage height under the heading + description (an inline embed).\n interaction_fills_stage: true,\n is_system: false,\n show_in_results: true,\n // Invitee name/email plus cancel/reschedule URLs (BOOKING_RESULT_SCHEMA).\n pii: true,\n respondent_media: null,\n // Structured provider data, but notifications render a one-line \"Booked for\n // <time> (<name>)\" from it (bookingAnswerDisplay), not a placeholder (#5306).\n notify_inline: true,\n // Object granularity, not a dotted path (#4618): every property under\n // these provider objects (scheduling_url, event_type_uri, calendar_id) is\n // the source workspace's own calendar, so save_form strips the whole\n // object on cross-workspace copy. workspace_integration_id is the top-level\n // connected-account pointer (Payment's convention). `calcom` is a dead key\n // (Cal.com support was removed, #5311) kept on purpose: save_form is SQL and\n // owner-scoped-config-keys.test.js binds the union of flat keys to the latest\n // save_form migration's strip array, so dropping it would force a migration.\n owner_scoped_config_keys: ['workspace_integration_id', 'calendly', 'calcom', 'google_meet'],\n // The viewer iframes calendly scheduling_url (booking/CalendlyScheduler.tsx): an outbound embed.\n // Unclaimed anonymous-MCP forms may not go live with this node (#4847).\n blocked_for_anon_mcp: true,\n default_config: null,\n config_schema: {\n type: 'object',\n properties: {\n // google_meet ships dark until integration_google_calendar is live (#5310).\n provider: { type: 'string', enum: BOOKING_PROVIDERS, enum_features: { google_meet: 'integration_google_calendar' }, label: 'Provider', description: 'Scheduling provider (one per node)' },\n workspace_integration_id: { type: 'string', description: 'Connected workspace integration (calendar account) this booking uses' },\n title: { type: 'string', label: 'Heading', maxLength: 80, description: 'Heading shown above the scheduler', anon_locked_keep: true },\n description: { type: 'string', label: 'Description', maxLength: 140, description: 'Body text shown below the heading', anon_locked_keep: true },\n allow_skip: { type: 'boolean', feature: 'optional_questions', default: false, label: 'Optional', description: 'Let respondents continue without booking' },\n calendly: {\n type: 'object',\n properties: {\n event_type_uri: { type: 'string', label: 'Event type URI', description: 'Your Calendly event type URI' },\n event_name: { type: 'string', label: 'Event name', description: 'Display name for the event' },\n scheduling_url: { type: 'string', label: 'Scheduling URL', description: 'Calendly scheduling link embedded in the form' },\n duration: { type: 'number', label: 'Duration (minutes)', description: 'Event duration in minutes' },\n },\n },\n google_meet: {\n type: 'object',\n feature: 'integration_google_calendar',\n properties: {\n // 'primary' (the owner's main calendar, Andy 2026-11-11): bookings must block the calendar other tools check.\n calendar_id: { type: 'string', label: 'Calendar', default: 'primary', description: 'Google Calendar to use for bookings' },\n calendar_name: { type: 'string', label: 'Calendar name', description: 'Display name for the selected calendar' },\n duration: { type: 'number', label: 'Duration (minutes)', default: 30, minimum: 15, maximum: 240, description: 'Meeting duration in minutes' },\n event_title: { type: 'string', label: 'Event title', maxLength: 80, description: 'Calendar event title; the form title when unset' },\n // Kept free on both sides of every busy event in the calendar, not just bookings (#5856).\n buffer_minutes: { type: 'number', label: 'Gap between meetings (minutes)', default: 0, minimum: 0, maximum: 60, description: 'Minutes kept free before and after every busy event in the calendar' },\n // Notice (4h), window (14 days) and timezone (the owner's calendar) are fixed:\n // GOOGLE_MEET_BOOKING_DEFAULTS, scope change on #5309 (2026-10-29).\n availability: {\n type: 'object',\n properties: {\n // Keyed mon..sun; each value is an array of { start, end } 'HH:MM' strings,\n // in the owner's Google Calendar timezone.\n weekly_hours: { type: 'object', description: 'Bookable hours per weekday (mon..sun), each an array of { start, end } HH:MM ranges in the calendar timezone' },\n },\n },\n },\n },\n },\n description: 'Booking provider configuration (one provider per node)',\n },\n response_schema: BOOKING_RESULT_SCHEMA,\n output_schema: BOOKING_OUTPUT_SCHEMA,\n },\n details: {\n label: 'Details',\n shorthand: 'Details',\n icon: 'User',\n color: '#ECFCCB',\n description: 'Collect several fields on one screen - name, email, phone, address, date, and more',\n category: 'input',\n sort_order: 4,\n has_options: false,\n is_terminal: false,\n show_nav_bar: true,\n loading: 'lazy',\n supports_prompt: false,\n supports_media: false,\n is_system: false,\n show_in_results: false,\n pii: true,\n respondent_media: null,\n // Excluded from the aggregate Results charts (a list of emails can't be\n // charted) but DOES show in the per-response Responses table, where each\n // lead's contact fields are actionable (#746).\n show_in_responses: true,\n // Key contact fields (first name, email) are the whole point of a\n // notification for this node type - always inline (#4154).\n notify_inline: true,\n owner_scoped_config_keys: [],\n default_config: {\n fields: [\n { id: 'first_name', required: true },\n { id: 'email', required: true },\n ],\n // No agreement out of the box - the builder adds one via \"Add agreement\"\n // when they actually need consent, so a fresh node ships no orphan checkbox. (#1378)\n consent_items: [],\n },\n config_schema: {\n type: 'object',\n required: ['fields'],\n properties: {\n title: { type: 'string' },\n fields: {\n type: 'array',\n minItems: 1,\n items: {\n type: 'object',\n required: ['id', 'required'],\n properties: {\n id: { type: 'string' },\n type: { enum: CONTACT_FIELD_TYPES, type: 'string' },\n label: { type: 'string' },\n order: { type: 'number' },\n required: { type: 'boolean', default: true },\n is_custom: { type: 'boolean', default: false },\n },\n },\n },\n description: { type: 'string' },\n consent_items: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n id: { type: 'string' },\n name: { type: 'string' },\n label: { type: 'string' },\n order: { type: 'number' },\n type: { type: 'string', enum: CONSENT_TYPES },\n // Optional attached agreement document (PDF only in v1, #2760). Served\n // from the public node-media bucket; `version` bumps on file replace.\n // anon_locked_file: an outside file on a guest live form (#4847), stripped from the\n // payload so the item renders as a plain consent checkbox.\n document: {\n type: 'object',\n anon_locked_file: true,\n properties: {\n storage_path: { type: 'string' },\n filename: { type: 'string' },\n url: { type: 'string' },\n version: { type: 'string' },\n },\n },\n // When true, the consent checkbox stays disabled until the respondent\n // scrolls the attached document to the end (scrollwrap gating, #2760).\n require_scroll_to_accept: { type: 'boolean' },\n },\n },\n },\n },\n },\n response_schema: {\n type: 'object',\n required: ['fields'],\n properties: {\n fields: {\n type: 'array',\n items: {\n type: 'object',\n required: ['id', 'type', 'label', 'value'],\n properties: {\n id: { type: 'string' },\n type: { type: 'string' },\n label: { type: 'string' },\n value: { type: 'string' },\n },\n },\n description: 'Contact form field entries with metadata',\n },\n consent: {\n type: 'array',\n items: {\n type: 'object',\n required: ['id', 'name', 'label', 'accepted', 'type'],\n properties: {\n id: { type: 'string' },\n name: { type: 'string' },\n label: { type: 'string' },\n accepted: { type: 'boolean' },\n type: { type: 'string', enum: CONSENT_TYPES },\n // Scrollwrap audit trail (#2760), present only for document-gated\n // consent items: whether they scrolled to the end, the exact\n // document version they saw, and when they accepted.\n reached_end: { type: 'boolean' },\n document_version: { type: 'string' },\n accepted_at: { type: 'string' },\n // Server-stamped on write (#4552) when the node's current document\n // matches document_version; any client-supplied value is discarded.\n document: {\n type: 'object',\n properties: {\n storage_path: { type: 'string' },\n url: { type: 'string' },\n filename: { type: 'string' },\n },\n },\n },\n },\n description: 'Consent checkbox entries',\n },\n },\n },\n output_schema: {\n type: 'object',\n required: ['node_type', 'fields'],\n properties: {\n node_type: { type: 'string', const: 'details' },\n fields: {\n type: 'array',\n items: {\n type: 'object',\n required: ['type', 'value'],\n properties: {\n type: { type: 'string' },\n value: { type: 'string' },\n },\n },\n },\n // Consent/opt-in agreements the respondent was shown. Present only when\n // the node has consent items. `accepted` is their choice; `label` is the\n // exact wording they agreed to, snapshotted per response (#2828).\n consent: {\n type: 'array',\n items: {\n type: 'object',\n required: ['name', 'accepted', 'type', 'label'],\n properties: {\n name: { type: 'string' },\n accepted: { type: 'boolean' },\n type: { type: 'string', enum: CONSENT_TYPES },\n label: { type: 'string' },\n // Scrollwrap audit trail (#2760), emitted only for document-gated items.\n reached_end: { type: 'boolean' },\n document_version: { type: 'string' },\n accepted_at: { type: 'string' },\n // The exact agreement file accepted (#4552). storage_path is not emitted.\n document: {\n type: 'object',\n properties: {\n url: { type: 'string' },\n filename: { type: 'string' },\n },\n },\n },\n },\n },\n },\n },\n },\n file_upload: {\n label: 'File Upload',\n shorthand: 'Upload',\n icon: 'Upload',\n color: '#ECFCCB',\n description: 'Collect file uploads from respondents',\n category: 'input',\n sort_order: 5,\n has_options: false,\n is_terminal: false,\n show_nav_bar: true,\n loading: 'lazy',\n supports_prompt: false,\n supports_media: false,\n is_system: false,\n show_in_results: true,\n pii: false,\n respondent_media: 'files',\n // Files, not a flat value - a notification renders a typed placeholder (#4154).\n notify_inline: false,\n owner_scoped_config_keys: [],\n // Unclaimed anonymous-MCP forms may not go live with this node (#4847; derived into ANON_MCP_BLOCKED_NODE_TYPES).\n blocked_for_anon_mcp: true,\n default_config: null,\n config_schema: {\n type: 'object',\n properties: {\n max_files: { max: 20, min: 1, type: 'number', label: 'Max files', default: 5, description: 'Maximum number of files respondents can upload' },\n // Capped at 50, not 500: respondent file uploads go straight to the Supabase\n // `file-uploads` bucket, and SUPABASE_STORAGE_MAX_BYTES is a hard ceiling there.\n // Anything above it passed validation and then 500'd at the storage layer (#2556).\n max_file_size_mb: { max: 50, min: 1, type: 'number', label: 'Max file size (MB)', default: 50, description: 'Maximum size per file (1-50 MB)' },\n allowed_media_types: {\n type: 'array',\n items: { enum: ['images', 'videos', 'documents', 'all'], type: 'string' },\n label: 'Allowed media types',\n default: ['images', 'documents'],\n enumLabels: {\n all: 'All file types',\n images: 'Images (JPEG, PNG, GIF, WebP, HEIC)',\n videos: 'Videos (MP4, MOV, WebM, AVI)',\n documents: 'Documents (PDF, DOC, DOCX, XLS, XLSX, TXT, CSV)',\n },\n description: 'Select which types of files respondents can upload',\n },\n },\n },\n response_schema: {\n type: 'object',\n required: ['files'],\n properties: {\n files: {\n type: 'array',\n items: {\n type: 'object',\n required: ['id', 'name', 'storage_path', 'url', 'mime_type', 'size', 'uploaded_at'],\n properties: {\n id: { type: 'string', format: 'uuid', description: 'Unique file identifier' },\n url: { type: 'string', format: 'uri', description: 'Signed Supabase Storage URL for download' },\n name: { type: 'string', description: 'Original filename' },\n size: { type: 'integer', minimum: 1, description: 'File size in bytes' },\n mime_type: { type: 'string', description: 'File MIME type' },\n uploaded_at: { type: 'string', format: 'date-time', description: 'ISO timestamp of upload completion' },\n storage_path: { type: 'string', description: 'Full storage path: workspace_id/form_id/node_id/uuid.ext' },\n width: { type: 'number', description: 'Displayed pixel width (EXIF applied), when the browser could read it (#5125)' },\n height: { type: 'number', description: 'Displayed pixel height (EXIF applied), when the browser could read it (#5125)' },\n duration: { type: 'number', description: 'Duration in seconds for video and audio files, when readable (#5125)' },\n },\n },\n minItems: 1,\n description: 'Array of uploaded file metadata',\n },\n },\n },\n output_schema: {\n type: 'object',\n required: ['node_type'],\n properties: {\n node_type: { type: 'string', const: 'file_upload' },\n files: {\n type: 'array',\n description: 'The uploaded files, each a canonical media object with a fresh signed link.',\n items: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Unique file identifier' },\n filename: { type: 'string', description: 'Original filename' },\n content_type: { type: 'string', description: 'File MIME type' },\n size: { type: 'integer', description: 'File size in bytes' },\n uploaded_at: { type: 'string', format: 'date-time', description: 'ISO timestamp of upload completion' },\n url: { type: 'string', format: 'uri', description: 'Direct, time-limited signed link (~48h, supports HTTP range)' },\n download_url: { type: 'string', format: 'uri', description: 'Same link with a forced download (Content-Disposition: attachment)' },\n expires_at: { type: 'string', format: 'date-time', description: 'When url/download_url stop working' },\n },\n },\n },\n },\n },\n },\n draw: {\n label: 'Drawing',\n shorthand: 'Draw',\n icon: 'Pencil',\n color: '#ECFCCB',\n description: 'Drawing canvas; respondents draw and it is saved as a PNG image',\n category: 'input',\n sort_order: 7,\n has_options: false,\n is_terminal: false,\n show_nav_bar: true,\n loading: 'lazy',\n supports_prompt: false,\n supports_media: true,\n is_system: false,\n show_in_results: true,\n pii: false,\n respondent_media: 'drawing',\n // An image, not a flat value - a notification renders a typed placeholder (#4154).\n notify_inline: false,\n owner_scoped_config_keys: [],\n // Per-type node_media presentation default for a NEW placement (attach /\n // upload routes apply it). The reference image is shown whole, not cropped\n // (#5076); the viewer reads node_media.fit_media like every other media node.\n media_defaults: { fit_media: true },\n default_config: {\n paper_color: '#FAF9F6',\n stroke_colors: ['#1F2937', '#EF4444', '#3B82F6', '#22C55E', '#FACC15'],\n stroke_widths: [3, 6, 12],\n diagram: { opacity: 1, scale: 1 },\n },\n config_schema: {\n type: 'object',\n properties: {\n title: { type: 'string', label: 'Heading', maxLength: 80, description: 'Heading shown above the drawing canvas' },\n description: { type: 'string', label: 'Description', maxLength: 140, description: 'Body text shown below the heading' },\n paper_color: {\n type: 'string',\n label: 'Paper',\n default: '#FAF9F6',\n // The builder offers these as single-select chips; any hex set via the API still renders.\n presets: ['#FAF9F6', '#FFFFFF', '#1E293B'],\n optionLabels: { '#FAF9F6': 'Off-white', '#FFFFFF': 'White', '#1E293B': 'Chalkboard' },\n description: 'Canvas background colour (off-white paper by default). The first stock pen colour (ink) follows it: white on dark paper.',\n },\n stroke_colors: {\n type: 'array',\n items: { type: 'string' },\n minItems: 1,\n maxItems: 8,\n label: 'Pen colours',\n // Chip names in the builder (and any picker); unknown values fall back to the hex.\n // The stock first chip (the one equal to inkFor(paper)) is named `inkLabel` instead, so a\n // group's chip names stay unique (a white pen on light paper is \"White\", not \"Ink\").\n inkLabel: 'Ink',\n optionLabels: { '#1F2937': 'Black', '#FFFFFF': 'White', '#EF4444': 'Red', '#3B82F6': 'Blue', '#22C55E': 'Green', '#FACC15': 'Yellow' },\n default: ['#1F2937', '#EF4444', '#3B82F6', '#22C55E', '#FACC15'],\n description: 'Colour swatches the respondent can draw with. The first entry is the default selection; a single entry locks the pen to that colour and hides the picker.',\n },\n stroke_widths: {\n type: 'array',\n items: { type: 'number', minimum: 1, maximum: 60 },\n minItems: 1,\n maxItems: 5,\n label: 'Pen thickness',\n // Keyed by width in px; unknown widths fall back to `${w}px`.\n optionLabels: { 3: 'Thin', 6: 'Medium', 12: 'Thick' },\n default: [3, 6, 12],\n description: 'Stroke widths (px) the respondent can choose. The middle entry is the default selection; a single entry locks the pen to that width and hides the picker.',\n },\n // The reference image is EITHER a built-in outline (`preset`, below: a static image\n // referenced by name, #5263) OR the node's attached media (media_id,\n // via the same media_asset/create-media.ts pipeline every other\n // supports_media node uses) - not a config field, to avoid a\n // duplicated asset ref. This only tunes its display/bake.\n diagram: {\n type: 'object',\n label: 'Diagram',\n description: 'Display settings for the optional diagram the respondent draws on (a body, vehicle or your own image)',\n properties: {\n // Fit + position (uploaded image only) live on the node_media placement (fit_media / position_x), shared with every media node.\n opacity: { type: 'number', minimum: 0, maximum: 1, default: 1, label: 'Opacity', description: 'Diagram opacity, from 0 (invisible) to 1 (fully opaque)' },\n scale: { type: 'number', minimum: 0.5, maximum: 1, default: 1, label: 'Size', description: 'Diagram size as a fraction of its fitted size. Applies only when the diagram is fitted (fit_media true).' },\n // A built-in outline (#5263): a static image served by the viewer, referenced by name. Not a media asset - no placement. Wins over an attached image; always shown whole and centred.\n preset: { type: 'string', enum: DRAW_PRESETS.map((p) => p.id), label: 'Built-in diagram', description: 'Use a ready-made outline instead of an uploaded image: ' + DRAW_PRESETS.map((p) => `${p.id} (${p.label})`).join(', ') + '. Shown whole and centred, so fit/position do not apply. Shown instead of any attached image while set; unset it to use the attached image of the node.' },\n },\n },\n // Optional match-to-shape game (#2148). Absent entirely by default\n // (not in default_config) - a node with no `game.target` behaves\n // exactly as it did before this key existed. `target.points` is\n // authored once in the builder (a simplified sketch modal, see\n // apps/dashboard) and stored pre-normalized to a [0,1] unit box so the\n // viewer's scorer (apps/viewer/lib/matchShape.ts) and the reveal\n // overlay share the same coordinate frame without re-deriving it.\n game: {\n type: 'object',\n feature: 'draw_target_shape',\n label: 'Match-to-shape game',\n description: 'Optional target shape the drawing is scored against on submit',\n properties: {\n target: {\n type: 'object',\n label: 'Target shape',\n description: 'The outline the respondent is scored against, drawn once by the form builder',\n properties: {\n points: {\n type: 'array',\n minItems: 2,\n maxItems: 500,\n items: {\n type: 'object',\n properties: {\n x: { type: 'number', minimum: 0, maximum: 1 },\n y: { type: 'number', minimum: 0, maximum: 1 },\n },\n },\n description: 'Closed polyline outline, normalized to a [0,1] unit box (aspect-preserving)',\n },\n },\n },\n tiers: {\n type: 'array',\n label: 'Score tiers',\n minItems: 1,\n maxItems: 10,\n items: {\n type: 'object',\n properties: {\n min_score: { type: 'number', minimum: 0, maximum: 100 },\n label: { type: 'string' },\n },\n },\n default: DRAW_GAME_DEFAULT_TIERS,\n description: 'Score bands shown in the reveal, ascending by min_score - defaults to a 5-band Scribble to Perfect scale',\n },\n },\n },\n allow_skip: {\n type: 'boolean',\n feature: 'optional_questions',\n default: false,\n label: 'Optional',\n description: 'Respondents can skip this question without drawing',\n },\n },\n },\n response_schema: {\n // Mirrors the live `open` node's media response shape (the only complete\n // media path): the sketch image is uploaded to the `media-responses`\n // bucket via the same upload-client pipeline and referenced by\n // storage_path. Exported as PNG (crisp line art); the off-white paper\n // background is composited in before export so it is baked into the file.\n type: 'object',\n required: ['media'],\n properties: {\n media: {\n type: 'object',\n required: ['storage_path', 'type'],\n properties: {\n type: { enum: ['image'], type: 'string', description: 'Always \"image\" for a sketch' },\n storage_path: { type: 'string', description: 'Path in the media-responses bucket: bucket/workspace_id/.../uuid.png' },\n mime_type: { type: 'string', description: 'Image MIME type (image/png)' },\n width: { type: 'number', description: 'Exported sketch width in pixels (#5125)' },\n height: { type: 'number', description: 'Exported sketch height in pixels (#5125)' },\n },\n description: 'The exported sketch, stored as a single image in media-responses',\n },\n // Present only when the node has a configured game.target - absent for\n // every draw node published before #2148 and for one with no target.\n game: {\n type: 'object',\n description: 'Present when the node has a configured target shape - the respondent\\'s match-to-shape score',\n properties: {\n score: { type: 'number', minimum: 0, maximum: 100, description: '0-100 match score against the target outline' },\n avg_deviation: { type: 'number', minimum: 0, description: 'Average normalized deviation from the target outline (lower is better)' },\n tier: { type: 'string', description: 'The configured tier label the score falls into' },\n },\n },\n },\n },\n output_schema: {\n type: 'object',\n required: ['node_type'],\n properties: {\n node_type: { type: 'string', const: 'draw' },\n media: {\n type: 'object',\n properties: {\n type: { enum: ['image'], type: 'string' },\n content_type: { type: 'string', description: 'Image MIME type (e.g. image/png)' },\n filename: { type: 'string', description: 'Suggested download filename' },\n url: { type: 'string', format: 'uri', description: 'Direct, time-limited signed link to the drawing (~48h, supports HTTP range)' },\n download_url: { type: 'string', format: 'uri', description: 'Same link with a forced download (Content-Disposition: attachment)' },\n expires_at: { type: 'string', format: 'date-time', description: 'When url/download_url stop working' },\n },\n },\n // Mirrors response_schema.game (piece 1 of #2148) - transformResponse\n // passes it through unchanged, so this describes the FINAL emitted shape.\n game: {\n type: 'object',\n description: 'Present when the node has a configured target shape - the respondent\\'s match-to-shape score',\n properties: {\n score: { type: 'number', minimum: 0, maximum: 100, description: '0-100 match score against the target outline' },\n avg_deviation: { type: 'number', minimum: 0, description: 'Average normalized deviation from the target outline (lower is better)' },\n tier: { type: 'string', description: 'The configured tier label the score falls into' },\n },\n },\n },\n },\n },\n camera: {\n label: 'Camera',\n shorthand: 'Camera',\n icon: 'Camera',\n color: '#ECFCCB',\n description: 'Capture a photo or video from the device camera',\n category: 'input',\n sort_order: 6,\n has_options: false,\n is_terminal: false,\n show_nav_bar: true,\n loading: 'lazy',\n supports_prompt: false,\n supports_media: false,\n is_system: false,\n show_in_results: true,\n pii: false,\n respondent_media: 'files',\n // A captured photo/video, not a flat value - a notification renders a\n // typed placeholder (#4154).\n notify_inline: false,\n owner_scoped_config_keys: [],\n default_config: null,\n config_schema: {\n type: 'object',\n properties: {\n title: { type: 'string', label: 'Heading', description: 'Heading shown above the capture area' },\n description: { type: 'string', label: 'Description', description: 'Body text shown below the heading' },\n camera_facing: {\n type: 'string',\n enum: ['user', 'environment'],\n default: 'user',\n label: 'Phone camera default',\n description: 'Where the camera opens on phones - respondents can still switch',\n enumLabels: { user: 'Front (selfie)', environment: 'Rear' },\n },\n // The respondent's buttons (see cameraCaptureSources): Take a photo /\n // Record a video from camera_capture, Choose from library from\n // allow_library_upload accepting allowed_capture. At least one button\n // stays on (the builder enforces it).\n allowed_capture: {\n type: 'array',\n items: { type: 'string', enum: ['photo', 'video'] },\n default: ['photo'],\n label: 'Library accepts',\n // Existing nodes have no value and stay photo-only (the default). Also\n // the camera buttons while camera_capture is unset.\n description: 'What respondents can pick from their library - photos, videos, or both.',\n enumLabels: { photo: 'Photos', video: 'Videos' },\n },\n // Absent = allowed_capture, so existing nodes keep a camera button per type.\n camera_capture: {\n type: 'array',\n items: { type: 'string', enum: ['photo', 'video'] },\n label: 'Camera buttons',\n description: 'Which camera buttons respondents get - take a photo, record a video, or both',\n },\n allow_library_upload: {\n type: 'boolean',\n default: true,\n label: 'Library button',\n description: 'Whether respondents can pick existing photos or videos from their device',\n },\n // Display order of the three capture buttons respondents see. Lists all\n // three, enabled or not, so a disabled tile keeps its slot (Open's\n // `formats` model). The enable flags stay allowed_capture /\n // allow_library_upload; existing nodes have no value and keep today's order.\n capture_order: {\n type: 'array',\n items: { type: 'string', enum: ['photo', 'video', 'library'] },\n default: ['photo', 'video', 'library'],\n // Labels the builder's button tile row, which the creator toggles and\n // drags to set this order.\n label: 'Respondents can',\n description: 'The buttons respondents get. Turn each on or off, and drag to set their order.',\n enumLabels: { photo: 'Take a photo', video: 'Record a video', library: 'Choose from library' },\n },\n // Same meaning and 20 cap as file_upload's max_files (a cap on the\n // `files` array). Default 1 keeps every existing node single-capture (#3737).\n max_files: {\n type: 'number',\n min: 1,\n max: 20,\n default: 1,\n label: 'Media items',\n shortLabel: 'Max',\n description: 'How many photos or videos one answer can hold (1 = a single capture). Set Max above 1 to also set a minimum.',\n },\n // Clamped to <= max_files by the builder; enforced client-side like max_files.\n min_files: {\n type: 'number',\n min: 1,\n max: 20,\n default: 1,\n label: 'Minimum media items',\n shortLabel: 'Min',\n description: 'Fewest photos or videos a respondent must add before continuing',\n },\n allow_skip: {\n type: 'boolean',\n feature: 'optional_questions',\n default: false,\n label: 'Optional',\n description: 'Respondents can skip this question without adding a photo or video',\n },\n },\n },\n // Reuses file_upload's response shape verbatim (array of 1..max_files files) so\n // Results/exports/webhooks treat it the same way (scaffold skill: shape reuse).\n // A video submission carries a video mime_type - the shape doesn't change (#2759).\n response_schema: {\n type: 'object',\n required: ['files'],\n properties: {\n files: {\n type: 'array',\n items: {\n type: 'object',\n required: ['id', 'name', 'storage_path', 'url', 'mime_type', 'size', 'uploaded_at'],\n properties: {\n id: { type: 'string', format: 'uuid', description: 'Unique file identifier' },\n url: { type: 'string', format: 'uri', description: 'Signed Supabase Storage URL for download' },\n name: { type: 'string', description: 'Original filename' },\n size: { type: 'integer', minimum: 1, description: 'File size in bytes' },\n mime_type: { type: 'string', description: 'File MIME type (image/* or video/*)' },\n uploaded_at: { type: 'string', format: 'date-time', description: 'ISO timestamp of upload completion' },\n storage_path: { type: 'string', description: 'Bucket-prefixed storage path: respondent-captures/workspace_id/form_id/session_id/uuid.ext' },\n width: { type: 'number', description: 'Displayed pixel width, when the browser could read it (#5125)' },\n height: { type: 'number', description: 'Displayed pixel height, when the browser could read it (#5125)' },\n duration: { type: 'number', description: 'Video duration in seconds, when readable (#5125)' },\n // Viewer-written for a video recorded without the on-device 9:16 crop (#5253); the camera\n // video processor validates it and crops the playback copy server-side.\n preview_crop: {\n type: 'object',\n description: 'What the viewfinder showed (stream and preview box sizes); untrusted, validated server-side',\n properties: {\n stream_width: { type: 'number' },\n stream_height: { type: 'number' },\n preview_width: { type: 'number' },\n preview_height: { type: 'number' },\n },\n },\n // Server-written by the camera video processor (#5114); stripped from client input.\n thumbnail_storage_path: { type: 'string', description: 'Poster frame (webp) of a video, bucket-prefixed' },\n playback_storage_path: { type: 'string', description: 'Browser-safe H.264/AAC mp4 copy of a video, when the original is not one' },\n processed_at: { type: 'string', description: 'When the video was processed' },\n processing_attempts: { type: 'integer', description: 'Failed processing attempts so far' },\n processing_failed_at: { type: 'string', description: 'Set once processing gave up' },\n },\n },\n minItems: 1,\n maxItems: 20,\n description: 'The captured photos and videos, in capture order (1 to max_files items, mirroring file_upload)',\n },\n },\n },\n output_schema: {\n type: 'object',\n required: ['node_type'],\n properties: {\n node_type: { type: 'string', const: 'camera' },\n files: {\n type: 'array',\n description: 'The captured photos and videos in capture order, each as a canonical media object with a fresh signed link.',\n items: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Unique file identifier' },\n filename: { type: 'string', description: 'Original filename' },\n content_type: { type: 'string', description: 'File MIME type' },\n size: { type: 'integer', description: 'File size in bytes' },\n uploaded_at: { type: 'string', format: 'date-time', description: 'ISO timestamp of upload completion' },\n url: { type: 'string', format: 'uri', description: 'Direct, time-limited signed link (~48h, supports HTTP range)' },\n download_url: { type: 'string', format: 'uri', description: 'Same link with a forced download (Content-Disposition: attachment)' },\n expires_at: { type: 'string', format: 'date-time', description: 'When url/download_url stop working' },\n },\n },\n },\n },\n },\n },\n // Phase 1 of the variables engine (#4104, this node #4105): routes the\n // flow on a generic built-in Number (internally `score`, derived from\n // node_options.score -> ScoreState.cumulativeScore - see ROUTABLE_VARIABLES\n // in logic-types.js). Response-less and screen-less - the viewer evaluates\n // it transparently (no render) and continues to the matching branch. Each\n // branch is a node_options row (has_options:true); the branch edge is a\n // `jump` action anchored by the option's id (LogicAction.option_id).\n conditional: {\n label: 'If / then',\n shorthand: 'If',\n icon: 'Split',\n color: '#E0E7FF',\n description: 'Route the flow to different branches based on a score, max score, or category variable.',\n category: 'logic',\n sort_order: 12,\n has_options: true,\n min_options: 2,\n max_options: 10,\n max_option_length: 40,\n is_terminal: false,\n show_nav_bar: false,\n loading: 'eager',\n supports_prompt: false,\n supports_media: false,\n is_system: false,\n show_in_results: false,\n pii: false,\n respondent_media: null,\n // Logic/routing node - no respondent answer to render in a channel\n // notification, same as the other control nodes (redirect, link_list,\n // end_screen). Required by the #4154 notify_inline invariant.\n notify_inline: false,\n owner_scoped_config_keys: [],\n default_config: {\n options: [\n { content: 'Branch 1' },\n { content: 'Else' },\n ],\n },\n config_schema: null,\n response_schema: null,\n output_schema: null,\n },\n payment: {\n label: 'Payment',\n shorthand: 'Payment',\n icon: 'CreditCard',\n color: '#E9D5FF',\n description: 'Collect a payment from respondents inline, charged to a connected Stripe account',\n category: 'action',\n sort_order: 9,\n has_options: false,\n is_terminal: false,\n show_nav_bar: true,\n loading: 'lazy',\n supports_prompt: false,\n supports_media: false,\n is_system: false,\n show_in_results: true,\n pii: true,\n respondent_media: null,\n // Config keys that are owner-scoped to the authoring workspace - a connected\n // account (Stripe/etc via workspace_integrations), the owner's own uploaded\n // files, or a calendar link - and so must NOT survive a cross-workspace copy\n // (#4619/#4617/#4618/#4620 generalised this from the payment-only\n // connection_config_keys). The SoT for save_form's strip. The publish gate's\n // own showcase waiver (graph-validation.js) still names workspace_integration_id\n // directly since it's the only per-type check today.\n owner_scoped_config_keys: ['workspace_integration_id'],\n // Unclaimed anonymous-MCP forms may not go live with this node (#4847; derived into ANON_MCP_BLOCKED_NODE_TYPES).\n blocked_for_anon_mcp: true,\n // A payment confirmation line is the whole point of a notification for\n // this node type - always inline (#4154).\n notify_inline: true,\n default_config: { amount: null, currency: 'usd', provider: 'stripe' },\n config_schema: {\n type: 'object',\n required: ['amount', 'currency', 'provider'],\n properties: {\n amount: { type: 'number', label: 'Amount (in cents)', minimum: 50, required: true, description: 'Payment amount in cents (e.g., 5000 = $50.00)' },\n currency: { enum: ['usd', 'eur', 'gbp', 'cad', 'aud'], type: 'string', label: 'Currency', default: 'usd', required: true, description: 'Three-letter ISO currency code' },\n provider: { enum: ['stripe', 'paddle'], type: 'string', label: 'Payment Provider', default: 'stripe', required: true, description: 'Payment provider to use' },\n workspace_integration_id: { type: 'string', label: 'Workspace Integration ID', description: 'UUID of the workspace_integrations record for the connected payment account' },\n // Capped (#3940): they share a row with the amount in the viewer's order summary.\n title: { type: 'string', label: 'Heading', maxLength: 60, description: 'Heading shown above the order summary', anon_locked_keep: true },\n description: { type: 'string', label: 'Description', maxLength: 140, description: 'Body text shown below the heading in the order summary', anon_locked_keep: true },\n },\n description: 'Payment configuration with provider-agnostic flat structure',\n },\n response_schema: {\n type: 'object',\n oneOf: [\n {\n required: ['stripe'],\n properties: {\n stripe: {\n type: 'object',\n required: ['payment_intent_id', 'status', 'amount', 'currency'],\n properties: {\n name: { type: 'string', description: 'Customer name from Stripe billing details' },\n email: { type: 'string', format: 'email', description: 'Customer email from Stripe billing details' },\n phone: { type: 'string', description: 'Customer phone from Stripe billing details' },\n address: {\n type: 'object',\n description: 'Customer billing address from Stripe (only non-null parts present)',\n properties: {\n line1: { type: 'string' },\n line2: { type: 'string' },\n city: { type: 'string' },\n state: { type: 'string' },\n postal_code: { type: 'string' },\n country: { type: 'string', description: 'Two-letter ISO country code' },\n },\n },\n amount: { type: 'number', description: 'Payment amount in cents' },\n status: { enum: ['pending', 'succeeded', 'failed', 'partially_refunded', 'refunded'], type: 'string', description: 'Payment status, re-derived from the charge on every webhook sync' },\n amount_refunded: { type: 'number', description: 'Amount refunded so far, in cents. Only present once a refund (full or partial) has been issued' },\n currency: { type: 'string', description: 'Three-letter ISO currency code (e.g., usd, eur)' },\n payment_intent_id: { type: 'string', description: 'Stripe payment intent ID' },\n charge_id: { type: 'string', description: 'Stripe charge ID (ch_...) for reconciliation' },\n receipt_url: { type: 'string', format: 'uri', description: 'Stripe-hosted receipt page for this charge' },\n receipt_number: { type: 'string', description: 'Stripe receipt number (present once Stripe emails a receipt)' },\n balance_transaction: { type: 'string', description: 'Stripe balance transaction ID (txn_...) tying the charge to the payout ledger' },\n },\n },\n },\n },\n {\n required: ['square'],\n properties: {\n square: {\n type: 'object',\n properties: {\n amount: { type: 'number' },\n status: { type: 'string' },\n order_id: { type: 'string' },\n payment_id: { type: 'string' },\n },\n },\n },\n },\n {\n required: ['paddle'],\n properties: {\n paddle: {\n type: 'object',\n properties: {\n amount: { type: 'number' },\n status: { type: 'string' },\n order_id: { type: 'string' },\n checkout_id: { type: 'string' },\n },\n },\n },\n },\n ],\n description: 'Payment response with provider-specific data',\n },\n // The FINAL first-class emitted shape (#3796): transformResponse flattens the\n // stored `{ stripe: {...} }` into this provider-agnostic object. Must match\n // transformResponse's payment arm exactly, or validateOutput warns per row.\n // Card PAN/CVC are never present (only brand/last4 exist upstream).\n output_schema: {\n type: 'object',\n required: ['node_type', 'provider', 'status', 'amount', 'currency', 'payment_intent_id'],\n properties: {\n node_type: { type: 'string', const: 'payment' },\n provider: { type: 'string', const: 'stripe', description: 'Payment provider that processed the charge' },\n status: { enum: ['pending', 'succeeded', 'failed', 'partially_refunded', 'refunded'], type: 'string', description: 'Payment status, re-derived from the charge on every webhook sync' },\n amount: { type: 'number', description: 'Payment amount in cents' },\n amount_refunded: { type: 'number', description: 'Amount refunded so far, in cents. Only present once a refund (full or partial) has been issued' },\n currency: { type: 'string', description: 'Three-letter ISO currency code (e.g., usd, eur)' },\n payment_intent_id: { type: 'string', description: 'Stripe payment intent ID (pi_...)' },\n charge_id: { type: 'string', description: 'Stripe charge ID (ch_...) for reconciliation' },\n receipt_url: { type: 'string', format: 'uri', description: 'Stripe-hosted receipt page for this charge' },\n receipt_number: { type: 'string', description: 'Stripe receipt number (present once Stripe emails a receipt)' },\n customer: {\n type: 'object',\n description: 'Billing details the respondent entered at checkout (only non-null parts present)',\n properties: {\n name: { type: 'string', description: 'Customer name from Stripe billing details' },\n email: { type: 'string', format: 'email', description: 'Customer email from Stripe billing details' },\n phone: { type: 'string', description: 'Customer phone from Stripe billing details' },\n address: {\n type: 'object',\n description: 'Customer billing address (only non-null parts present)',\n properties: {\n line1: { type: 'string' },\n line2: { type: 'string' },\n city: { type: 'string' },\n state: { type: 'string' },\n postal_code: { type: 'string' },\n country: { type: 'string', description: 'Two-letter ISO country code' },\n },\n },\n },\n },\n },\n },\n },\n binary: {\n label: 'Binary',\n shorthand: 'A/B',\n icon: 'CircleCheck',\n color: '#DBEAFE',\n description: 'Two-option choice - yes/no, true/false, or this vs that',\n category: 'input',\n sort_order: 1.5,\n has_options: true,\n min_options: 2,\n max_options: 2,\n max_option_length: 12,\n is_terminal: false,\n show_nav_bar: true,\n loading: 'eager',\n supports_prompt: true,\n supports_media: true,\n is_system: false,\n show_in_results: true,\n pii: false,\n respondent_media: null,\n // Short selected-option label - safe to render inline (#4154).\n notify_inline: true,\n owner_scoped_config_keys: [],\n default_config: {\n choice: { enable_branching: false },\n options: [\n { content: 'Yes' },\n { content: 'No' },\n ],\n },\n config_schema: {\n type: 'object',\n properties: {\n choice: {\n type: 'object',\n properties: {\n enable_branching: {\n type: 'boolean',\n label: 'Enable branching logic',\n default: true,\n description: 'Allow each option to have its own logic path.',\n },\n },\n },\n content_media_type: {\n enum: ['upload', 'recorded'],\n type: 'string',\n label: 'Content media type',\n description: 'How the node media was provided',\n },\n },\n },\n response_schema: {\n type: 'string',\n description: 'Selected option ID',\n },\n output_schema: {\n type: 'object',\n required: ['node_type', 'label', 'option_id'],\n properties: {\n node_type: { type: 'string', const: 'binary' },\n label: { type: 'string', description: 'Human-readable option label' },\n option_id: { type: 'string', format: 'uuid', description: 'Selected option UUID' },\n },\n },\n },\n button: {\n label: 'Button',\n shorthand: 'Button',\n icon: 'RectangleHorizontal',\n color: '#DBEAFE',\n description: 'Simple button for acknowledgment or navigation',\n category: 'input',\n sort_order: 3.5,\n has_options: true,\n min_options: 1,\n max_options: 1,\n max_option_length: 28,\n is_terminal: false,\n show_nav_bar: true,\n loading: 'eager',\n supports_prompt: true,\n supports_media: true,\n is_system: false,\n show_in_results: false,\n pii: false,\n respondent_media: null,\n // Short selected-option label - safe to render inline (#4154).\n notify_inline: true,\n owner_scoped_config_keys: [],\n default_config: { options: [{ content: 'Continue' }] },\n config_schema: {\n type: 'object',\n properties: {\n button_text: { type: 'string', label: 'Button text', default: 'Continue' },\n button_style: { enum: ['primary', 'secondary', 'outline'], type: 'string', label: 'Button style', default: 'primary' },\n },\n },\n response_schema: {\n type: 'string',\n description: 'Selected option ID',\n },\n output_schema: {\n type: 'object',\n required: ['node_type', 'label', 'option_id'],\n properties: {\n node_type: { type: 'string', const: 'button' },\n label: { type: 'string', description: 'Human-readable option label' },\n option_id: { type: 'string', format: 'uuid', description: 'Selected option UUID' },\n },\n },\n },\n redirect: {\n label: 'Redirect',\n shorthand: 'Redirect',\n icon: 'ExternalLink',\n color: '#FFEDD5',\n description: 'Redirect users to an external URL',\n category: 'end',\n sort_order: 997,\n has_options: false,\n is_terminal: true,\n show_nav_bar: false,\n loading: 'lazy',\n supports_prompt: false,\n supports_media: false,\n is_system: false,\n show_in_results: false,\n pii: false,\n respondent_media: null,\n // Terminal node - never appears in a completed submission's answers\n // (filtered by NON_COUNTABLE_FILTER); false is a no-op default.\n notify_inline: false,\n owner_scoped_config_keys: [],\n // Unclaimed anonymous-MCP forms may not go live with this node (#4847; derived into ANON_MCP_BLOCKED_NODE_TYPES).\n blocked_for_anon_mcp: true,\n default_config: { url: '', auto_redirect: true },\n config_schema: {\n type: 'object',\n properties: {\n url: { type: 'string', label: 'Redirect URL', placeholder: 'https://example.com', outbound_link: true },\n auto_redirect: { type: 'boolean', label: 'Auto-redirect', default: true, description: 'Automatically redirect to the URL instead of showing a button' },\n },\n },\n response_schema: {\n type: 'string',\n description: 'URL the user was redirected to',\n },\n output_schema: null,\n },\n link_list: {\n label: 'Link List',\n shorthand: 'Links',\n icon: 'ExternalLink',\n color: '#FFEDD5',\n description: 'Display a list of links for users to choose from',\n category: 'end',\n sort_order: 998,\n has_options: false,\n is_terminal: true,\n show_nav_bar: false,\n loading: 'lazy',\n supports_prompt: false,\n supports_media: false,\n is_system: false,\n show_in_results: false,\n pii: false,\n respondent_media: null,\n // Terminal node - never appears in a completed submission's answers\n // (filtered by NON_COUNTABLE_FILTER); false is a no-op default.\n notify_inline: false,\n owner_scoped_config_keys: [],\n // Unclaimed anonymous-MCP forms may not go live with this node (#4847; derived into ANON_MCP_BLOCKED_NODE_TYPES).\n blocked_for_anon_mcp: true,\n default_config: { links: [{ id: 'default', url: '', title: '', description: '', order: 0 }], auto_redirect: false },\n config_schema: {\n type: 'object',\n properties: {\n links: {\n type: 'array',\n items: {\n type: 'object',\n required: ['id', 'url'],\n properties: {\n id: { type: 'string' },\n url: { type: 'string', label: 'URL', placeholder: 'https://example.com', outbound_link: true },\n title: { type: 'string', label: 'Heading' },\n description: { type: 'string', label: 'Description' },\n order: { type: 'number', label: 'Sort order' },\n },\n },\n label: 'Links',\n minItems: 1,\n },\n auto_redirect: { type: 'boolean', label: 'Auto-redirect', default: false, description: 'Automatically redirect to the URL instead of showing a button' },\n },\n },\n response_schema: {\n type: 'string',\n description: 'URL of the link that was clicked',\n },\n output_schema: null,\n },\n file_download: {\n label: 'File Download',\n shorthand: 'Download',\n icon: 'Download',\n color: '#E9D5FF',\n description: 'Provide a file for respondents to download',\n category: 'action',\n sort_order: 11,\n has_options: false,\n is_terminal: false,\n show_nav_bar: true,\n loading: 'lazy',\n supports_prompt: false,\n supports_media: false,\n is_system: false,\n show_in_results: true,\n pii: false,\n respondent_media: null,\n // Files, not a flat value - a notification renders a typed placeholder (#4154).\n notify_inline: false,\n // The owner's own uploaded files (#4617) - stripped on cross-workspace\n // copy so a forked node can't keep serving the source workspace's files;\n // the publish gate's \"No files uploaded\" check then forces a fresh upload.\n owner_scoped_config_keys: ['files'],\n // Unclaimed anonymous-MCP forms may not go live with this node (#4847; derived into ANON_MCP_BLOCKED_NODE_TYPES).\n blocked_for_anon_mcp: true,\n default_config: null,\n config_schema: {\n type: 'object',\n properties: {\n files: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n file_name: { type: 'string', label: 'Original file name', required: true },\n display_name: { type: 'string', label: 'Friendly name shown to respondents' },\n file_path: { type: 'string', label: 'File path in storage', required: true },\n file_size: { type: 'number', label: 'File size in bytes' },\n mime_type: { type: 'string', label: 'MIME type' },\n },\n },\n label: 'Downloadable files',\n },\n button_text: { type: 'string', label: 'Continue button text', default: 'Continue' },\n description: { type: 'string', label: 'Description text', anon_locked_keep: true },\n },\n },\n response_schema: {\n type: 'object',\n required: ['files'],\n properties: {\n files: {\n type: 'array',\n items: {\n type: 'object',\n required: ['file_path', 'file_name', 'downloaded_at'],\n properties: {\n file_name: { type: 'string', description: 'Display name of the file' },\n file_path: { type: 'string', description: 'Storage path of the downloaded file' },\n downloaded_at: { type: 'string', format: 'date-time', description: 'Timestamp when download was initiated' },\n },\n },\n description: 'List of files downloaded by respondent',\n },\n },\n },\n output_schema: {\n type: 'object',\n required: ['node_type'],\n properties: {\n node_type: { type: 'string', const: 'file_download' },\n files: {\n type: 'array',\n description: 'The files the respondent downloaded, each a canonical media object with a fresh signed link.',\n items: {\n type: 'object',\n properties: {\n filename: { type: 'string', description: 'Original filename' },\n content_type: { type: 'string', description: 'File MIME type' },\n downloaded_at: { type: 'string', format: 'date-time', description: 'Timestamp when download was initiated' },\n url: { type: 'string', format: 'uri', description: 'Direct, time-limited signed link (~48h, supports HTTP range)' },\n download_url: { type: 'string', format: 'uri', description: 'Same link with a forced download (Content-Disposition: attachment)' },\n expires_at: { type: 'string', format: 'date-time', description: 'When url/download_url stop working' },\n },\n },\n },\n },\n },\n },\n shopping: {\n label: 'Shopping',\n shorthand: 'Shop',\n icon: 'ShoppingBag',\n color: '#E9D5FF',\n description: 'Product recommendations with direct checkout',\n category: 'action',\n sort_order: 10,\n has_options: false,\n is_terminal: true,\n show_nav_bar: true,\n loading: 'lazy',\n supports_prompt: false,\n supports_media: false,\n is_system: false,\n show_in_results: false,\n pii: false,\n respondent_media: null,\n // No response_schema - never carries a flat answer value; false is a no-op default.\n notify_inline: false,\n owner_scoped_config_keys: [],\n default_config: { provider: 'shopify', cta_mode: 'checkout', source_mode: 'manual' },\n config_schema: {\n type: 'object',\n required: ['provider', 'cta_mode'],\n properties: {\n title: { type: 'string', label: 'Heading', description: 'Heading shown above the product list' },\n description: { type: 'string', label: 'Description', description: 'Body text shown below the heading' },\n provider: { enum: ['shopify'], type: 'string', label: 'Provider', default: 'shopify', description: 'Ecommerce provider' },\n workspace_integration_id: { type: 'string', label: 'Workspace Integration ID', description: 'UUID of the workspace_integrations record for the connected store' },\n cta_mode: { enum: ['checkout', 'add_to_cart'], type: 'string', label: 'CTA Mode', default: 'checkout', description: 'Whether to go to checkout or add to cart' },\n source_mode: { enum: ['manual', 'collection'], type: 'string', label: 'Product source', default: 'manual', description: 'How products are selected: manually picked or from a collection' },\n collection_id: { type: 'string', label: 'Collection ID', description: 'Shopify collection GID (when source_mode is collection)' },\n collection_title: { type: 'string', label: 'Collection title', description: 'Display name of the selected collection' },\n products: {\n type: 'array',\n label: 'Selected Products',\n description: 'Products to show (static mode)',\n items: {\n type: 'object',\n properties: {\n product_id: { type: 'string', description: 'Shopify product GID' },\n variant_id: { type: 'string', description: 'Shopify variant GID' },\n title: { type: 'string' },\n handle: { type: 'string' },\n image_url: { type: 'string' },\n price: { type: 'string' },\n currency: { type: 'string' },\n recommended: { type: 'boolean', default: true, description: 'Pre-ticked in viewer' },\n },\n },\n },\n product_mappings: {\n type: 'array',\n label: 'Score-based product mappings',\n description: 'Map score ranges to different product sets. First matching range wins.',\n items: {\n type: 'object',\n required: ['min', 'max'],\n properties: {\n min: { type: 'integer', label: 'Minimum score (inclusive)' },\n max: { type: 'integer', label: 'Maximum score (inclusive)' },\n message: { type: 'string', label: 'Message' },\n products: { type: 'array', description: 'Products for this score range' },\n },\n },\n },\n },\n description: 'Shopping configuration with provider-agnostic structure',\n },\n response_schema: null,\n output_schema: null,\n },\n end_screen: {\n label: 'Ending',\n shorthand: 'End',\n icon: 'Flag',\n color: '#FFEDD5',\n description: 'Final screen shown when form is completed',\n category: 'end',\n sort_order: 999,\n has_options: false,\n is_terminal: true,\n show_nav_bar: false,\n loading: 'eager',\n supports_prompt: false,\n supports_media: false,\n is_system: false,\n show_in_results: false,\n pii: false,\n respondent_media: null,\n // Terminal node - never appears in a completed submission's answers\n // (filtered by NON_COUNTABLE_FILTER); false is a no-op default.\n notify_inline: false,\n owner_scoped_config_keys: [],\n default_config: {\n title: 'Thank you!',\n message: 'Your response has been submitted.',\n },\n config_schema: {\n type: 'object',\n properties: {\n title: { type: 'string', label: 'Title', default: 'Thank you!', description: 'Heading shown on completion' },\n message: { type: 'string', label: 'Message', default: 'Your response has been submitted.', description: 'Message shown on completion' },\n show_score: { type: 'boolean', label: 'Show score', default: false, description: 'Display score on the end screen (e.g. \"You scored 4 out of 5\")' },\n icon: { type: 'string', label: 'Icon', enum: ['tick', 'trophy', 'star', 'crown', 'party', 'none'], default: 'tick', description: 'Icon shown above the title' },\n show_share_button: { type: 'boolean', label: 'Show share button', default: false, description: 'Show a share button above the CTA' },\n cta_type: { type: 'string', label: 'CTA type', enum: ['none', 'restart', 'external_link'], default: 'none', description: 'Primary call-to-action button type' },\n cta_text: { type: 'string', label: 'CTA button text', default: 'Continue', description: 'Button label for the CTA' },\n cta_url: { type: 'string', label: 'CTA URL', format: 'uri', description: 'URL to open (only for external_link CTA type)', placeholder: 'https://example.com', outbound_link: true },\n score_ranges: {\n type: 'array',\n label: 'Score-based content',\n description: 'Show different content based on cumulative score. First matching range wins.',\n items: {\n type: 'object',\n required: ['min', 'max', 'title'],\n properties: {\n min: { type: 'integer', label: 'Minimum score (inclusive)' },\n max: { type: 'integer', label: 'Maximum score (inclusive)' },\n title: { type: 'string', label: 'Title' },\n message: { type: 'string', label: 'Message' },\n },\n },\n },\n score_line: {\n type: 'string',\n label: 'Score line',\n feature: 'variables',\n description: 'Sentence shown with the score, with variable codes (e.g. \"You scored {{score}} out of 10\"). Replaces the default \"You scored X out of Y\" line.',\n },\n outcomes: {\n type: 'array',\n label: 'Variable-based results',\n feature: 'variables',\n description: 'Show different content based on a number variable. The first outcome whose range (inclusive) holds the variable value wins.',\n items: {\n type: 'object',\n required: ['variable_id', 'min', 'max', 'title'],\n properties: {\n variable_id: { type: 'string', label: 'Number variable id' },\n min: { type: 'number', label: 'Minimum (inclusive)' },\n max: { type: 'number', label: 'Maximum (inclusive)' },\n title: { type: 'string', label: 'Title' },\n message: { type: 'string', label: 'Message' },\n },\n },\n },\n scoring_results: {\n type: 'array',\n label: 'Category-based results',\n description: 'Results keyed by scoring category. The winning category (highest non-knocked-out score) determines which result is shown.',\n items: {\n type: 'object',\n required: ['category', 'title'],\n properties: {\n category: { type: 'string', label: 'Category key (must match keys used in option scores)' },\n title: { type: 'string', label: 'Title' },\n message: { type: 'string', label: 'Message' },\n cta_url: { type: 'string', label: 'CTA URL', format: 'uri', outbound_link: true },\n cta_text: { type: 'string', label: 'CTA button text' },\n },\n },\n },\n },\n },\n response_schema: null,\n output_schema: null,\n },\n};\n\n// Availability is derived from the FEATURES registry (single source of truth).\n// Each node type `x` maps to feature `node_x`; the throw below makes a missing\n// or renamed feature fail loudly at import, and a vitest guards the mapping.\nfor (const [type, def] of Object.entries(NODE_TYPES)) {\n const feature = FEATURES[`node_${type}`];\n if (!feature) {\n throw new Error(`NODE_TYPES.${type}: no matching FEATURES[\"node_${type}\"] entry`);\n }\n def.is_active = feature.enabled;\n}\n\n// A top-level config_schema property may carry `feature: '<FEATURES key>'`: the\n// key is available only while that feature is enabled. Author surfaces (MCP\n// summary + write tools, OpenAPI key list) read gatedConfigKeys; stored data is\n// never touched, so flipping the flag re-exposes the key. An unknown feature\n// name throws at import (same loud-failure pattern as the node_${type} mapping).\n// `enum_features: { <value>: '<FEATURES key>' }` gates single enum values the\n// same way (booking's `google_meet` provider while Calendly is live alone).\nexport function validateFeatureMarkers(nodeTypes, features) {\n for (const [type, def] of Object.entries(nodeTypes)) {\n for (const [key, prop] of Object.entries(def.config_schema?.properties ?? {})) {\n if (prop.feature !== undefined && !features[prop.feature]) {\n throw new Error(`NODE_TYPES.${type}.config_schema.${key}: feature \"${prop.feature}\" is not in FEATURES`);\n }\n for (const [value, feature] of Object.entries(prop.enum_features ?? {})) {\n if (!prop.enum?.includes(value)) {\n throw new Error(`NODE_TYPES.${type}.config_schema.${key}: enum_features value \"${value}\" is not in its enum`);\n }\n if (!features[feature]) {\n throw new Error(`NODE_TYPES.${type}.config_schema.${key}: enum_features feature \"${feature}\" is not in FEATURES`);\n }\n }\n }\n }\n}\nvalidateFeatureMarkers(NODE_TYPES, FEATURES);\n\n/**\n * Enum values of `type`'s top-level config key `key` whose `enum_features`\n * marker is currently off. Evaluated on each call so a flag flip is honoured.\n */\nexport function gatedEnumValues(type, key) {\n const prop = NODE_TYPES[type]?.config_schema?.properties?.[key];\n return new Set(\n Object.entries(prop?.enum_features ?? {})\n .filter(([, feature]) => !FEATURES[feature]?.enabled)\n .map(([value]) => value)\n );\n}\n\n/** True when `config[key]` holds a gated enum value (see gatedEnumValues). */\nfunction holdsGatedEnumValue(type, key, value) {\n return typeof value === 'string' && gatedEnumValues(type, key).has(value);\n}\n\n/**\n * Top-level config keys of `type` whose `feature` marker is currently off.\n * Evaluated on each call so a flag flip is honoured.\n */\nexport function gatedConfigKeys(type) {\n const props = NODE_TYPES[type]?.config_schema?.properties ?? {};\n return new Set(\n Object.entries(props)\n .filter(([, prop]) => prop.feature !== undefined && !FEATURES[prop.feature]?.enabled)\n .map(([key]) => key)\n );\n}\n\n/**\n * Drop gated keys from a caller-supplied config, and any key set to a gated\n * enum value. Returns a new object (never mutates - default_config is shared)\n * plus the dropped key names.\n */\nexport function stripGatedConfigKeys(type, config) {\n if (!config || typeof config !== 'object') return { config, dropped: [] };\n const gated = gatedConfigKeys(type);\n const isGated = ([k, v]) => gated.has(k) || holdsGatedEnumValue(type, k, v);\n const dropped = Object.entries(config).filter(isGated).map(([k]) => k);\n if (dropped.length === 0) return { config, dropped };\n return { config: Object.fromEntries(Object.entries(config).filter((e) => !isGated(e))), dropped };\n}\n\n// Derived exports\n\n/** Sorted list of all node types with their type key included */\nexport const NODE_TYPES_LIST = Object.entries(NODE_TYPES)\n .map(([type, def]) => ({ type, ...def }))\n .sort((a, b) => a.sort_order - b.sort_order);\n\n/**\n * Node types the dashboard treats as active, as full definitions - the single\n * owner of the derivation previously inlined in NodeTypesProvider. A type is\n * active when it is globally active OR the company is allowlisted to dogfood it\n * ahead of the global flip. Mirrors the old dashboard filter exactly: system\n * nodes (e.g. `start`, which is is_active) stay in, so getNodeType('start')\n * still resolves its colour - the node picker filters `is_system` separately.\n * Pass no companyId for the plain globally-active set.\n */\nexport function getActiveNodeTypes(companyId) {\n return NODE_TYPES_LIST.filter(\n t => t.is_active || companyHasNodeType(companyId, t.type)\n );\n}\n\n/**\n * Active, non-system node type KEYS - the user-addable set consumed by the API\n * and MCP server. Derived from Object.entries(NODE_TYPES) (definition order) so\n * the list is byte-identical to the derivations it replaces, including the order\n * that surfaces in z.enum / validation error messages.\n */\nexport const ACTIVE_NODE_TYPES = Object.entries(NODE_TYPES)\n .filter(([, def]) => def.is_active && !def.is_system)\n .map(([type]) => type);\n\n/** All valid node type keys */\nexport const NODE_TYPE_KEYS = Object.keys(NODE_TYPES);\n\nconst END_SCREEN_ICON_SCHEMA = NODE_TYPES.end_screen.config_schema.properties.icon;\n\n/** The End Screen icons a creator can pick, in picker order (`none` shows no icon). */\nexport const END_SCREEN_ICONS = END_SCREEN_ICON_SCHEMA.enum;\n\n/**\n * The End Screen icon to show for a stored `config.icon` (#6077): the value\n * when the schema knows it, else the schema default. Stored data can hold an\n * off-schema value (null, a non-string, a retired name), so the viewer and the\n * builder picker both read through this instead of trusting the raw value.\n */\nexport function resolveEndScreenIcon(value) {\n return END_SCREEN_ICONS.includes(value) ? value : END_SCREEN_ICON_SCHEMA.default;\n}\n\n/**\n * Node types -> their owner_scoped_config_keys, for types that declare any\n * (non-empty). The SoT for save_form (cross-workspace copy, #2064 part 2,\n * generalised by #4619/#4617/#4618/#4620) to strip workspace-owner-scoped\n * refs from a copied node's config - derived like ACTIVE_NODE_TYPES so no\n * consumer hand-maintains a duplicate list. Does NOT cover\n * `details.consent_items[].document`, which is nested inside an array and\n * handled by a dedicated SQL rewrite instead.\n *\n * `owner_scoped_config_keys` is MANDATORY on every NODE_TYPES entry (`[]`\n * when nothing in that type's config is owner-scoped) - a fail-safe default\n * so a new node type can't silently inherit this bug class by omission.\n * Enforced by packages/config/test/owner-scoped-config-keys.test.js.\n */\nexport const OWNER_SCOPED_CONFIG_KEYS = Object.fromEntries(\n Object.entries(NODE_TYPES)\n .filter(([, def]) => Array.isArray(def.owner_scoped_config_keys) && def.owner_scoped_config_keys.length > 0)\n .map(([type, def]) => [type, def.owner_scoped_config_keys])\n);\n\n/** Response schemas keyed by node type */\nexport const RESPONSE_SCHEMAS = Object.fromEntries(\n Object.entries(NODE_TYPES).map(([k, v]) => [k, v.response_schema])\n);\n\n/** Config schemas keyed by node type */\nexport const CONFIG_SCHEMAS = Object.fromEntries(\n Object.entries(NODE_TYPES).map(([k, v]) => [k, v.config_schema])\n);\n\n/** Output schemas keyed by node type */\nexport const OUTPUT_SCHEMAS = Object.fromEntries(\n Object.entries(NODE_TYPES).map(([k, v]) => [k, v.output_schema])\n);\n\n/** Metadata subset used by viewer for layout decisions */\nexport const NODE_TYPE_METADATA = Object.fromEntries(\n Object.entries(NODE_TYPES).map(([k, v]) => [k, {\n supports_prompt: v.supports_prompt,\n supports_media: v.supports_media,\n is_terminal: v.is_terminal,\n show_nav_bar: v.show_nav_bar,\n category: v.category,\n loading: v.loading,\n interaction_fills_stage: v.interaction_fills_stage === true,\n }])\n);\n\n/** Terminal node type keys (is_terminal === true) */\nexport const TERMINAL_TYPES = Object.entries(NODE_TYPES)\n .filter(([, v]) => v.is_terminal)\n .map(([k]) => k);\n\n/** Node types excluded from counts (system + terminal) */\nexport const NON_COUNTABLE_TYPES = Object.entries(NODE_TYPES)\n .filter(([, v]) => v.is_system || v.is_terminal)\n .map(([k]) => k);\n\n/** Supabase .not() filter string for non-countable types */\nexport const NON_COUNTABLE_FILTER = `(${NON_COUNTABLE_TYPES.map(t => `\"${t}\"`).join(',')})`;\n\n/** Node types excluded from the aggregate Results charts */\nexport const RESULTS_EXCLUDED_TYPES = Object.entries(NODE_TYPES)\n .filter(([, v]) => !v.show_in_results)\n .map(([k]) => k);\n\n/** Node types whose answer is contact or payment data (`pii` flag). */\nexport const PII_NODE_TYPES = Object.entries(NODE_TYPES)\n .filter(([, v]) => v.pii)\n .map(([k]) => k);\n\n/** Node types that can hold respondent-uploaded or recorded media (`respondent_media` flag). */\nexport const RESPONDENT_MEDIA_NODE_TYPES = Object.entries(NODE_TYPES)\n .filter(([, v]) => v.respondent_media !== null)\n .map(([k]) => k);\n\n/** Node types whose answer is a `files` array of stored uploads (`respondent_media: 'files'`). */\nexport const FILE_ANSWER_NODE_TYPES = Object.entries(NODE_TYPES)\n .filter(([, v]) => v.respondent_media === 'files')\n .map(([k]) => k);\n\n/**\n * Node types excluded from the PUBLIC results portal on top of\n * `RESULTS_EXCLUDED_TYPES` (#2129): PII (contact details, booking details,\n * payment data) and\n * respondent media stored as files or drawings (file uploads, camera captures,\n * drawings) never leave the owner-only Results tab, even when a form's results\n * are shared publicly. Derived from the `pii` and `respondent_media` flags\n * (#5282). Recordings (`open`) are not listed: an open answer is usually text.\n * The `get_public_form_results` RPC mirrors this list in SQL (drift-gated by\n * `test/public-results-excluded-sql.test.js`); the API route applies it again\n * on the returned rows, and the public page applies it a third time.\n */\nexport const PUBLIC_RESULTS_EXCLUDED_TYPES = Object.entries(NODE_TYPES)\n .filter(([, v]) => v.pii || v.respondent_media === 'files' || v.respondent_media === 'drawing')\n .map(([k]) => k);\n\n/**\n * Node types that count as a step in the respondent-facing step counter (#488).\n * Only answer-collecting nodes count - the respondent thinks in questions\n * (\"3 of 5\"), not screens. Pure transitions (`button`) and terminals/start are\n * nav-bar or non-nav nodes that advance neither the current step nor the total.\n */\nconst NON_STEP_TYPES = new Set(['button']);\nexport const STEP_COUNTED_TYPES = Object.entries(NODE_TYPES)\n .filter(([k, v]) => v.show_nav_bar && !NON_STEP_TYPES.has(k))\n .map(([k]) => k);\n\n/**\n * Node types excluded from the per-response Responses table.\n * Defaults to the Results exclusions; a type can opt back IN for responses\n * with `show_in_responses: true` (e.g. contact - aggregate-meaningless but\n * actionable per-lead, #746).\n */\nexport const RESPONSES_EXCLUDED_TYPES = Object.entries(NODE_TYPES)\n .filter(([, v]) => !(v.show_in_responses ?? v.show_in_results))\n .map(([k]) => k);\n\n/** Check if a node type is terminal */\nexport function isTerminalType(type) {\n return NODE_TYPE_METADATA[type]?.is_terminal === true;\n}\n\n/** Check if a node type counts as a step in the respondent step counter (#488) */\nexport function countsAsStep(type) {\n return STEP_COUNTED_TYPES.includes(type);\n}\n\n\n/**\n * Node types an unclaimed anonymous-MCP form may NOT go live with (#4847):\n * phishing-capable (`redirect`, `link_list`, `file_download`, `payment`) and\n * `file_upload` (audio/video answers are allowed, arbitrary files wait for a\n * claim). Derived from the `blocked_for_anon_mcp` flag on NODE_TYPES - never\n * hardcode this list downstream.\n */\nexport const ANON_MCP_BLOCKED_NODE_TYPES = Object.entries(NODE_TYPES)\n .filter(([, v]) => v.blocked_for_anon_mcp === true)\n .map(([k]) => k);\n\n/**\n * Config fields that send a respondent to an outbound URL, derived from the\n * config_schema: a property flagged `outbound_link: true` is a rule \"non-empty\",\n * and a property whose `enum` offers `external_link` is a rule \"equals\n * external_link\". Paths use `[]` for array items. Together with\n * ANON_MCP_BLOCKED_NODE_TYPES this is what an unclaimed anonymous-MCP form may\n * not go live with (#4847): the end_screen CTA is the ending-node escape hatch.\n * @type {{ type: string, path: string[], kind: 'non_empty' | 'equals', value?: string }[]}\n */\nexport const ANON_MCP_OUTBOUND_LINK_RULES = (() => {\n const rules = [];\n const walk = (type, schema, path) => {\n if (!schema || typeof schema !== 'object') return;\n for (const [key, prop] of Object.entries(schema.properties ?? {})) {\n const next = [...path, key];\n if (prop.outbound_link === true) rules.push({ type, path: next, kind: 'non_empty' });\n if (Array.isArray(prop.enum) && prop.enum.includes('external_link')) {\n rules.push({ type, path: next, kind: 'equals', value: 'external_link' });\n }\n walk(type, prop, next);\n if (prop.items) walk(type, prop.items, [...next, '[]']);\n }\n // Union variants (booking's per-provider config) share the same path.\n for (const branch of [...(schema.oneOf ?? []), ...(schema.anyOf ?? [])]) walk(type, branch, path);\n };\n for (const [type, def] of Object.entries(NODE_TYPES)) walk(type, def.config_schema, []);\n return rules;\n})();\n\n/**\n * Per-field strip rules for NON-blocked node types on a live anonymous-workspace\n * form (#4847): every outbound-link destination (non-empty\n * ANON_MCP_OUTBOUND_LINK_RULES: end_screen cta_url + scoring_results[].cta_url)\n * plus every property flagged `anon_locked_file: true` (details\n * consent_items[].document - an outside file). A BLOCKED node type\n * (ANON_MCP_BLOCKED_NODE_TYPES) is not handled field by field: its whole config\n * is blanked (see stripAnonMcpLockedNode), so an undeclared url field can never\n * slip through. Derived from the config_schema markers - never hand-list these.\n * @type {{ type: string, path: string[] }[]}\n */\nexport const ANON_MCP_STRIPPED_FIELD_RULES = (() => {\n const rules = ANON_MCP_OUTBOUND_LINK_RULES.filter((r) => r.kind === 'non_empty' && !ANON_MCP_BLOCKED_NODE_TYPES.includes(r.type)).map(({ type, path }) => ({ type, path }));\n const walk = (type, schema, path) => {\n if (!schema || typeof schema !== 'object') return;\n for (const [key, prop] of Object.entries(schema.properties ?? {})) {\n const next = [...path, key];\n if (prop.anon_locked_file === true) rules.push({ type, path: next });\n walk(type, prop, next);\n if (prop.items) walk(type, prop.items, [...next, '[]']);\n }\n for (const branch of [...(schema.oneOf ?? []), ...(schema.anyOf ?? [])]) walk(type, branch, path);\n };\n for (const [type, def] of Object.entries(NODE_TYPES)) {\n if (!ANON_MCP_BLOCKED_NODE_TYPES.includes(type)) walk(type, def.config_schema, []);\n }\n return rules;\n})();\n\n/**\n * Plain display-text keys a BLOCKED node type keeps when its config is blanked on a\n * guest live form (#4847), so the creator's own heading survives on the locked step:\n * the TOP-LEVEL config_schema string properties flagged `anon_locked_keep: true`\n * (payment title/description, file_download description). Everything else - urls,\n * ids, providers, amounts, files, links - is dropped. Derived from the markers.\n * @type {Record<string, string[]>}\n */\nexport const ANON_MCP_KEPT_TEXT_KEYS = (() => {\n const out = {};\n for (const type of ANON_MCP_BLOCKED_NODE_TYPES) {\n const props = NODE_TYPES[type]?.config_schema?.properties ?? {};\n const keys = Object.entries(props)\n .filter(([, p]) => p && p.anon_locked_keep === true && p.type === 'string')\n .map(([k]) => k);\n if (keys.length > 0) out[type] = keys;\n }\n return out;\n})();\n\nfunction anonValuesAtPath(value, path) {\n if (path.length === 0) return [value];\n const [head, ...rest] = path;\n if (head === '[]') return Array.isArray(value) ? value.flatMap((v) => anonValuesAtPath(v, rest)) : [];\n if (value && typeof value === 'object') return anonValuesAtPath(value[head], rest);\n return [];\n}\n\nfunction blankAtPath(value, path) {\n if (path.length === 0) return '';\n const [head, ...rest] = path;\n if (head === '[]') return Array.isArray(value) ? value.map((v) => blankAtPath(v, rest)) : value;\n if (value && typeof value === 'object' && head in value) {\n return { ...value, [head]: blankAtPath(value[head], rest) };\n }\n return value;\n}\n\n/**\n * Does this node carry a locked step for an unclaimed anonymous workspace\n * (#4847)? ONE derivation shared by the payload strip and the claim lock, so\n * neither has its own list: a blocked node type, OR an outbound-link rule match,\n * OR a non-empty value at any ANON_MCP_STRIPPED_FIELD_RULES path (an outside file\n * such as a consent document). Whatever the strip removes, this detects.\n * @param {{ type: string, config?: unknown }} node\n */\nexport function isAnonMcpLockedNode(node) {\n if (!node || typeof node.type !== 'string') return false;\n if (ANON_MCP_BLOCKED_NODE_TYPES.includes(node.type)) return true;\n const isSet = (v) => (typeof v === 'string' ? v.trim() !== '' : v != null && v !== false);\n const outbound = ANON_MCP_OUTBOUND_LINK_RULES.some((rule) => {\n if (rule.type !== node.type) return false;\n return anonValuesAtPath(node.config, rule.path).some((v) => (rule.kind === 'equals' ? v === rule.value : isSet(v)));\n });\n if (outbound) return true;\n return ANON_MCP_STRIPPED_FIELD_RULES.some(\n (rule) => rule.type === node.type && anonValuesAtPath(node.config, rule.path).some(isSet),\n );\n}\n\n/**\n * The node as a guest live form may serve it. A BLOCKED node type has its config\n * reduced to ANON_MCP_KEPT_TEXT_KEYS (plain display text, so the locked step keeps its\n * heading) and nothing else. Any other\n * type has just its ANON_MCP_STRIPPED_FIELD_RULES fields blanked to \"\", keeping\n * the shape. Pure: returns the same node when nothing applies, never mutates.\n * @template T\n * @param {T & { type: string, config?: unknown }} node\n * @returns {T}\n */\nexport function stripAnonMcpLockedNode(node) {\n if (!node || typeof node.type !== 'string') return node;\n if (ANON_MCP_BLOCKED_NODE_TYPES.includes(node.type)) {\n // Keep only marked plain-text fields (and only if they are strings); drop everything else.\n const src = node.config && typeof node.config === 'object' ? node.config : {};\n const kept = {};\n for (const key of ANON_MCP_KEPT_TEXT_KEYS[node.type] ?? []) {\n if (typeof src[key] === 'string') kept[key] = src[key];\n }\n const same =\n node.config && typeof node.config === 'object' &&\n Object.keys(node.config).length === Object.keys(kept).length &&\n Object.keys(kept).every((k) => node.config[k] === kept[k]);\n return same ? node : { ...node, config: kept };\n }\n if (!node.config || typeof node.config !== 'object') return node;\n let config = node.config;\n for (const rule of ANON_MCP_STRIPPED_FIELD_RULES) {\n if (rule.type === node.type) config = blankAtPath(config, rule.path);\n }\n return config === node.config ? node : { ...node, config };\n}\n","/**\n * Recall (#5671, #5686): show a variable's value, or an earlier answer, inside node text with a\n * short code. One parser shared by the viewer, the dashboard, the API (\"used in\" scan) and the\n * share image.\n *\n * {{key}} a variable (or the quiz score)\n * {{answer:<node uuid>}} the answer the respondent gave to that step\n * {{answer:<node uuid>.<field>}} one field of a Details step (a CONTACT_FIELDS id or a custom field's uuid)\n * {{ref|fallback}} shown when the value is empty (1-60 characters, none of `{ } |` or a line\n * break, so there is no escaping: `{{points|}}` and `{{a|b}c}}` stay plain text)\n *\n * Capture 1 is the ref, capture 2 the fallback (undefined when there is none).\n */\nimport { VARIABLE_KEY_MAX_LENGTH, coerceVariableValue } from './variables.js';\n\n/** The longest fallback text a code carries. */\nexport const RECALL_FALLBACK_MAX_LENGTH = 60;\n\n/** How many characters a code counts as when text is measured for display (about one chip's width). */\nexport const RECALL_CHIP_DISPLAY_LENGTH = 10;\n\n/** The longest Details field id an answer code names. */\nexport const RECALL_FIELD_ID_MAX_LENGTH = 64;\n\nconst UUID = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';\nconst KEY = `[a-z][a-z0-9_]{0,${VARIABLE_KEY_MAX_LENGTH - 1}}`;\n// A Details field id is whatever the form stores (a CONTACT_FIELDS id, a custom field's uuid, or an id an API/MCP client\n// chose: `companyName`, `job-title`): any 1-64 characters except `.`, braces, `|` and whitespace. Defined ONCE, here.\nconst FIELD_ID = `[^.{}|\\\\s]{1,${RECALL_FIELD_ID_MAX_LENGTH}}`;\nconst ANSWER = `answer:(${UUID})(?:\\\\.(${FIELD_ID}))?`;\nconst REF = `answer:${UUID}(?:\\\\.${FIELD_ID})?|${KEY}`;\n\n/** Source of one recall code. Capture 1 is the ref (a variable key or an answer ref), capture 2 the optional fallback. */\nexport const RECALL_TOKEN_SOURCE = `\\\\{\\\\{(${REF})(?:\\\\|([^{}|\\\\r\\\\n]{1,${RECALL_FALLBACK_MAX_LENGTH}}))?\\\\}\\\\}`;\n\n/** Global matcher for recall codes. Stateful (`g`): use `new RegExp(RECALL_TOKEN_PATTERN)` or the helpers. */\nexport const RECALL_TOKEN_PATTERN = new RegExp(RECALL_TOKEN_SOURCE, 'g');\n\nconst ANSWER_REF = new RegExp(`^${ANSWER}$`);\nconst KEY_REF = new RegExp(`^${KEY}$`);\nconst WHOLE_TOKEN = new RegExp(`^${RECALL_TOKEN_SOURCE}$`);\n\n/**\n * A ref string as parts: `{ kind: 'variable', ref, key }` or `{ kind: 'answer', ref, nodeId, fieldId }` (`fieldId`\n * null unless a Details field). null for anything that is not a valid ref.\n */\nexport function parseRecallRef(ref) {\n if (typeof ref !== 'string') return null;\n const a = ANSWER_REF.exec(ref);\n if (a) return { kind: 'answer', ref, nodeId: a[1], fieldId: a[2] ?? null };\n if (KEY_REF.test(ref)) return { kind: 'variable', ref, key: ref };\n return null;\n}\n\n/** One whole `{{ref}}` or `{{ref|fallback}}` code as parts (`fallback` null when absent); null when it is not a valid code. */\nexport function parseRecallToken(token) {\n if (typeof token !== 'string') return null;\n const m = WHOLE_TOKEN.exec(token);\n if (!m) return null;\n const parsed = parseRecallRef(m[1]);\n return parsed ? { ...parsed, fallback: m[2] ?? null } : null;\n}\n\n/**\n * What a fallback input accepts: `{ } |` and line breaks removed, cut to 60 characters, so what is typed always fits the\n * grammar (no escaping). Trimming is the caller's choice.\n */\nexport function sanitizeRecallFallback(value) {\n return typeof value === 'string' ? value.replace(/[{}|\\r\\n]/g, '').slice(0, RECALL_FALLBACK_MAX_LENGTH) : '';\n}\n\n/**\n * The quiz keys that resolve in a `{{key}}` code without being custom variables, and the name the builder shows for each\n * (the chip and the `@` menu read this, so they can never drift).\n */\nexport const RECALL_RESERVED_LABELS = { score: 'Score', max_score: 'Max score' };\n\n/** A number without trailing zeros and at most 2 decimals; text as is; anything else blank. */\nexport function formatRecallValue(value) {\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) return '';\n return String(Math.round(value * 100) / 100);\n }\n if (typeof value === 'string') return value;\n return '';\n}\n\n/** Every distinct ref (variable key or answer ref) used in the text, in first-seen order. */\nexport function findRecallRefs(text) {\n if (typeof text !== 'string' || !text.includes('{{')) return [];\n const refs = [];\n for (const m of text.matchAll(new RegExp(RECALL_TOKEN_SOURCE, 'g'))) {\n if (!refs.includes(m[1])) refs.push(m[1]);\n }\n return refs;\n}\n\n/** Every distinct answer ref (`answer:<uuid>[.<field>]`) used in the text, in first-seen order. */\nexport function findRecallAnswerRefs(text) {\n return findRecallRefs(text).filter((r) => r.startsWith('answer:'));\n}\n\n/** Every distinct VARIABLE key used in the text, in first-seen order (answer refs are not keys; `{{points|0}}` uses `points`). */\nexport function findRecallKeys(text) {\n return findRecallRefs(text).filter((r) => !r.startsWith('answer:'));\n}\n\n/** True when the text holds a `{{key}}` code for exactly `key` (`{{answer:x}}`, `{{ptsx}}`, `{{PTS}}` do not match `pts`). */\nexport function textUsesRecallKey(text, key) {\n return findRecallKeys(text).includes(key);\n}\n\n/** True when the text recalls the answer of node `nodeId` (any of its fields). */\nexport function textUsesRecallAnswer(text, nodeId) {\n return findRecallAnswerRefs(text).some((r) => parseRecallRef(r)?.nodeId === nodeId);\n}\n\nfunction valueMatches(value, textTest) {\n if (typeof value === 'string') return textTest(value);\n if (Array.isArray(value)) return value.some((v) => valueMatches(v, textTest));\n if (value && typeof value === 'object') return Object.values(value).some((v) => valueMatches(v, textTest));\n return false;\n}\n\n/** True when any string anywhere inside the value (deep: arrays, objects) holds a `{{key}}` code. */\nexport function valueUsesRecallKey(value, key) {\n return valueMatches(value, (t) => textUsesRecallKey(t, key));\n}\n\n/** A node's respondent-facing text: its prompt, every string in its config (deep) and its live (not deleted) option labels. */\nfunction nodeTextMatches(node, textTest) {\n if (!node) return false;\n if (valueMatches(node.prompt, textTest) || valueMatches(node.config, textTest)) return true;\n return (Array.isArray(node.options) ? node.options : []).some((o) => !o?.deleted_at && valueMatches(o?.content, textTest));\n}\n\n/**\n * True when a node's respondent-facing text names `{{key}}`: its prompt, every string in its\n * config (deep) and its live (not deleted) option labels. The ONE scan behind the API's\n * Delete 409 (`used_in_text`) and the dashboard's disabled Delete.\n */\nexport function nodeUsesRecallKey(node, key) {\n return nodeTextMatches(node, (t) => textUsesRecallKey(t, key));\n}\n\n/** True when a node's respondent-facing text (same places as `nodeUsesRecallKey`) recalls the answer of node `nodeId`. */\nexport function nodeUsesRecallAnswer(node, nodeId) {\n return nodeTextMatches(node, (t) => textUsesRecallAnswer(t, nodeId));\n}\n\n/** Every distinct answer ref a node's text uses (same places as `nodeUsesRecallKey`), first-seen order. */\nexport function nodeRecallAnswerRefs(node) {\n const refs = [];\n nodeTextMatches(node, (t) => {\n for (const r of findRecallAnswerRefs(t)) if (!refs.includes(r)) refs.push(r);\n return false;\n });\n return refs;\n}\n\n/**\n * Text as segments: `{ text, recalled }`, where `recalled` is true for a value that replaced a code (so a surface can\n * bold it) and false for plain text. Same resolution rules as `interpolateRecall`, which is a join over this.\n * - A value that formats to '' shows the fallback, else blank (a blank value adds no segment).\n * - An answer ref always resolves (value, then fallback, then blank) and never shows its raw code.\n * - A variable key missing from `valuesByKey` stays as its raw code (plain text), unless the code has a fallback.\n */\nexport function interpolateRecallParts(text, valuesByKey) {\n if (typeof text !== 'string') return [];\n if (!text.includes('{{') || !valuesByKey) return text === '' ? [] : [{ text, recalled: false }];\n const parts = [];\n let last = 0;\n const push = (t, recalled) => {\n if (t === '') return;\n const prev = parts[parts.length - 1];\n if (prev && prev.recalled === recalled) prev.text += t;\n else parts.push({ text: t, recalled });\n };\n for (const m of text.matchAll(new RegExp(RECALL_TOKEN_SOURCE, 'g'))) {\n const [whole, ref, fallback] = m;\n push(text.slice(last, m.index), false);\n last = m.index + whole.length;\n const known = Object.hasOwn(valuesByKey, ref);\n if (!known && !ref.startsWith('answer:') && fallback === undefined) {\n push(whole, false);\n continue;\n }\n const value = known ? formatRecallValue(valuesByKey[ref]) : '';\n push(value !== '' ? value : (fallback ?? ''), true);\n }\n push(text.slice(last), false);\n return parts;\n}\n\n/**\n * Replace each code with its formatted value (see `interpolateRecallParts` for the rules).\n * Text with no `{{` is returned as the same string.\n */\nexport function interpolateRecall(text, valuesByKey) {\n if (typeof text !== 'string' || !text.includes('{{') || !valuesByKey) return text;\n return interpolateRecallParts(text, valuesByKey).map((p) => p.text).join('');\n}\n\n/**\n * How long text reads in the builder: each recall code counts as one chip (`RECALL_CHIP_DISPLAY_LENGTH`), not its stored\n * length (an answer chip is ~47 stored characters). For soft display limits only; hard limits count stored text.\n */\nexport function recallDisplayLength(text) {\n if (typeof text !== 'string') return 0;\n return text.replace(new RegExp(RECALL_TOKEN_SOURCE, 'g'), 'x'.repeat(RECALL_CHIP_DISPLAY_LENGTH)).length;\n}\n\nfunction optionsOf(node) {\n const list = node?.options ?? node?.node_options;\n return Array.isArray(list) ? list : [];\n}\n\n/**\n * The text an earlier answer shows when recalled. `responseData` is the answer as stored (an option id or ids, a\n * number, `{ response_type, text }`, `{ fields }`).\n * - choice / binary: the picked option labels in OPTION order, joined ', ' (the webhook `label`);\n * - scale: the number; open: typed text only (a recording is blank);\n * - details: the value of field `fieldId`;\n * - anything else: ''.\n */\nexport function recallAnswerText(node, responseData, fieldId) {\n if (!node || responseData === undefined || responseData === null) return '';\n if (node.type === 'choice' || node.type === 'binary') {\n const picked = new Set(Array.isArray(responseData) ? responseData : [responseData]);\n return optionsOf(node)\n .filter((o) => o && !o.deleted_at && picked.has(o.id) && typeof o.content === 'string')\n .map((o) => o.content)\n .join(', ');\n }\n if (node.type === 'scale') return typeof responseData === 'number' && Number.isFinite(responseData) ? String(responseData) : '';\n if (node.type === 'open') {\n return responseData.response_type === 'text' && typeof responseData.text === 'string' ? responseData.text : '';\n }\n if (node.type === 'details') {\n if (!fieldId || !Array.isArray(responseData.fields)) return '';\n const value = responseData.fields.find((f) => f?.id === fieldId)?.value;\n return typeof value === 'string' ? value : typeof value === 'number' ? String(value) : '';\n }\n return '';\n}\n\n/**\n * Values by key before anything is answered: each custom variable's base (a number\n * defaults to 0, text to blank) and a zero quiz total. For surfaces that show the\n * first screen with no respondent (the share image).\n */\nexport function startingRecallValues(variables) {\n const out = { score: 0, max_score: 0 };\n for (const v of Array.isArray(variables) ? variables : []) {\n if (!v || v.kind !== 'custom' || typeof v.key !== 'string') continue;\n const base = coerceVariableValue(v.type, v.base);\n out[v.key] = base !== undefined ? base : v.type === 'text' ? '' : 0;\n }\n return out;\n}\n","// @vid-master/config/validate\n// Shared JSON Schema validation for config and response data.\n// Supports: object, array, string, number, integer, boolean, oneOf, enum, min/max, minItems/maxItems.\n\nimport { NODE_TYPES, CONFIG_SCHEMAS, RESPONSE_SCHEMAS, OUTPUT_SCHEMAS } from './node-types.js';\n\n/**\n * Validate data against a JSON Schema subset.\n * @param {any} data\n * @param {Record<string, any>} schema\n * @returns {{ valid: boolean, errors: string[] }}\n */\nexport function validateAgainstSchema(data, schema) {\n const errors = [];\n\n if (data === null || data === undefined) {\n if (schema.required === true || (Array.isArray(schema.required) && schema.required.length > 0)) {\n errors.push('Value is required');\n }\n return { valid: errors.length === 0, errors };\n }\n\n // Const check (exact value match)\n if (schema.const !== undefined && data !== schema.const) {\n errors.push(`Expected value ${JSON.stringify(schema.const)}, got ${JSON.stringify(data)}`);\n return { valid: false, errors };\n }\n\n // Determine actual type\n const actualType = Array.isArray(data) ? 'array' : typeof data;\n\n // Type check\n if (schema.type) {\n if (schema.type === 'integer') {\n if (typeof data !== 'number' || !Number.isInteger(data)) {\n errors.push(`Expected type integer, got ${actualType}${typeof data === 'number' ? ' (non-integer)' : ''}`);\n return { valid: false, errors };\n }\n } else if (schema.type === 'array') {\n if (!Array.isArray(data)) {\n errors.push(`Expected type array, got ${actualType}`);\n return { valid: false, errors };\n }\n } else if (actualType !== schema.type) {\n errors.push(`Expected type ${schema.type}, got ${actualType}`);\n return { valid: false, errors };\n }\n }\n\n // Array validation\n if (Array.isArray(data) && (schema.type === 'array' || !schema.type)) {\n if (schema.minItems !== undefined && data.length < schema.minItems) {\n errors.push(`Array must have at least ${schema.minItems} item(s), got ${data.length}`);\n }\n if (schema.maxItems !== undefined && data.length > schema.maxItems) {\n errors.push(`Array must have at most ${schema.maxItems} item(s), got ${data.length}`);\n }\n if (schema.items) {\n for (let i = 0; i < data.length; i++) {\n const itemResult = validateAgainstSchema(data[i], schema.items);\n if (!itemResult.valid) {\n errors.push(`Item [${i}]: ${itemResult.errors.join(', ')}`);\n }\n }\n }\n }\n\n // oneOf for every data type except the typed-object case, which evaluates it\n // below (after `required`, keeping that branch's error order). Lets a schema\n // express \"string or array of strings\" (#151 choice answers).\n const isTypedObject = schema.type === 'object' && typeof data === 'object' && !Array.isArray(data);\n if (!isTypedObject && Array.isArray(schema.oneOf)) {\n const matched = schema.oneOf.some((sub) => validateAgainstSchema(data, sub).valid);\n if (!matched) {\n errors.push('Data does not match any of the allowed schemas (oneOf)');\n }\n }\n\n // Object validation\n if (isTypedObject) {\n // Required properties (array form)\n if (Array.isArray(schema.required)) {\n for (const key of schema.required) {\n if (!(key in data)) {\n errors.push(`Missing required property: ${key}`);\n }\n }\n }\n\n // oneOf\n if (Array.isArray(schema.oneOf)) {\n const matched = schema.oneOf.some((sub) => {\n const r = validateAgainstSchema(data, sub);\n return r.valid;\n });\n if (!matched) {\n errors.push('Data does not match any of the allowed schemas (oneOf)');\n }\n }\n\n // Validate known properties + reject unknown ones\n if (schema.properties) {\n for (const key in data) {\n if (schema.properties[key]) {\n const propResult = validateAgainstSchema(data[key], schema.properties[key]);\n if (!propResult.valid) {\n errors.push(`Property \"${key}\": ${propResult.errors.join(', ')}`);\n }\n } else if (!schema.additionalProperties) {\n errors.push(`Unknown property: \"${key}\"`);\n }\n }\n }\n }\n\n // String validation\n if (schema.type === 'string' && typeof data === 'string') {\n if (schema.enum && !schema.enum.includes(data)) {\n errors.push(`Value must be one of: ${schema.enum.join(', ')}`);\n }\n }\n\n // Number / integer validation (support both min/max and minimum/maximum)\n if ((schema.type === 'number' || schema.type === 'integer') && typeof data === 'number') {\n const lo = schema.minimum !== undefined ? schema.minimum : schema.min;\n const hi = schema.maximum !== undefined ? schema.maximum : schema.max;\n if (lo !== undefined && data < lo) {\n errors.push(`Value must be >= ${lo}`);\n }\n if (hi !== undefined && data > hi) {\n errors.push(`Value must be <= ${hi}`);\n }\n }\n\n return { valid: errors.length === 0, errors };\n}\n\n/**\n * Plain-language error when a choice node asks for Letters display with more\n * options than the Letters cap (#5411), else null. The A/B/C chips share one\n * row, so Letters stops at `choice.max_letters_options` while List takes the\n * full `max_options`. Shared by the API write routes and the MCP schemas so\n * the MCP never accepts what a route rejects.\n * @param {string} nodeType\n * @param {Record<string, any> | null | undefined} config effective node config\n * @param {number} count option count\n * @returns {string | null}\n */\nexport function lettersCapError(nodeType, config, count) {\n const typeDef = NODE_TYPES[nodeType];\n const cap = typeDef?.max_letters_options;\n if (cap === undefined || config?.option_display !== 'letters' || count <= cap) return null;\n return `Letters display works with up to ${cap} options, got ${count}. Use option_display \"list\" for up to ${typeDef.max_options}, or remove options.`;\n}\n\n/**\n * Plain-language error when an options count is over the node type's\n * `max_options` (#5434), else null. Split out of `validateOptions` so write\n * routes can enforce just the max rule (no min_options, Letters or length\n * checks) and `validateOptions` reports the identical message.\n * @param {string} nodeType\n * @param {number} count option count\n * @returns {string | null}\n */\nexport function maxOptionsError(nodeType, count) {\n const typeDef = NODE_TYPES[nodeType];\n if (typeDef?.max_options === undefined || count <= typeDef.max_options) return null;\n return `${nodeType} nodes allow at most ${typeDef.max_options} option(s), got ${count}`;\n}\n\n/**\n * Validate that a node's options array meets the requirements for its type.\n * Uses min_options / max_options from NODE_TYPES as the source of truth.\n * @param {string} nodeType\n * @param {Array<{ content: string }>} [options]\n * @param {Record<string, any> | null} [config] effective node config (for the Letters cap)\n * @returns {{ valid: boolean, errors: string[] }}\n */\nexport function validateOptions(nodeType, options, config) {\n const typeDef = NODE_TYPES[nodeType];\n if (!typeDef) {\n return { valid: false, errors: [`Unknown node type \"${nodeType}\"`] };\n }\n\n const errors = [];\n const count = Array.isArray(options) ? options.length : 0;\n\n if (typeDef.has_options && typeDef.min_options !== undefined && count < typeDef.min_options) {\n errors.push(`${nodeType} nodes require at least ${typeDef.min_options} option(s), got ${count}`);\n }\n\n const maxError = maxOptionsError(nodeType, count);\n if (maxError) errors.push(maxError);\n\n const lettersError = lettersCapError(nodeType, config, count);\n if (lettersError) errors.push(lettersError);\n\n if (typeDef.max_option_length !== undefined && Array.isArray(options)) {\n for (let i = 0; i < options.length; i++) {\n if (typeof options[i]?.content === 'string' && options[i].content.length > typeDef.max_option_length) {\n errors.push(`options[${i}].content must be ${typeDef.max_option_length} characters or fewer`);\n }\n }\n }\n\n return { valid: errors.length === 0, errors };\n}\n\n/**\n * Validate a node config against its CONFIG_SCHEMA.\n * @param {string} nodeType\n * @param {any} configData\n * @returns {{ valid: boolean, errors: string[] }}\n */\nexport function validateConfig(nodeType, configData) {\n const schema = CONFIG_SCHEMAS[nodeType];\n if (!schema) {\n return { valid: false, errors: [`No config schema found for type \"${nodeType}\"`] };\n }\n return validateAgainstSchema(configData, schema);\n}\n\n/**\n * Whether a node type collects a response at all, derived from RESPONSE_SCHEMAS\n * (never hand-enumerate a type list here). Terminal/system types like\n * `end_screen`, `shopping`, and `start` have no response schema - reaching one\n * is not a validation failure, it's a not-applicable case (#4097).\n * @param {string} nodeType\n * @returns {boolean}\n */\nexport function collectsResponse(nodeType) {\n return Boolean(RESPONSE_SCHEMAS[nodeType]);\n}\n\n/**\n * Validate a response against its RESPONSE_SCHEMA.\n * @param {string} nodeType\n * @param {any} responseData\n * @returns {{ valid: boolean, errors: string[] }}\n */\nexport function validateResponse(nodeType, responseData) {\n const schema = RESPONSE_SCHEMAS[nodeType];\n if (!schema) {\n return { valid: false, errors: [`No response schema found for type \"${nodeType}\"`] };\n }\n return validateAgainstSchema(responseData, schema);\n}\n\n/**\n * Validate an output against its OUTPUT_SCHEMA.\n * @param {string} nodeType\n * @param {any} outputData\n * @returns {{ valid: boolean, errors: string[] }}\n */\nexport function validateOutput(nodeType, outputData) {\n const schema = OUTPUT_SCHEMAS[nodeType];\n if (!schema) {\n return { valid: false, errors: [`No output schema for \"${nodeType}\"`] };\n }\n return validateAgainstSchema(outputData, schema);\n}\n","// @vid-master/config/form-types\n// Static form type definitions — single source of truth for all apps.\n// Workflow prose (step-by-step instructions) and craft guides remain in the\n// MCP server. This registry defines structural metadata only.\n\nimport { FEATURES } from './features.js';\nimport { NODE_TYPES } from './node-types.js';\n\nexport const FORM_TYPES = {\n quiz: {\n label: 'Quiz',\n description: 'Scored knowledge quiz with narrated video questions',\n sort_order: 1,\n category: 'assessment',\n aliases: ['trivia', 'test', 'exam'],\n variants: ['personality', 'comprehension', 'composition'],\n required_features: [],\n required_node_types: ['choice', 'end_screen'],\n default_media_style: 'video',\n guide_uri: 'clipform://guides/quiz',\n guide_description: 'Craft knowledge for writing engaging quizzes - difficulty curves, question psychology, narration style, scoring',\n discovery: [\n { key: 'topic', question: 'What topic or subject area?', fallback: 'General trivia', mode: 'all' },\n { key: 'question_count', question: 'How many questions?', fallback: '8', mode: 'all' },\n { key: 'media_style', question: 'Video with narration (recommended), images, or text only?', fallback: 'Video with narration', mode: 'full' },\n ],\n variant_discovery: {\n personality: [\n { key: 'topic', question: \"What's the theme? (Which X are you?)\", fallback: 'General personality', mode: 'all' },\n { key: 'categories', question: 'What outcome categories? (3-5 results)', fallback: 'Infer 4 categories from the theme', mode: 'full' },\n { key: 'question_count', question: 'How many questions?', fallback: '8', mode: 'all' },\n ],\n comprehension: [\n { key: 'source', question: \"What's the source material? (paste the transcript, document text, or notes)\", fallback: 'Ask the user to paste it in chat', mode: 'all' },\n { key: 'question_count', question: 'How many questions?', fallback: '8', mode: 'all' },\n { key: 'audience', question: \"Who's the audience? (kids, teens, adults)\", fallback: 'General adults', mode: 'full' },\n ],\n composition: [\n { key: 'topic', question: 'What topic? (flags, movies, geography, music...)', fallback: 'General trivia', mode: 'all' },\n { key: 'question_count', question: 'How many questions? (composition quizzes use ~1 node per question, plus one more for any optional reveal beat - 5-6 is the sweet spot)', fallback: '5', mode: 'all' },\n ],\n },\n variant_guide_uris: {\n personality: 'clipform://guides/quiz/personality',\n comprehension: 'clipform://guides/quiz/comprehension',\n composition: 'clipform://guides/quiz/composition',\n },\n variant_descriptions: {\n personality: 'Addendum for personality quizzes - category design, option weighting, outcome writing, no right/wrong answers',\n comprehension: 'Addendum for comprehension quizzes - writing questions from source material (transcript, document, notes), distractor design, audience adaptation',\n composition: 'Addendum for composition quizzes - guess formats built from rendered compositions: mechanic selection, the clue clip + answer feedback default (with an optional reveal payoff node), difficulty design',\n },\n prompt: { name: 'create-quiz', title: 'Create a Quiz', description: 'Build a scored knowledge quiz with narrated video questions' },\n },\n\n survey: {\n label: 'Survey',\n description: 'Feedback survey, NPS form, or research questionnaire',\n sort_order: 2,\n category: 'feedback',\n aliases: ['feedback', 'poll', 'nps', 'questionnaire'],\n variants: [],\n required_features: [],\n required_node_types: ['choice', 'open', 'end_screen'],\n default_media_style: 'text',\n guide_uri: 'clipform://guides/survey',\n guide_description: 'Craft knowledge for feedback surveys, NPS, and research forms - brevity, rating scales, respondent fatigue',\n discovery: [\n { key: 'topic', question: 'What are you measuring? (satisfaction, NPS, feedback on what?)', fallback: 'General satisfaction', mode: 'all' },\n { key: 'anonymous', question: 'Anonymous or identified responses?', fallback: 'Anonymous', mode: 'full' },\n ],\n variant_discovery: {},\n variant_guide_uris: {},\n variant_descriptions: {},\n prompt: { name: 'create-survey', title: 'Create a Survey', description: 'Build a feedback survey, NPS form, or research questionnaire' },\n },\n\n interview: {\n label: 'Interview',\n description: 'Async video interview, case study, or expert input collection',\n sort_order: 3,\n category: 'collection',\n aliases: ['case-study', 'callout'],\n variants: [],\n required_features: [],\n required_node_types: ['open', 'details', 'end_screen'],\n default_media_style: 'video',\n guide_uri: 'clipform://guides/interview',\n guide_description: 'Craft knowledge for building interview forms - warm-up pacing, open questions, consent, video responses',\n discovery: [\n { key: 'purpose', question: 'What are you collecting? (case studies, feedback, expert input)', fallback: 'General responses', mode: 'all' },\n { key: 'response_format', question: 'How should people respond? (video, audio, text, all)', fallback: 'All formats', mode: 'full' },\n { key: 'needs_consent', question: 'Need a consent statement?', fallback: 'Yes', mode: 'full' },\n ],\n variant_discovery: {},\n variant_guide_uris: {},\n variant_descriptions: {},\n prompt: { name: 'create-interview', title: 'Create an Interview', description: 'Build an async video interview for collecting case studies, feedback, or expert input' },\n },\n\n funnel: {\n label: 'Funnel',\n description: 'Lead qualification funnel with conditional routing',\n sort_order: 4,\n category: 'qualification',\n aliases: ['lead-gen', 'qualification', 'lead-magnet'],\n variants: [],\n required_features: ['branching', 'funnel'],\n required_node_types: ['choice', 'details', 'end_screen'],\n default_media_style: 'text',\n guide_uri: 'clipform://guides/funnel',\n guide_description: 'Craft knowledge for lead qualification funnels - planned feature, conditional routing coming soon',\n discovery: [],\n variant_discovery: {},\n variant_guide_uris: {},\n variant_descriptions: {},\n prompt: { name: 'create-funnel', title: 'Create a Funnel', description: 'Lead qualification funnels with branching logic are planned but not yet available' },\n },\n\n testimonial: {\n label: 'Testimonial',\n description: 'Video testimonial and story collection form',\n sort_order: 5,\n category: 'collection',\n aliases: ['story', 'review'],\n variants: [],\n required_features: [],\n required_node_types: ['open', 'details', 'end_screen'],\n default_media_style: 'video',\n guide_uri: 'clipform://guides/testimonial',\n guide_description: 'Craft knowledge for collecting testimonials and customer stories on video - storytelling prompts, comfort techniques, consent',\n discovery: [\n { key: 'use_case', question: 'What stories are you collecting? (customer success, employee, partner)', fallback: 'Customer success stories', mode: 'all' },\n { key: 'media_style', question: 'Video responses (recommended), audio, or text?', fallback: 'Video', mode: 'full' },\n ],\n variant_discovery: {},\n variant_guide_uris: {},\n variant_descriptions: {},\n prompt: { name: 'create-testimonial', title: 'Collect Testimonials', description: 'Build a video testimonial collection form - capture authentic customer stories on camera' },\n },\n\n application: {\n label: 'Application',\n description: 'Structured application form for jobs, programmes, or grants',\n sort_order: 6,\n category: 'collection',\n aliases: ['job-application', 'admission', 'enrollment', 'grant'],\n variants: [],\n required_features: [],\n required_node_types: ['open', 'choice', 'details', 'end_screen'],\n default_media_style: 'video',\n guide_uri: 'clipform://guides/application',\n guide_description: 'Craft knowledge for application and evaluation forms - multi-section structure, video responses for behavioural questions, screening',\n discovery: [\n { key: 'role', question: 'What role or position?', fallback: 'General application', mode: 'all' },\n ],\n variant_discovery: {},\n variant_guide_uris: {},\n variant_descriptions: {},\n prompt: { name: 'create-application', title: 'Create an Application Form', description: 'Build a structured application form with video responses for behavioural questions' },\n },\n\n booking: {\n label: 'Booking',\n description: 'Event registration, course signup, or booking form',\n sort_order: 7,\n category: 'registration',\n aliases: ['registration', 'signup', 'event', 'rsvp', 'workshop'],\n variants: [],\n required_features: [],\n required_node_types: ['details', 'choice', 'end_screen'],\n default_media_style: 'text',\n guide_uri: 'clipform://guides/booking',\n guide_description: 'Craft knowledge for event registration and booking forms - minimal friction, video welcome, confirmation flow',\n discovery: [\n { key: 'event_name', question: \"What's the event name?\", fallback: 'Event registration', mode: 'all' },\n { key: 'event_type', question: 'What type? (workshop, webinar, meetup, conference)', fallback: 'Event', mode: 'full' },\n ],\n variant_discovery: {},\n variant_guide_uris: {},\n variant_descriptions: {},\n prompt: { name: 'create-booking', title: 'Create a Booking Form', description: 'Build an event registration or booking form with a personal video welcome' },\n },\n\n intake: {\n label: 'Client Intake',\n description: 'Client intake and onboarding form for a service business',\n sort_order: 8,\n category: 'collection',\n aliases: ['client-intake', 'onboarding', 'enquiry', 'inquiry', 'new-client'],\n variants: [],\n required_features: [],\n required_node_types: ['details', 'open', 'end_screen'],\n default_media_style: 'video',\n guide_uri: 'clipform://guides/intake',\n guide_description: 'Craft knowledge for client intake and onboarding forms - a warm welcome, minimal contact capture, a video-first question about what the client needs, and a clear next step',\n discovery: [\n { key: 'use_case', question: 'What kind of business or service? (massage, coaching, personal training, agency)', fallback: 'General client intake', mode: 'all' },\n { key: 'response_format', question: 'How should people answer the open question? (video, audio, text, all)', fallback: 'All formats', mode: 'full' },\n ],\n variant_discovery: {},\n variant_guide_uris: {},\n variant_descriptions: {},\n prompt: { name: 'create-intake', title: 'Create a Client Intake Form', description: 'Build a warm client intake or onboarding form that captures contact details and what the client needs' },\n },\n\n 'lead-capture': {\n label: 'Lead Capture',\n description: 'Linear lead capture or enquiry form - turn interest into a contact with minimal friction',\n sort_order: 9,\n category: 'collection',\n aliases: ['lead', 'lead-form', 'enquiry-form', 'waitlist', 'get-a-quote'],\n variants: [],\n required_features: [],\n required_node_types: ['details', 'end_screen'],\n default_media_style: 'text',\n guide_uri: 'clipform://guides/lead-capture',\n guide_description: 'Craft knowledge for linear lead capture and enquiry forms - minimal friction, a light qualifier only if it routes follow-up, and a clear next step (no branching, no scoring)',\n discovery: [\n { key: 'use_case', question: 'What are you capturing leads for? (a service, a product, a waitlist, a quote)', fallback: 'General enquiries', mode: 'all' },\n ],\n variant_discovery: {},\n variant_guide_uris: {},\n variant_descriptions: {},\n prompt: { name: 'create-lead-capture', title: 'Create a Lead Capture Form', description: 'Build a short lead capture or enquiry form that turns interest into a contact' },\n },\n};\n\n// ---------------------------------------------------------------------------\n// Derived exports\n// ---------------------------------------------------------------------------\n\n// Availability is derived from dependencies (single source of truth): a form type\n// is active iff every required feature is enabled and every required node type is\n// active. No hand-set flag to drift - e.g. funnel auto-hides while branching is planned.\nfor (const def of Object.values(FORM_TYPES)) {\n const featuresLive = def.required_features.every((k) => FEATURES[k]?.enabled === true);\n const nodesLive = def.required_node_types.every((t) => NODE_TYPES[t]?.is_active === true);\n def.is_active = featuresLive && nodesLive;\n}\n\nexport const FORM_TYPES_LIST = Object.entries(FORM_TYPES)\n .map(([key, def]) => ({ key, ...def }))\n .sort((a, b) => a.sort_order - b.sort_order);\n\nexport const FORM_TYPE_KEYS = Object.keys(FORM_TYPES);\n\nexport const WORKFLOW_TYPES = FORM_TYPE_KEYS.filter(\n key => FORM_TYPES[key].is_active\n);\n\nexport const FORM_TYPE_ALIASES = Object.fromEntries(\n Object.entries(FORM_TYPES).flatMap(([key, def]) =>\n def.aliases.map(alias => [alias, key])\n )\n);\n\nexport const ALL_VARIANTS = Object.entries(FORM_TYPES).flatMap(\n ([, def]) => def.variants\n);\n\nexport function resolveFormType(input) {\n const normalised = input.toLowerCase().trim();\n if (FORM_TYPES[normalised]) return normalised;\n return FORM_TYPE_ALIASES[normalised] ?? null;\n}\n\nexport function getDiscoveryParams(formType, variant, mode = 'full') {\n const def = FORM_TYPES[formType];\n if (!def) return [];\n\n let params;\n if (variant && def.variant_discovery?.[variant]) {\n params = def.variant_discovery[variant];\n } else {\n params = def.discovery;\n }\n\n if (mode === 'demo') {\n return params.filter(p => p.mode === 'all');\n }\n return params;\n}\n\nexport function isFormTypeAvailable(formType, features) {\n const def = FORM_TYPES[formType];\n if (!def || !def.is_active) return false;\n return def.required_features.every(\n featureKey => features[featureKey]?.enabled === true\n );\n}\n\nexport function getAvailableFormTypes(features) {\n return FORM_TYPE_KEYS.filter(key => isFormTypeAvailable(key, features));\n}\n","/**\n * Anonymous-MCP safety floor limits (#4847). An \"unclaimed anonymous MCP\n * workspace\" is one linked via bot_linked_accounts(platform = 'mcp') whose\n * uid is still an anonymous Supabase user (apps/api/src/mcp/anon-workspace.ts).\n */\n\n/** Completed responses an unclaimed anonymous-MCP form accepts before the limit screen. */\nexport const ANON_MCP_RESPONSE_CAP = 3;\n\n/**\n * Started (viewed or in-progress) sessions are bounded at this multiple of the\n * cap, so abandoned sessions cannot be used for unlimited uploads. The cap is\n * enforced at session init, answer writes and completion, but the count is not\n * atomic: concurrent inits can briefly overshoot it (a strict cap needs a DB function).\n */\nexport const ANON_MCP_STARTED_SESSION_MULTIPLE = 5;\n\n/** Max started sessions per unclaimed anonymous-MCP form. */\nexport const ANON_MCP_STARTED_SESSION_CAP =\n ANON_MCP_RESPONSE_CAP * ANON_MCP_STARTED_SESSION_MULTIPLE;\n\n/** Days a live, unclaimed anonymous-MCP form stays published (matches the claim-link TTL). */\nexport const ANON_MCP_LIVE_TTL_DAYS = 7;\n\n/**\n * Upload sessions (stream-start / signed-url) one form session may open on an\n * unclaimed anonymous-MCP form. Best-effort and per API process only (not shared\n * across instances); the completed cap is the real bound.\n */\nexport const ANON_MCP_UPLOADS_PER_SESSION = 10;\n","// @vid-master/config/logic-chain\n// Pure, branch-aware graph helpers over node_logic actions - no DB, no React\n// Flow. Moved out of apps/api/src/lib/logic-chain.ts (#1058) so a single\n// implementation backs the DB-backed chain ops; apps/api re-exports these so\n// existing callers/imports are unchanged.\n//\n// The chain helpers historically read/wrote only `actions[0]`, which silently\n// orphaned every other edge on a branched node (#704). These pure functions\n// treat a node's logic as the multi-edge graph it is.\n\nimport { isOptionEdge, isInactiveOptionEdge } from './logic-types.js';\n\n/**\n * Distinct outgoing target node-ids from a node's actions, in action order.\n * When `node` is given, parked option edges (branching off) are skipped so the\n * walk follows only the ACTIVE graph; omit it to treat every edge as live.\n *\n * @param {import('./logic-types.js').LogicAction[] | undefined} actions\n * @param {import('./logic-types.js').BranchingNode} [node]\n * @returns {string[]}\n */\nexport function outgoingTargets(actions, node) {\n const out = [];\n for (const a of actions ?? []) {\n if (node && isInactiveOptionEdge(node, a)) continue;\n const v = a?.details?.to?.value;\n if (v && !out.includes(v)) out.push(v);\n }\n return out;\n}\n\n/**\n * A node is \"branched\" when its logic routes more than one way: per-option\n * (an option-typed condition var) or to more than one distinct target. A node\n * with no logic, or a single node-level jump, is linear. With `node` given, a\n * choice/binary node whose branching is off is linear (its parked option edges\n * don't count) even though the parked edges still exist in node_logic.\n *\n * @param {import('./logic-types.js').LogicAction[] | undefined} actions\n * @param {import('./logic-types.js').BranchingNode} [node]\n * @returns {boolean}\n */\nexport function isBranched(actions, node) {\n if (!actions || actions.length === 0) return false;\n const active = node ? actions.filter((a) => !isInactiveOptionEdge(node, a)) : actions;\n const routesByOption = active.some((a) => isOptionEdge(a));\n return routesByOption || outgoingTargets(active).length > 1;\n}\n\n/**\n * The default (fallback) target of a node: the target of its node-level action\n * (\"everything else -> X\"), else the first action's target, else null when the\n * node is a chain tail / terminal.\n *\n * @param {import('./logic-types.js').LogicAction[] | undefined} actions\n * @returns {import('./logic-types.js').LogicActionDetails['to'] | null}\n */\nexport function defaultTarget(actions) {\n if (!actions || actions.length === 0) return null;\n const nodeLevel = actions.find((a) => {\n const vars = a.condition?.vars;\n return !!vars && vars.length > 0 && vars.every((v) => v.type === 'node');\n });\n return (nodeLevel ?? actions[0])?.details?.to ?? null;\n}\n\n/**\n * Order nodes by BFS from the start node, following ALL outgoing edges (not\n * just the first). Unreachable nodes are appended in stable input order so the\n * caller still receives every node - branched forms used to come back\n * mis-ordered and missing whole branches.\n *\n * @template {{ id: string, type: string, config?: object }} T\n * @param {T[]} nodes\n * @param {Map<string, import('./logic-types.js').LogicAction[]>} logicByNode\n * @returns {T[]}\n */\nexport function bfsOrder(nodes, logicByNode) {\n const byId = new Map(nodes.map((n) => [n.id, n]));\n const ordered = [];\n const seen = new Set();\n\n const start = nodes.find((n) => n.type === 'start');\n if (start) {\n const queue = [start.id];\n while (queue.length) {\n const id = queue.shift();\n if (seen.has(id)) continue;\n seen.add(id);\n const node = byId.get(id);\n if (node) ordered.push(node);\n for (const target of outgoingTargets(logicByNode.get(id), node)) {\n if (!seen.has(target) && byId.has(target)) queue.push(target);\n }\n }\n }\n\n // Append anything the start can't reach (parked/draft branches) so the full\n // node set is always returned, reachable-first.\n for (const node of nodes) if (!seen.has(node.id)) ordered.push(node);\n return ordered;\n}\n\n/**\n * Rewrites for deleting `nodeId`: every action across every node that targets\n * it is re-pointed at the deleted node's default target, so no incoming edge is\n * left dangling. If the deleted node has no default target (it was a tail /\n * terminal), the incoming action is dropped instead. Returns only the entries\n * that changed.\n *\n * @param {Array<{ node_id: string, actions: import('./logic-types.js').LogicAction[] }>} allLogic\n * @param {string} nodeId\n * @returns {Array<{ node_id: string, actions: import('./logic-types.js').LogicAction[] }>}\n */\nexport function computeRemovalRewrites(allLogic, nodeId) {\n const target = defaultTarget(\n allLogic.find((e) => e.node_id === nodeId)?.actions\n );\n const changes = [];\n\n for (const entry of allLogic) {\n if (entry.node_id === nodeId) continue;\n let changed = false;\n const next = [];\n for (const action of entry.actions ?? []) {\n if (action?.details?.to?.value === nodeId) {\n changed = true;\n // Re-point to the deleted node's default target - unless there is no\n // default, or doing so would create a self-loop (a 2-cycle through the\n // deleted node), in which case drop the edge.\n if (target && target.value !== entry.node_id) {\n next.push({ ...action, details: { to: { ...target } } });\n }\n } else {\n next.push(action);\n }\n }\n if (changed) changes.push({ node_id: entry.node_id, actions: next });\n }\n return changes;\n}\n","// @vid-master/config/guide\n// Template walkthrough notes (#6269): a short note on a node of an outbound\n// template, shown as a builder tour step when someone opens their copy. The\n// note rides in `node.config.guide`, which save_form copies verbatim, so no\n// migration. Authoring is dark (FEATURES.template_walkthrough); `guide` is in\n// NO config_schema, so no public surface derived from those schemas names it.\n//\n// Shape: node.config.guide = { tour?: { title, body, anchor? }, intro?: { title, body }, checklist?: ChecklistItem[] }.\n// `intro` is the card shown before the first note (the first one in form order wins;\n// Start is read-only, so it goes on the first noted node). `checklist` (#6275) is the\n// copy's getting-started list, written per company. All three go through the same\n// merge and strip.\n\nimport { bfsOrder } from './logic-chain.js';\nimport { NODE_TYPES } from './node-types.js';\nimport { FEATURES } from './features.js';\nimport { INTEGRATION_CATALOG } from './integration-catalog.js';\n\nexport const GUIDE_CONFIG_KEY = 'guide';\n\nexport const GUIDE_LIMITS = Object.freeze({\n titleMax: 60,\n bodyMax: 280,\n maxTourSteps: 5,\n maxChecklistItems: 6,\n // The getting-started card is 288px wide and its rows wrap: about two lines each at these sizes (#6275).\n checklistLabelMax: 40,\n // Stored and validated, but not shown since #6299: the getting-started list renders labels only.\n checklistDescriptionMax: 80,\n});\n\n/** `node`: the step points at its own node. `share`: the closing step points at the Share button. */\nexport const GUIDE_TOUR_ANCHORS = Object.freeze(['node', 'share']);\n\n/**\n * Named parts of a node a note can point at (#6286). The node card marks each with\n * `data-guide-section=\"<name>\"`. `media`, `prompt` and `body` come from the NODE_TYPES\n * flags; GUIDE_NODE_SECTIONS adds the type-specific ones.\n */\nexport const GUIDE_SECTIONS = Object.freeze(['media', 'prompt', 'body', 'formats', 'options']);\n\nexport const GUIDE_NODE_SECTIONS = Object.freeze({ open: Object.freeze(['formats']), choice: Object.freeze(['options']) });\n\n/** The sections a node type has, in card order. Unknown types and Start (no card body to point at) get none. */\nexport function guideSectionsFor(nodeType) {\n const def = NODE_TYPES[nodeType];\n if (!def || nodeType === 'start') return [];\n const sections = [];\n if (def.supports_media === true) sections.push('media');\n if (def.supports_prompt === true) sections.push('prompt');\n sections.push('body');\n return [...sections, ...(GUIDE_NODE_SECTIONS[nodeType] ?? [])];\n}\n\n/**\n * What a company checklist item can ask for (#6275). Each is an ACTIVATION_STEP_KINDS\n * entry the builder ticks from real state. `record_video` is about the node it sits on;\n * the others are workspace-wide, so they sit on any node (by convention the End screen).\n */\nexport const COMPANY_CHECKLIST_KINDS = Object.freeze(['record_video', 'preview', 'connect', 'go_live', 'claim_account']);\n\nconst GUIDE_KEYS = ['tour', 'intro', 'checklist'];\nconst TOUR_KEYS = ['title', 'body', 'anchor'];\nconst INTRO_KEYS = ['title', 'body'];\nconst CHECKLIST_ITEM_KEYS = ['kind', 'label', 'description', 'integration'];\n\n/**\n * Integrations a `connect` item may name: native, connected in-app, and globally live\n * (`integration_<slug>` enabled). An allowlist-only one is left out: a copy lives in\n * another workspace, where it would show Coming Soon.\n */\nexport function checklistConnectableIntegrations() {\n return Object.entries(INTEGRATION_CATALOG)\n .filter(([slug, def]) => def.kind === 'native' && def.feature === `integration_${slug}` && FEATURES[def.feature]?.enabled === true)\n .map(([slug]) => slug);\n}\n\nfunction isPlainObject(value) {\n return !!value && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction checkText(value, field, max) {\n if (typeof value !== 'string') return { error: `guide.${field} must be a string` };\n const text = value.trim();\n if (text.length === 0 || text.length > max) return { error: `guide.${field} must be 1 to ${max} characters` };\n return { text };\n}\n\n/** One tour note, trimmed. `anchor` is kept only when sent. */\nfunction validateTour(tour, nodeType) {\n if (!isPlainObject(tour)) return { ok: false, error: 'guide.tour must be an object with a title and a body' };\n const unknown = Object.keys(tour).find((k) => !TOUR_KEYS.includes(k));\n if (unknown) return { ok: false, error: `guide.tour supports only: ${TOUR_KEYS.join(', ')}` };\n const title = checkText(tour.title, 'tour.title', GUIDE_LIMITS.titleMax);\n if (title.error) return { ok: false, error: title.error };\n const body = checkText(tour.body, 'tour.body', GUIDE_LIMITS.bodyMax);\n if (body.error) return { ok: false, error: body.error };\n if (tour.anchor !== undefined) {\n const allowed = [...GUIDE_TOUR_ANCHORS, ...guideSectionsFor(nodeType)];\n if (!allowed.includes(tour.anchor)) {\n return { ok: false, error: `guide.tour.anchor must be one of: ${allowed.join(', ')}` };\n }\n }\n const value = { title: title.text, body: body.text };\n if (tour.anchor !== undefined) value.anchor = tour.anchor;\n return { ok: true, value };\n}\n\n/** The intro card, trimmed. Same limits as a note; it points at nothing. */\nfunction validateIntro(intro) {\n if (!isPlainObject(intro)) return { ok: false, error: 'guide.intro must be an object with a title and a body' };\n const unknown = Object.keys(intro).find((k) => !INTRO_KEYS.includes(k));\n if (unknown) return { ok: false, error: `guide.intro supports only: ${INTRO_KEYS.join(', ')}` };\n const title = checkText(intro.title, 'intro.title', GUIDE_LIMITS.titleMax);\n if (title.error) return { ok: false, error: title.error };\n const body = checkText(intro.body, 'intro.body', GUIDE_LIMITS.bodyMax);\n if (body.error) return { ok: false, error: body.error };\n return { ok: true, value: { title: title.text, body: body.text } };\n}\n\n/**\n * One checklist item, trimmed. `nodeType` is the type of the node it sits on: a\n * `record_video` item needs one that carries media.\n */\nfunction validateChecklistItem(item, index, nodeType) {\n const at = `guide.checklist[${index}]`;\n if (!isPlainObject(item)) return { ok: false, error: `${at} must be an object with a kind and a label` };\n const unknown = Object.keys(item).find((k) => !CHECKLIST_ITEM_KEYS.includes(k));\n if (unknown) return { ok: false, error: `${at} supports only: ${CHECKLIST_ITEM_KEYS.join(', ')}` };\n if (!COMPANY_CHECKLIST_KINDS.includes(item.kind)) {\n return { ok: false, error: `${at}.kind must be one of: ${COMPANY_CHECKLIST_KINDS.join(', ')}` };\n }\n if (typeof item.label !== 'string') return { ok: false, error: `${at}.label must be a string` };\n const label = item.label.trim();\n if (label.length === 0 || label.length > GUIDE_LIMITS.checklistLabelMax) {\n return { ok: false, error: `${at}.label must be 1 to ${GUIDE_LIMITS.checklistLabelMax} characters` };\n }\n let description;\n if (item.description !== undefined) {\n if (typeof item.description !== 'string') return { ok: false, error: `${at}.description must be a string` };\n description = item.description.trim();\n if (description.length > GUIDE_LIMITS.checklistDescriptionMax) {\n return { ok: false, error: `${at}.description must be at most ${GUIDE_LIMITS.checklistDescriptionMax} characters` };\n }\n }\n if (item.kind === 'record_video' && NODE_TYPES[nodeType]?.supports_media !== true) {\n return { ok: false, error: `${at}: record_video needs a step that can carry a video` };\n }\n if (item.kind === 'connect') {\n const connectable = checklistConnectableIntegrations();\n if (!connectable.includes(item.integration)) {\n return { ok: false, error: `${at}.integration must be a live integration: ${connectable.join(', ')}` };\n }\n } else if (item.integration !== undefined) {\n return { ok: false, error: `${at}.integration is only for a connect item` };\n }\n const value = { kind: item.kind, label };\n if (description) value.description = description;\n if (item.kind === 'connect') value.integration = item.integration;\n return { ok: true, value };\n}\n\n/** A checklist write: an array (empty deletes it, like null). */\nfunction validateChecklist(checklist, nodeType) {\n if (!Array.isArray(checklist)) return { ok: false, error: 'guide.checklist must be an array of items, or null' };\n if (checklist.length > GUIDE_LIMITS.maxChecklistItems) {\n return { ok: false, error: `guide.checklist supports at most ${GUIDE_LIMITS.maxChecklistItems} items` };\n }\n const items = [];\n for (let i = 0; i < checklist.length; i += 1) {\n const item = validateChecklistItem(checklist[i], i, nodeType);\n if (!item.ok) return item;\n items.push(item.value);\n }\n return { ok: true, value: items.length > 0 ? items : null };\n}\n\n/**\n * Validate a `guide` write (a patch: `tour: null`, `intro: null` or `checklist: null`\n * deletes that key). Trims the text, enforces GUIDE_LIMITS, the anchor and kind enums, and rejects\n * any other key. `nodeType` is the type of the node being written: a `record_video`\n * checklist item needs one that carries media.\n * Returns `{ ok: true, value }` or `{ ok: false, error }`.\n */\nexport function validateNodeGuide(value, { nodeType } = {}) {\n if (!isPlainObject(value)) return { ok: false, error: 'guide must be an object' };\n const unknown = Object.keys(value).find((k) => !GUIDE_KEYS.includes(k));\n if (unknown) return { ok: false, error: `guide supports only: ${GUIDE_KEYS.join(', ')}` };\n const out = {};\n if ('tour' in value) {\n if (value.tour === null) {\n out.tour = null;\n } else {\n const tour = validateTour(value.tour, nodeType);\n if (!tour.ok) return tour;\n out.tour = tour.value;\n }\n }\n if ('intro' in value) {\n if (value.intro === null) {\n out.intro = null;\n } else {\n const intro = validateIntro(value.intro);\n if (!intro.ok) return intro;\n out.intro = intro.value;\n }\n }\n if ('checklist' in value) {\n if (value.checklist === null) {\n out.checklist = null;\n } else {\n const checklist = validateChecklist(value.checklist, nodeType);\n if (!checklist.ok) return checklist;\n out.checklist = checklist.value;\n }\n }\n return { ok: true, value: out };\n}\n\n/**\n * One-level merge of a validated guide patch into the stored guide, so `tour`\n * and `checklist` stay independent (update-node's own merge replaces nested\n * objects wholesale). A null sub-key deletes it; an empty guide is null.\n */\nexport function mergeNodeGuide(existing, patch) {\n const merged = isPlainObject(existing) ? { ...existing } : {};\n if (isPlainObject(patch)) {\n for (const [key, value] of Object.entries(patch)) {\n if (value === null) delete merged[key];\n else merged[key] = value;\n }\n }\n return Object.keys(merged).length > 0 ? merged : null;\n}\n\n/** The config without `guide` (the same object when it has none). */\nexport function stripNodeGuide(config) {\n if (!isPlainObject(config) || !(GUIDE_CONFIG_KEY in config)) return config;\n const { [GUIDE_CONFIG_KEY]: _guide, ...rest } = config;\n return rest;\n}\n\n/**\n * The walkthrough steps of a form, from its live nodes' notes: in BFS order\n * from Start (unreachable nodes after), one step per valid note, the single\n * `share` step last (the first one in that order wins), capped at\n * GUIDE_LIMITS.maxTourSteps including it. A note on a node that is not in\n * `nodes` (or is deleted) never shows, and an invalid note is dropped.\n *\n * @param {Array<{ id: string, type: string, config?: object | null, deleted_at?: string | null }>} nodes\n * @param {Map<string, import('./logic-types.js').LogicAction[]>} logicByNode\n * @returns {Array<{ node_id: string, node_type: string, title: string, body: string, anchor: string }>}\n */\nexport function buildTemplateTourSteps(nodes, logicByNode) {\n const ordered = liveInFormOrder(nodes, logicByNode);\n const steps = [];\n let closing = null;\n for (const node of ordered) {\n const raw = isPlainObject(node.config) && isPlainObject(node.config[GUIDE_CONFIG_KEY]) ? node.config[GUIDE_CONFIG_KEY].tour : undefined;\n if (raw == null) continue;\n // A stored section the type no longer has (a type change) falls back to the whole node.\n const stale = isPlainObject(raw) && GUIDE_SECTIONS.includes(raw.anchor) && !guideSectionsFor(node.type).includes(raw.anchor);\n const tour = validateTour(stale ? { ...raw, anchor: 'node' } : raw, node.type);\n if (!tour.ok) continue;\n const step = { node_id: node.id, node_type: node.type, title: tour.value.title, body: tour.value.body, anchor: tour.value.anchor ?? 'node' };\n if (step.anchor === 'share') {\n if (!closing) closing = step;\n } else {\n steps.push(step);\n }\n }\n const cap = GUIDE_LIMITS.maxTourSteps;\n return closing ? [...steps.slice(0, cap - 1), closing] : steps.slice(0, cap);\n}\n\n/**\n * The company checklist of a form (#6275), from its live nodes' `guide.checklist`: nodes\n * in the same BFS order as the tour steps, then array order within a node; an invalid\n * item is dropped (a type change can leave a `record_video` on a node without media, a\n * catalog change can take an integration dark) and the list is capped at\n * GUIDE_LIMITS.maxChecklistItems. An item on a node not in `nodes` (or deleted) never shows.\n * Ids are `company:<node_id>:<index in the node's list>`, so they stay put when another\n * item is dropped. A `record_video` item carries `baseline_media_id`: the node's media\n * that came with the copy (`baselineMediaByNode`), which never counts as the owner's own.\n *\n * @param {Array<{ id: string, type: string, config?: object | null, deleted_at?: string | null }>} nodes\n * @param {Map<string, import('./logic-types.js').LogicAction[]>} logicByNode\n * @param {Map<string, string | null>} [baselineMediaByNode]\n */\nexport function buildTemplateChecklist(nodes, logicByNode, baselineMediaByNode) {\n const ordered = liveInFormOrder(nodes, logicByNode);\n const baselines = baselineMediaByNode instanceof Map ? baselineMediaByNode : new Map();\n const items = [];\n for (const node of ordered) {\n const raw = isPlainObject(node.config) && isPlainObject(node.config[GUIDE_CONFIG_KEY]) ? node.config[GUIDE_CONFIG_KEY].checklist : undefined;\n if (!Array.isArray(raw)) continue;\n raw.forEach((entry, index) => {\n const checked = validateChecklistItem(entry, index, node.type);\n if (!checked.ok) return;\n const item = { id: `company:${node.id}:${index}`, node_id: node.id, ...checked.value };\n if (item.kind === 'record_video') item.baseline_media_id = baselines.get(node.id) ?? null;\n items.push(item);\n });\n }\n return items.slice(0, GUIDE_LIMITS.maxChecklistItems);\n}\n\n/**\n * The walkthrough's intro card: the first valid `guide.intro` in the same order as\n * the steps (BFS from Start), or null (the builder shows its plain default). It\n * never counts as a step.\n *\n * @param {Array<{ id: string, type: string, config?: object | null, deleted_at?: string | null }>} nodes\n * @param {Map<string, import('./logic-types.js').LogicAction[]>} logicByNode\n * @returns {{ title: string, body: string } | null}\n */\nexport function buildTemplateTourIntro(nodes, logicByNode) {\n for (const node of liveInFormOrder(nodes, logicByNode)) {\n const raw = isPlainObject(node.config) && isPlainObject(node.config[GUIDE_CONFIG_KEY]) ? node.config[GUIDE_CONFIG_KEY].intro : undefined;\n if (raw == null) continue;\n const intro = validateIntro(raw);\n if (intro.ok) return intro.value;\n }\n return null;\n}\n\nfunction liveInFormOrder(nodes, logicByNode) {\n const live = (Array.isArray(nodes) ? nodes : []).filter((n) => n && typeof n.id === 'string' && !n.deleted_at);\n return bfsOrder(live, logicByNode instanceof Map ? logicByNode : new Map());\n}\n","import { FEATURES, getLiveFeatures, ANNOUNCE_PALETTES } from './features.js';\nimport { HELP_TOPICS, buildHelpLinks } from './help-links.js';\nimport { NODE_TYPES as NODE_TYPE_DEFS, CONSENT_TYPES } from './node-types.js';\nimport { RECALL_TOKEN_SOURCE, RECALL_RESERVED_LABELS, parseRecallRef } from './recall.js';\n\n// @vid-master/config - Essential shared configuration\n\n/**\n * Environment Detection\n * Automatically detects dev/localhost vs production\n */\nconst isServer = typeof window === 'undefined';\nconst isBrowser = typeof window !== 'undefined';\n\n// Detect localhost/development environment\nconst isLocalhost = isBrowser && (\n window.location.hostname === 'localhost' ||\n window.location.hostname === '127.0.0.1' ||\n window.location.hostname.includes('local')\n);\n\nconst isDevelopment = isServer\n ? process.env.NODE_ENV !== 'production'\n : isLocalhost;\n\nexport const ENV = {\n isDevelopment,\n isProduction: !isDevelopment,\n isLocalhost: isDevelopment, // alias for clarity\n};\n\n/**\n * Domain the dashboard auth cookies USED to be written on (#5528). Auth\n * cookies are now host-only (no Domain), so a form owner's session is never\n * sent to or readable on form pages on the apex. This is kept ONLY to expire\n * the old domain-wide cookies: a cookie is deleted only by a write with the\n * same name, Domain and Path.\n * undefined in dev (browsers reject explicit domain on localhost).\n */\nexport const LEGACY_AUTH_COOKIE_DOMAIN = ENV.isDevelopment ? undefined : '.clipform.io';\n\n// `sb-<ref>-auth-token`, its `.N` chunks, and `-code-verifier` (PKCE), as\n// written by @supabase/ssr before the session cookie got its own name.\nconst LEGACY_AUTH_COOKIE_RE = /^sb-.+-auth-token(?:-code-verifier)?(?:\\.\\d+)?$/;\n\n/** True for a pre-#5528 Supabase auth cookie name (see LEGACY_AUTH_COOKIE_DOMAIN). */\nexport function isLegacyAuthCookie(name) {\n return LEGACY_AUTH_COOKIE_RE.test(name);\n}\n\n/**\n * Browser is accessing the app via the Cloudflare dev tunnel\n * (e.g. dashboard-dev.smith-forge.com → routes to local Next.js).\n * In that case browser fetches must use the matching tunnel hostnames,\n * because the browser cannot reach localhost on the dev's machine.\n */\nconst isTunnelBrowser = isBrowser &&\n window.location.hostname.endsWith('.smith-forge.com');\n\n/**\n * Production origins - the single source of truth for Clipform's public URLs.\n * getUrls() returns these in prod (dev/tunnel branches override). Embed adapters\n * that run on third-party platforms and can't import this package (apps/embeds/*,\n * apps/shopify) hardcode these origins; they're pinned to this value by\n * apps/api/src/__tests__/lib/embed-origin-parity.test.ts so a domain change\n * can't silently skip an adapter.\n */\nexport const PROD_URLS = {\n marketing: 'https://www.clipform.io',\n // Dedicated CDN host for the embed SDK, decoupled from the marketing deploy\n // (ships in seconds via packages/embed-sdk `deploy:cf`). www.clipform.io/embed.js\n // stays as the legacy bridge until all installs migrate here.\n embed: 'https://js.clipform.io',\n dashboard: 'https://app.clipform.io',\n viewer: 'https://clipform.io',\n api: 'https://api.clipform.io',\n // Dedicated subdomain for the remote MCP server. Same Render service\n // as `api`, just routed by Host header. Token audience is bound here.\n mcp: 'https://mcp.clipform.io',\n docs: 'https://clipform.io/docs',\n};\n\nexport function getUrls() {\n if (isTunnelBrowser) {\n return {\n marketing: 'https://marketing-dev.smith-forge.com',\n // Dev/tunnel: the marketing dev server 308-redirects /embed.js to js.clipform.io\n // (public/embed.js was retired in #1288), so embeds load the live SDK.\n embed: 'https://marketing-dev.smith-forge.com',\n dashboard: 'https://dashboard-dev.smith-forge.com',\n viewer: 'https://viewer-dev.smith-forge.com',\n api: 'https://api-dev.smith-forge.com',\n mcp: 'https://api-dev.smith-forge.com/mcp',\n docs: 'https://clipform.io/docs',\n };\n }\n\n if (ENV.isDevelopment) {\n // Per-worktree overrides: a parallel worktree can run its own full stack on\n // a distinct port block by setting NEXT_PUBLIC_*_URL in its .env.local (plus\n // a matching `-p` / PORT). Without these the apps resolve each other at the\n // base ports below and would cross-wire to another worktree's servers.\n // Direct `process.env.NEXT_PUBLIC_*` reads (not destructured) so Next inlines\n // them into client bundles - every app that imports this package client-side\n // transpiles it (see each app's next.config transpilePackages).\n const api = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3003';\n return {\n marketing: process.env.NEXT_PUBLIC_MARKETING_URL || 'http://localhost:3002',\n // Local: the marketing dev server redirects /embed.js to js.clipform.io\n // (public/embed.js was retired in #1288), so embeds load the live SDK.\n embed: process.env.NEXT_PUBLIC_MARKETING_URL || 'http://localhost:3002',\n dashboard: process.env.NEXT_PUBLIC_DASHBOARD_URL || 'http://localhost:3000',\n viewer: process.env.NEXT_PUBLIC_VIEWER_URL || 'http://localhost:3001',\n api,\n // No separate MCP host in dev - tools live on the api subpath.\n mcp: api + '/mcp',\n // The docs app serves under basePath /docs (matching prod\n // clipform.io/docs), so the dev URL must include it too.\n docs: process.env.NEXT_PUBLIC_DOCS_URL || 'http://localhost:3004/docs',\n };\n }\n\n // Fresh copy so callers can't mutate the shared PROD_URLS source of truth.\n return { ...PROD_URLS };\n}\n\n/** Public changelog page (generated from FEATURES). Dev-aware; the trailing slash matches marketing's `trailingSlash`. */\nexport function changelogUrl() {\n return `${getUrls().marketing}/changelog/`;\n}\n\n/** The remote MCP server's two surfaces (#6241): `forms` (forms and results) and `all` (every tool, media included). */\nexport const MCP_SURFACES = ['forms', 'all'];\n\n/**\n * The remote MCP server URL an AI client connects to (#6241), env-resolved\n * off getUrls().mcp (`https://mcp.clipform.io` in prod, `<api>/mcp` in dev\n * and on the tunnel), never hardcoded. `forms` is the forms-and-results\n * surface at `/forms`, the one the Claude directory listing uses; `all` is\n * the bare URL with every tool (apps/api/src/mcp/path-match.ts). Throws on\n * an unknown surface so a caller can't hand a client a dead URL.\n */\nexport function mcpServerUrl(surface) {\n if (!MCP_SURFACES.includes(surface)) {\n throw new Error(`mcpServerUrl: unknown surface \"${surface}\" - must be one of ${MCP_SURFACES.join(', ')}`);\n }\n const base = getUrls().mcp;\n return surface === 'forms' ? `${base}/forms` : base;\n}\n\n/**\n * Core business information - UPDATE THESE AS NEEDED\n */\nexport const BUSINESS = {\n name: \"Clipform\",\n tagline: \"Video-Driven Form Builder\",\n description:\n \"Create engaging forms that combine video content with interactive questions. Capture authentic responses with text, audio, or video recordings.\",\n shortDescription:\n \"Interactive video forms that capture authentic responses. Build engaging forms in minutes.\",\n domain: \"clipform.io\",\n email: {\n support: \"support@clipform.io\",\n sales: \"sales@clipform.io\",\n hello: \"hello@clipform.io\",\n founder: \"andy@clipform.io\",\n // Inbound form-builder address (Cloudflare Email Routing -> email-inbound\n // worker). Also the Reply-To on bot replies so a reply reaches the bot.\n new: \"new@clipform.io\",\n // Vulnerability disclosure inbox (#4011) - advertised in security.txt\n // (RFC 9116) and the docs disclosure policy.\n security: \"security@clipform.io\",\n },\n urls: getUrls(),\n};\n\n/**\n * Two-tier video delivery threshold (#1015): a video at/above this size goes to\n * Mux (adaptive HLS); below it it's stored direct in Supabase. The\n * API gate (`apps/api/src/lib/video-delivery.ts`) and the uploader client both\n * read this so the client knows whether to send bytes through the API (direct)\n * or straight to Mux (large). Single source - never hardcode the threshold.\n *\n * Set to 20MB from real data (#1495): the old 10MB cap sent ~half of uploads to\n * Mux purely for being big. A clip up to VIDEO_COMPRESS_MAX_SECONDS (43s)\n * compresses to under 20MB at the 3.5Mbps target (#1512).\n *\n * Not a playback cutoff: the #5887 lab found start time and stalls follow\n * bitrate against the connection, not size or length (a 5 min 3.5 Mbps clip\n * starts as fast direct as a 10s one). It stays for two other reasons, both\n * retired by #6136: bytes at/over it upload straight from the browser to Mux,\n * so the API never has them; and nothing re-encodes the served original on the\n * server (only a lite fallback copy, #6044), so a file this big is almost\n * always a full-bitrate camera original that would stall if served as-is,\n * which Mux's transcode fixes.\n */\nexport const MEDIA_DIRECT_MAX_BYTES = 20 * 1024 * 1024; // 20 MB\n\n/**\n * Product-level cap on any still image, whatever the source (multipart\n * upload, phone upload, or a caller/model-supplied URL). Every image\n * ingest path (apps/api's create-media.ts, the node upload route, the\n * phone-upload page) and the dashboard's own client-side pre-check\n * (MediaModal) read this single source rather than hardcoding 10MB.\n */\nexport const MEDIA_IMAGE_MAX_BYTES = 10 * 1024 * 1024; // 10 MB\n\n/**\n * What makes a good custom draw diagram (#5210, #5052). One sentence shared by the\n * builder's upload hint, the MCP craft line (packages/mcp-content) and the help docs.\n */\nexport const DRAW_DIAGRAM_SPEC = `PNG with simple dark outlines on a light or transparent background (no shading or text), portrait, at least 1000px wide. Up to ${Math.round(MEDIA_IMAGE_MAX_BYTES / (1024 * 1024))}MB.`;\n\n/**\n * Product-level cap on a consent-agreement PDF (#4525), whatever the source\n * (multipart upload or a caller/model-supplied URL).\n */\nexport const MEDIA_DOCUMENT_MAX_BYTES = 20 * 1024 * 1024; // 20 MB\n\n/**\n * Hard ceiling on ANY single object written to Supabase storage, in bytes.\n *\n * This is not our choice - it is the project-global storage limit imposed by the\n * Supabase plan, and it OVERRIDES every per-bucket `file_size_limit` declared in\n * `supabase/config.toml` at upload time. Offering the user more than this just\n * produces an upload that passes every client check and then dies at the storage\n * layer (#2556).\n *\n * Only applies to the Supabase destination. Mux-bound uploads are unaffected and\n * keep their own, larger limits.\n *\n * Raising it means lifting the plan ceiling in the Supabase dashboard FIRST, then\n * raising the bucket declarations in `supabase/config.toml`, then this value.\n * #4023: raised 50 -> 200 MiB now that we're confirmed on Supabase Pro (the\n * global project ceiling was raised to 500 MiB and the `media-responses`\n * bucket to 200 MiB to match).\n */\nexport const SUPABASE_STORAGE_MAX_BYTES = 200 * 1024 * 1024; // 200 MiB\n\n/**\n * Storage `cacheControl` (seconds, sent as `max-age=<n>`) for uploads (#5133).\n *\n * Both are bare whole-number strings on purpose: Supabase TUS only accepts an\n * integer `cacheControl` and stores `no-cache` for anything else, so there is\n * no `immutable` directive.\n *\n * IMMUTABLE (1 year) is for public `node-media` objects at a unique path.\n * RULE: a path written with IMMUTABLE must never be rewritten with different\n * bytes - browsers hold it for a year. Write a new path instead (UUID, content\n * hash, or a bumped rendition `version`).\n *\n * PRIVATE (1 hour) is for the signed-URL buckets (media-responses,\n * respondent-captures, file-uploads, file-downloads), matching the signed-URL\n * lifetime.\n */\nexport const STORAGE_CACHE_CONTROL_IMMUTABLE = \"31536000\";\nexport const STORAGE_CACHE_CONTROL_PRIVATE = \"3600\";\n\n/**\n * Trash (#2596 slice 3): days a trashed form stays recoverable before the\n * purge sweep (a later slice) hard-deletes it. Single source for the\n * dashboard's countdown badge and dialogs - never hardcode 30 there.\n *\n * The docs page (apps/docs/content/docs/help/managing-forms.mdx) states this\n * in prose as a hand-synced copy, NOT a derived value (MDX has no import of\n * this module) - if this constant ever changes, update that prose by hand too.\n */\nexport const TRASH_RETENTION_DAYS = 30;\n\n/**\n * Default resume window (#3885): hours before an incomplete response session\n * is considered expired and cleared, when a form has no explicit\n * `form_metadata.session_expiry_hours` override. Single source for the\n * `form_metadata.session_expiry_hours` column default (kept in step by hand -\n * SQL can't import this), `useFormMetadata`'s optimistic-cache default, the\n * dashboard's \"Keep progress for\" field, viewer's resume-window fallbacks,\n * and the responses table's stale-session threshold. Stored/displayed in\n * hours; the dashboard presents it in days (this / 24).\n */\nexport const DEFAULT_SESSION_EXPIRY_HOURS = 168;\n\n/**\n * Upper bound of `form_metadata.session_expiry_hours` (#1216): the builder\n * offers 1-30 days and the API clamps writes to this. It is therefore the\n * longest a respondent session can live, which the staged-node-delete sweep\n * (#5077) uses as its grace window. Single source - never hardcode 720.\n */\nexport const MAX_SESSION_EXPIRY_HOURS = 720;\n\n/**\n * On-device video compression settings (#1512, desktop parity #2329) - single\n * source of truth for both the phone upload page (`apps/api/src/routes/v1/media/\n * phone-upload-page.ts`, inline script) and the desktop builder helper\n * (`apps/dashboard/lib/compress-video.ts`). Both re-encode via mediabunny/\n * WebCodecs to these exact settings before the direct-vs-Mux size handshake, so\n * a clip compresses identically regardless of upload surface.\n *\n * VIDEO_COMPRESS_FLOOR_BYTES is a \"won't shrink, skip the generation loss + CPU\"\n * floor - below this a clip can't meaningfully benefit from re-encoding at the\n * bitrate below, and the keep-only-if-smaller guard in both callers already\n * blocks any accidental bloat. Locked at 1 MB (#2329).\n *\n * VIDEO_COMPRESS_MAX_SHORT_SIDE caps the SHORT side of the output (#6321), so a\n * 9:16 portrait clip keeps 1080x1920 and a landscape one 1920x1080 (a height\n * cap squashed portrait to 608x1080). It never upscales: a clip whose short\n * side is already at or under it keeps that size, rounded down to even (H.264\n * refuses odd sizes). The phone page and the desktop apply the identical\n * rule - change both together.\n */\nexport const VIDEO_COMPRESS_BITRATE = 3_500_000;\nexport const VIDEO_COMPRESS_MAX_SHORT_SIDE = 1080;\nexport const VIDEO_COMPRESS_FPS = 30;\nexport const VIDEO_COMPRESS_FLOOR_BYTES = 1 * 1024 * 1024; // 1 MB\n\n/**\n * Product-level cap on a single video upload (#5876), whatever the surface\n * (builder picker, phone upload page, Mux direct upload). Single source - the\n * dashboard's client-side pre-check, the phone page and the API's Mux upload\n * message all read this rather than hardcoding 200MB.\n */\nexport const MEDIA_VIDEO_MAX_BYTES = 200 * 1024 * 1024; // 200 MB\n\n/**\n * Max size of one file a creator attaches to a File Download node (#4706). The\n * builder's upload widget, its \"Max file size\" hint and the size refusal all\n * read this. Matches the `file-downloads` bucket ceiling in supabase/config.toml.\n */\nexport const FILE_DOWNLOAD_MAX_BYTES = 50 * 1024 * 1024; // 50 MB\n\n/**\n * Longest clip that still fits the direct tier (MEDIA_DIRECT_MAX_BYTES) after\n * on-device compression, in whole seconds (43). Both compressors set only the\n * video bitrate (VIDEO_COMPRESS_BITRATE) and pass the source audio through, so\n * the budget allows up to 256 kbps of audio plus 3% for MP4 overhead and encoder\n * overshoot. The desktop picker skips compressing a longer clip: it is over the\n * size cap even compressed, so it goes to Mux whatever we do, and Mux bills\n * minutes, not bytes (#5876). There is no length rule on delivery itself (#5887).\n */\nconst VIDEO_COMPRESS_AUDIO_ALLOWANCE = 256_000; // bits per second\nconst VIDEO_COMPRESS_SIZE_MARGIN = 0.97;\nexport const VIDEO_COMPRESS_MAX_SECONDS = Math.floor(\n (MEDIA_DIRECT_MAX_BYTES * 8 * VIDEO_COMPRESS_SIZE_MARGIN) / (VIDEO_COMPRESS_BITRATE + VIDEO_COMPRESS_AUDIO_ALLOWANCE),\n);\n\n/**\n * Upload stall bound (#5876): abort when no bytes move for this long. Shared by\n * the dashboard's upload watchdog and the phone upload page.\n */\nexport const UPLOAD_STALL_MS = 45_000;\n\n/** Once every byte is up, the server's budget to probe and store the file before an upload is abandoned (#5876). */\nexport const UPLOAD_RESPONSE_BUDGET_MS = 120_000;\n\n/** Share of a compressed video's progress bar given to the encode (0-1); the upload fills the rest (#5360). */\nexport const UPLOAD_COMPRESS_BAND = 0.4;\n\n/**\n * Backoff (ms) between retries of a resumable (tus) upload chunk, one entry per retry (#6197). Shared by\n * `uploadFileToStorageTus` (upload-client) and the phone upload page's inline tus client.\n */\nexport const TUS_RETRY_DELAYS_MS = Object.freeze([0, 3000, 5000, 10000, 20000]);\n\n/**\n * Desktop compression is skipped for a clip that is already ready to serve\n * (fast-start H.264/AAC MP4) at or under this bitrate (#5876).\n */\nexport const VIDEO_COMPRESS_SKIP_BITRATE = VIDEO_COMPRESS_BITRATE * 1.5; // 5.25 Mbps\n\n/**\n * Desktop encode bails to the original when its projected total time exceeds\n * this (#5876). A starting value, tuned from `video_compression` events.\n */\nexport const VIDEO_COMPRESS_MAX_PROJECTED_MS = 20_000;\n\n/**\n * Whether front-camera captures are SAVED mirrored (#5021). Off: only the\n * live preview is mirrored; the review and the saved photo/video show the true\n * camera image - the industry default (iPhone/Android cameras,\n * Zoom/Meet/Loom recordings, VideoAsk), so writing in shot reads correctly for\n * the form owner. Read by the API media processor (video answers) and the\n * viewer's desktop webcam capture and Open review (on: the saved file is mirrored\n * and the review shows it as saved); kept as a switch rather than deleting the flip.\n */\nexport const SAVE_FRONT_CAMERA_MIRRORED = false;\n\n/**\n * In-product \"Learn more\" deep-links (#394) - single source of truth, keyed\n * by concept. Anchors are CI-checked against real docs headings\n * (apps/docs/scripts/check-help-links.mjs). Never hardcode docs URLs in UI.\n */\nexport const HELP_LINKS = buildHelpLinks(BUSINESS.urls.docs);\nexport { HELP_TOPICS };\n\n/**\n * Per-node-type \"Learn more\" deep-link (#3963): looks up `node_<nodeType>` in\n * HELP_LINKS, so a node's settings menu can link straight to its section on\n * help/node-types.mdx. Returns null when the node type has no docs topic\n * (menu renders nothing rather than a dead link).\n */\nexport function nodeHelpLink(nodeType) {\n return HELP_LINKS[`node_${nodeType}`] ?? null;\n}\n\n/** URL builders — single source of truth for public-facing links */\nexport function viewerUrl(shareId) {\n return `${BUSINESS.urls.viewer}/${shareId}`;\n}\n/**\n * The link handed to someone to open/claim a form they built as a guest\n * (bot email + social replies, MCP create-form). Flag-gated on\n * `FEATURES.anonymous_builder` (#2979): on -> `/try`, which drops them\n * straight into the builder to see the product (no signup gate); off -> the\n * legacy `/save` signup wall. `getTemplateCtaUrl` (marketing) mirrors this\n * branch for template CTAs.\n */\nexport function formUrl(shareId) {\n return FEATURES.anonymous_builder.enabled\n ? templateTryUrl(shareId, BUSINESS.urls.dashboard)\n : `${BUSINESS.urls.dashboard}/save/${shareId}`;\n}\n/**\n * Same-UID claim handoff link (#3330 decision 3) for an MCP-minted anonymous\n * session: opens the dashboard's one-time claim route, which signs the\n * browser back into that exact anon Supabase session (not a copy) so the\n * standard convert flow can flip is_anonymous on it in place. `token` is a\n * one-time, ~15-minute opaque token from mintMcpClaimToken - never a\n * share_id or workspace id.\n */\nexport function mcpClaimUrl(token) {\n return `${BUSINESS.urls.dashboard}/claim/${token}`;\n}\n/**\n * Every dashboard tab a form has (#3405) - single source for the tab path\n * segment, so an MCP/bot deeplink can never drift from the real route. The\n * dashboard route folders under apps/dashboard/app/(app)/[workspaceId]/forms/[formId]/\n * are the ground truth this mirrors. Enforced, not just documentation:\n * dashboardFormUrl throws on any tab not in this list, so a caller's own\n * hardcoded tab string (e.g. get-form.ts's urls object) fails loudly the\n * moment it drifts from this array instead of silently building a dead link.\n */\nexport const DASHBOARD_FORM_TABS = ['build', 'summary', 'responses', 'analytics', 'share', 'share/embed', 'share/dynamic-link'];\n\n/**\n * Relative dashboard path for a form tab (#5131), optionally with a query\n * (object of string values). Same tab validation as dashboardFormUrl, which is\n * built on it. Use this for in-app links; use dashboardFormUrl for absolute URLs.\n */\nexport function dashboardFormPath(workspaceId, formId, tab = 'build', query) {\n if (!DASHBOARD_FORM_TABS.includes(tab)) {\n throw new Error(\n `dashboardFormPath: unknown tab \"${tab}\" - must be one of ${DASHBOARD_FORM_TABS.join(', ')}`\n );\n }\n const qs = query ? new URLSearchParams(query).toString() : '';\n return `/${workspaceId}/forms/${formId}/${tab}${qs ? `?${qs}` : ''}`;\n}\n\nexport function dashboardFormUrl(workspaceId, formId, tab = 'build') {\n return `${BUSINESS.urls.dashboard}${dashboardFormPath(workspaceId, formId, tab)}`;\n}\n\n/** Dashboard workspace root (redirects to the forms list). */\nexport function dashboardWorkspaceUrl(workspaceId) {\n return `${BUSINESS.urls.dashboard}/${workspaceId}`;\n}\n\n/** Dashboard forms list for a workspace. */\nexport function dashboardFormsListUrl(workspaceId) {\n return `${BUSINESS.urls.dashboard}/${workspaceId}/forms`;\n}\n\n/**\n * The dashboard's Settings area (#6211): one place, grouped by the scope a\n * setting applies to - Account (you), Company (every workspace in it) and\n * Workspace. Paths are relative to the workspace root `/{workspaceId}/`; the\n * route folders under apps/dashboard/app/(app)/[workspaceId]/settings/ are the\n * ground truth this mirrors (apps/dashboard/__tests__/app/settings/routes.test.ts).\n */\nexport const DASHBOARD_SETTINGS_PAGES = {\n account: 'settings/account',\n company: 'settings/company',\n companyBilling: 'settings/company/billing',\n workspace: 'settings/workspace',\n domains: 'settings/workspace/domains',\n};\n\n/**\n * The dashboard's Developers page (#6241), the one home for developer tools:\n * connecting AI clients over MCP (the hub), API keys, webhooks and the\n * authorized apps that hold access to the workspace. A rail item next to\n * Integrations, not part of Settings. Paths are relative to the workspace\n * root `/{workspaceId}/`; the route folders under\n * apps/dashboard/app/(app)/[workspaceId]/developers/ are the ground truth\n * (apps/dashboard/__tests__/app/developers/routes.test.ts).\n */\nexport const DASHBOARD_DEVELOPER_PAGES = {\n developers: 'developers',\n apiKeys: 'developers/api-keys',\n webhooks: 'developers/webhooks',\n authorizedApps: 'developers/authorized-apps',\n};\n\n/**\n * Old settings URLs and the page each moved to (#6211, #6241), both relative\n * to `/{workspaceId}/`. One table, read by the dashboard's next.config.js\n * redirects (in-workspace URLs), the workspace-less `/settings`, `/company`,\n * `/account` and `/developers` forwarders, and their tests. Every `to` is a\n * current page (never another `from`), so an old link lands in one hop,\n * query kept. Integrations stays a rail item, so its pre-#3203 URL goes\n * there; API keys, Webhooks and Authorized apps live in Developers.\n */\nexport const DASHBOARD_SETTINGS_REDIRECTS = [\n { from: 'settings', to: DASHBOARD_SETTINGS_PAGES.workspace },\n { from: 'company', to: DASHBOARD_SETTINGS_PAGES.company },\n { from: 'company/billing', to: DASHBOARD_SETTINGS_PAGES.companyBilling },\n { from: 'settings/billing', to: DASHBOARD_SETTINGS_PAGES.companyBilling },\n { from: 'api-keys', to: DASHBOARD_DEVELOPER_PAGES.apiKeys },\n { from: 'webhooks', to: DASHBOARD_DEVELOPER_PAGES.webhooks },\n { from: 'settings/api-keys', to: DASHBOARD_DEVELOPER_PAGES.apiKeys },\n { from: 'settings/webhooks', to: DASHBOARD_DEVELOPER_PAGES.webhooks },\n { from: 'settings/integrations', to: 'integrations' },\n { from: 'settings/domains', to: DASHBOARD_SETTINGS_PAGES.domains },\n { from: 'settings/connected-apps', to: DASHBOARD_DEVELOPER_PAGES.authorizedApps },\n // #6211's Settings - Workspace pages, moved to Developers (#6241).\n { from: 'settings/workspace/api-keys', to: DASHBOARD_DEVELOPER_PAGES.apiKeys },\n { from: 'settings/workspace/webhooks', to: DASHBOARD_DEVELOPER_PAGES.webhooks },\n { from: 'settings/workspace/authorized-apps', to: DASHBOARD_DEVELOPER_PAGES.authorizedApps },\n];\n\n/**\n * The workspace-less deep-link roots the dashboard forwards (#1002, #4587,\n * #6211, #6241): `/settings/...`, `/company/...`, `/account/...` and\n * `/developers/...` resolve the user's active workspace, so docs and emails\n * never carry a workspace id.\n */\nexport const DASHBOARD_SETTINGS_FORWARDERS = ['settings', 'company', 'account', 'developers'];\n\n/**\n * A settings page's dashboard path. With no workspace it is the\n * workspace-less deep link (`/settings/...`), which resolves the active\n * workspace. Throws on an unknown page so a caller can't build a dead link.\n */\nexport function dashboardSettingsPath(workspaceId, page) {\n const path = DASHBOARD_SETTINGS_PAGES[page];\n if (!path) {\n throw new Error(\n `dashboardSettingsPath: unknown page \"${page}\" - must be one of ${Object.keys(DASHBOARD_SETTINGS_PAGES).join(', ')}`\n );\n }\n return workspaceId ? `/${workspaceId}/${path}` : `/${path}`;\n}\n\n/**\n * A Developers page's dashboard path (#6241), mirroring dashboardSettingsPath:\n * with no workspace it is the workspace-less deep link (`/developers/...`),\n * which resolves the active workspace. Throws on an unknown page so a caller\n * can't build a dead link.\n */\nexport function dashboardDeveloperPath(workspaceId, page) {\n const path = DASHBOARD_DEVELOPER_PAGES[page];\n if (!path) {\n throw new Error(\n `dashboardDeveloperPath: unknown page \"${page}\" - must be one of ${Object.keys(DASHBOARD_DEVELOPER_PAGES).join(', ')}`\n );\n }\n return workspaceId ? `/${workspaceId}/${path}` : `/${path}`;\n}\n\n/**\n * Where a workspace-less settings or developers deep link lands, relative to\n * `/{workspaceId}/` (#6211, #6241): an old URL maps through\n * DASHBOARD_SETTINGS_REDIRECTS, `/company/<x>` sits under\n * `settings/company/<x>`, anything under `/account` is the Account page, and\n * a current Settings or Developers path passes through. Null when the link\n * doesn't reach a real page (an unknown root or sub-page), which the docs\n * link guard fails on.\n */\nexport function dashboardSettingsTarget(path) {\n const clean = String(path ?? '').replace(/^\\/+|\\/+$/g, '');\n const root = clean.split('/')[0];\n if (!DASHBOARD_SETTINGS_FORWARDERS.includes(root)) return null;\n const row = DASHBOARD_SETTINGS_REDIRECTS.find((r) => r.from === clean);\n let target = row ? row.to : clean;\n if (!row && root === 'company') target = `settings/${clean}`;\n if (root === 'account') target = DASHBOARD_SETTINGS_PAGES.account;\n const isPage =\n target === 'integrations' ||\n Object.values(DASHBOARD_SETTINGS_PAGES).includes(target) ||\n Object.values(DASHBOARD_DEVELOPER_PAGES).includes(target);\n return isPage ? target : null;\n}\n\n/**\n * Company settings - Billing (#4587, under Settings since #6211), the\n * dashboard path the billing API's Stripe return URLs and every dashboard\n * Upgrade link share. With no workspace it is the workspace-less\n * `/settings/company/billing` deep link, which resolves the active workspace.\n */\nexport function dashboardCompanyBillingPath(workspaceId) {\n return dashboardSettingsPath(workspaceId, 'companyBilling');\n}\n\n/**\n * Dashboard auth routes - single source of truth so a login/signup route rename\n * is one edit here (plus renaming the app/<route> folder). Internal dashboard\n * redirects use AUTH_ROUTES.*; cross-app links (marketing) use the *Url builders.\n */\nexport const AUTH_ROUTES = { login: '/login', signup: '/signup' };\nexport function loginUrl() {\n return `${BUSINESS.urls.dashboard}${AUTH_ROUTES.login}`;\n}\nexport function signupUrl() {\n return `${BUSINESS.urls.dashboard}${AUTH_ROUTES.signup}`;\n}\n\n/**\n * Minimum password length (#3843) - single source of truth for both the\n * client-side floor (AuthForm's password step, SetPasswordCard, the\n * /auth/callback recovery form, ConvertAccountModal) and the server-side\n * one (`minimum_password_length` in supabase/config.toml, dashboard-set on\n * dev + prod - see that file's #2984/#3843 note). Kept in lockstep by\n * apps/api/src/__tests__/lib/min-password-length-sync.test.ts - change both\n * together.\n */\nexport const MIN_PASSWORD_LENGTH = 8;\n\n/**\n * OTP/magic-link resend cooldown, in seconds (#3873) - must equal\n * `[auth.email] max_frequency` in supabase/config.toml AND the hosted\n * Supabase dashboard value (Auth -> Providers -> Email -> \"Rate limit for\n * sending emails\"; Studio's shared default is 60s for both the OTP and\n * magic-link email types). GoTrue rejects an email send inside this window\n * with `over_email_send_rate_limit`, so AuthForm's Resend control disables\n * itself and shows a countdown for this long after every send instead of\n * letting the user hit the server limit. Kept in lockstep by\n * apps/api/src/__tests__/lib/otp-resend-cooldown-sync.test.ts - change both\n * together.\n */\nexport const OTP_RESEND_COOLDOWN_SECONDS = 60;\n\n/**\n * Accepted shape of a form share_id: more generous than the real 9-char hex slug, but it excludes\n * `/`, `.` and everything else a URL path segment could use to escape (see apps/dashboard/lib/saveTemplate.ts).\n */\nexport const SHARE_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;\n\n/**\n * The real shape of a form share_id: exactly 9 lowercase hex characters (every prod\n * share id). Stricter than SHARE_ID_PATTERN, which only keeps a URL segment safe.\n * A form alias must never match it (#3278), so a name can't be mistaken for an id.\n */\nexport const SHARE_ID_SHAPE = /^[0-9a-f]{9}$/;\nexport function isShareIdShape(value) {\n return typeof value === 'string' && SHARE_ID_SHAPE.test(value);\n}\n\n/** The one `/try?template=<share id>` builder (formUrl and tryUrl both use it). */\nfunction templateTryUrl(shareId, base) {\n return `${base}/try?template=${shareId}`;\n}\n\n/**\n * The anonymous-builder entry point (`FEATURES.anonymous_builder`, #2979):\n * mints a guest session and drops straight into the builder, no signup gate.\n * With a share id, links to that template's copy instead of a blank form\n * (`/try?template=<id>`); with a valid alias name (`isValidFormAlias`, #3278) it\n * builds the readable `/try/<name>`. `base` overrides the host (default: this environment's dashboard) for tools that must\n * always link to production, e.g. `PROD_URLS.dashboard`.\n */\nexport function tryUrl(idOrName, base = BUSINESS.urls.dashboard) {\n if (idOrName && isValidFormAlias(idOrName)) return `${base}/try/${idOrName}`;\n return idOrName ? templateTryUrl(idOrName, base) : `${base}/try`;\n}\n\n/**\n * Readable template-link names (#3278): `app.clipform.io/try/<name>`. Mirrored by\n * the CHECKs on `form_alias` (drift-tested against the migration). Lowercase\n * letters, digits and single dashes; 3-50 characters (length is enforced in\n * `isValidFormAlias`, not the pattern).\n */\nexport const FORM_ALIAS_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/;\nexport const FORM_ALIAS_MIN_LENGTH = 3;\nexport const FORM_ALIAS_MAX_LENGTH = 50;\n\n/** Names that could clash with a current or future `/try/*` or top-level route. */\nexport const FORM_ALIAS_RESERVED = [\n 'new', 'edit', 'admin', 'settings', 'login', 'signup', 'api', 'templates', 'template',\n 'try', 'claim', 'auth', 'oauth', 'internal', 'help', 'docs',\n];\n\n/**\n * True for a usable alias: right shape and length, not reserved, and never a\n * 9-hex string (that is a share id - every prod share id has exactly that shape).\n */\nexport function isValidFormAlias(name) {\n return (\n typeof name === 'string' &&\n name.length >= FORM_ALIAS_MIN_LENGTH &&\n name.length <= FORM_ALIAS_MAX_LENGTH &&\n FORM_ALIAS_PATTERN.test(name) &&\n !SHARE_ID_SHAPE.test(name) &&\n !FORM_ALIAS_RESERVED.includes(name)\n );\n}\n\n/**\n * The Powered-by CTA's fork entry (#857/#3777): same anonymous-builder mint\n * as `tryUrl`, but carries the source form's shareId as `?fork=` instead of\n * `?template=` - `/try` resolves this into a blank NODE-SHAPE skeleton\n * (`POST /v1/forms/skeleton`) rather than a full content clone (`?template=`'s\n * `/v1/forms/save/:shareId` path). Mirrors `tryImportUrl`'s gating: with the\n * flag off, falls back to the plain dashboard link rather than a dead `/try`.\n */\nexport function tryForkUrl(shareId) {\n return FEATURES.anonymous_builder.enabled\n ? `${BUSINESS.urls.dashboard}/try?fork=${encodeURIComponent(shareId)}`\n : BUSINESS.urls.dashboard;\n}\n\n/**\n * Normalizes a scheme-less paste (\"docs.google.com/forms/...\", the common\n * copy from an address bar) by prepending https://. `new URL()` throws on a\n * bare host (so provider detection would reject a perfectly valid form link),\n * and the API's `z.string().url()` would reject it too. Call this before\n * validating/sending so both checks see the same value the request body will\n * actually carry.\n */\nexport function normalizeFormUrl(value) {\n return /^[a-zA-Z][a-zA-Z0-9+.-]*:\\/\\//.test(value) ? value : `https://${value}`;\n}\n\n/**\n * The form import widget's target URL (#3414 SSOT promotion of\n * #3402's marketing-only `getGoogleImportUrl`; Typeform and Tally too, #3705): redirects into the\n * dashboard's `/try` anonymous lane with the (already normalized) form URL\n * as a query param, which runs the same anon sign-in + captcha +\n * at-limit-gate flow as the template path before calling\n * `POST /v1/forms/import/<provider>`. Consumed by both marketing\n * (`FormImportSection`) and docs (`FormImporter`) - neither app\n * calls the API directly.\n *\n * Mirrors `formUrl`'s `FEATURES.anonymous_builder` gating - unlike the\n * template path, there is no legacy signup-gated fallback for importing, so\n * with the flag off this falls back to the plain dashboard link (same as\n * marketing's `getTemplateCtaUrl`'s missing-share-id case,\n * `apps/marketing/src/lib/template-cta.ts`) rather than a dead `/try`.\n */\nexport function tryImportUrl(url) {\n return FEATURES.anonymous_builder.enabled\n ? `${BUSINESS.urls.dashboard}/try?import=${encodeURIComponent(url)}`\n : BUSINESS.urls.dashboard;\n}\n\n/**\n * Embeddable viewer iframe — single source of truth for embedding a form on a\n * third-party page. Consumed directly by anything inside our bundler (e.g. the\n * oEmbed endpoint in `apps/api`). Two artifacts run OUTSIDE the bundler and so\n * cannot import this — the static SDK (`apps/marketing/public/embed.js`) and\n * the standalone Framer component (`apps/embeds/framer/Clipform.tsx`) — and\n * carry a verbatim copy of `iframeAllow`. A parity test\n * (`apps/api/src/__tests__/lib/embed-allow-parity.test.ts`) fails if either\n * copy drifts from this value, so this stays the source of truth.\n */\nexport const EMBED = {\n // Permissions delegated to the cross-origin viewer iframe: recording\n // (camera/microphone), video (autoplay/fullscreen), Stripe wallets\n // (payment), the end-screen share button (web-share + clipboard-write), and\n // keeping the respondent's screen from auto-dimming mid-session (#2859).\n iframeAllow: 'camera; microphone; autoplay; fullscreen; payment; web-share; clipboard-write; screen-wake-lock',\n // Default 9:16 portrait box — matches embed.js DEFAULT_MAX_WIDTH (460px).\n defaultWidth: 460,\n defaultHeight: 818, // round(460 * 16 / 9)\n};\n\n/** Embeddable viewer URL for a form (the viewer's `display=embed` mode). */\nexport function embedViewerUrl(shareId) {\n return `${BUSINESS.urls.viewer}/${shareId}?display=embed`;\n}\n\n/**\n * Brand assets and visual identity\n */\nexport const BRAND = {\n logo: {\n primary: \"/logo.svg\",\n withText: \"/logo_text.svg\",\n icon: \"/favicon.ico\",\n iconSvg: \"/icon.svg\",\n appleTouchIcon: \"/apple-touch-icon.png\",\n minWidth: \"120px\",\n maxWidth: \"200px\",\n spacing: \"16px\",\n },\n colors: {\n primary: \"#171717\",\n secondary: \"#404040\",\n accent: \"#3182CE\",\n background: \"#FAFAFA\",\n surface: \"#FFFFFF\",\n border: \"#E5E5E5\",\n muted: \"#737373\",\n destructive: \"#DC2626\",\n success: \"#16A34A\",\n },\n fonts: {\n body: \"Inter, sans-serif\",\n headings: \"'Satoshi', Inter, sans-serif\",\n logo: \"'Plus Jakarta Sans', sans-serif\",\n satoshiImport: \"https://api.fontshare.com/v2/css?f[]=satoshi@400,500,700,900&display=swap\",\n },\n};\n\n/**\n * Plan limits — shared between API (enforcement), dashboard (UI gating), and viewer (branding)\n *\n * Keyed by plan_version string (e.g. 'free_v1', 'pro_v1') so we can\n * grandfather old limits when pricing changes. New signups get the version\n * from CURRENT_PLAN_VERSIONS; existing companies keep theirs until\n * explicitly migrated.\n *\n * Per-version billing identity is provider-agnostic (#1027): `price_cents` is\n * the canonical machine-readable price (the `price` string is display-only);\n * `stripe_price_id` and `shopify_plan_handle` map the version to each biller.\n * `shopify_plan_handle` is null until the matching Shopify App Pricing plan is\n * created in the Partner Dashboard.\n */\nexport const PLAN_LIMITS = {\n free_v1: {\n tier: 0,\n name: 'Free',\n price: '$0',\n period: 'forever',\n price_cents: 0,\n stripe_price_id: { test: null, live: null },\n // Shopify App Pricing plan NAME (must match the Partner Dashboard plan\n // exactly - the app_subscriptions/update payload carries this name). Free\n // generates no subscription, so this is only used by the drift check.\n shopify_plan_handle: 'Free',\n // Platform commission on payments collected by a Free-plan creator, in\n // basis points (#3831). Live at 500 (5%) - paid tiers stay 0%. Retained\n // on refund by design (industry standard - Stripe keeps `application_fee`\n // unless `refund_application_fee` is set). See create-payment-intent.ts\n // for the fee gate.\n platform_fee_bps: 500,\n node_limit: null,\n form_limit: 5,\n workspace_limit: 1,\n show_branding: true,\n custom_theme: false,\n dynamic_links: false,\n custom_domain: false,\n response_limit: 100,\n features: [\n 'Up to 5 forms',\n 'Unlimited questions per form',\n // \"completed\" is not a tightening: response_limit has always been 100,\n // but the counter now excludes partials (#2618), so this wording is both\n // accurate and strictly more generous than what it replaced.\n '100 completed responses per month',\n 'Full AI tooling (TTS, media, video)',\n 'Clipform branding',\n ],\n },\n pro_v1: {\n tier: 1,\n name: 'Pro',\n price: '$25',\n period: '/month',\n price_cents: 2500,\n stripe_price_id: { test: 'price_1TZnmhCWdEPD0KoNWWJTc3B6', live: 'price_1TZnrZEJOD9ik3LhhFwGZ6ut' },\n // Must match the Partner Dashboard plan name exactly (drives webhook plan\n // mapping + the price drift check). Keep in step with price_cents above.\n shopify_plan_handle: 'Pro',\n // Paid tier - platform takes 0% (#3831). Free is the only tier with a\n // commission, and only once go-live flips it on.\n platform_fee_bps: 0,\n node_limit: null,\n form_limit: null,\n workspace_limit: null,\n show_branding: false,\n custom_theme: true,\n dynamic_links: true,\n custom_domain: true,\n response_limit: null,\n features: [\n 'Unlimited forms',\n 'Unlimited questions',\n 'Unlimited responses',\n 'Custom themes & colors',\n 'Remove Clipform branding',\n 'Dynamic links - repoint a printed URL to a new form',\n ],\n },\n\n // Banded Pro (#1937). pro_v2_1k IS the current tier-1 version (#2671) - new\n // Pro signups land here; pro_v1 is retained only to grandfather the accounts\n // that predate the flip.\n //\n // Billing is one subscription with TWO Stripe items: this licensed base\n // billed in advance, plus a volume-tiered metered top-up (STRIPE_BAND_PRICE_ID\n // below) billed in arrears - so the band a workspace lands in is decided by\n // usage, never by swapping plan version. Completed responses report to the\n // Stripe usage meter (#2651, apps/api/src/lib/usage-metering.ts) via\n // planMetersUsage below, and checkout appends the metered item whenever a band\n // price is configured for the mode (#2652). The band price now exists in BOTH\n // test and live (STRIPE_BAND_PRICE_ID), so a new Pro checkout is two-item and\n // usage above the base band IS charged once this deploys - the HUMAN LEGAL\n // REVIEW on LEGAL.billing below must clear before that go-live.\n //\n // `response_limit` counts COMPLETED submissions only (#4118: per completed\n // form_session, grandfathered pre-cutover as completed response sets - see\n // count_workspace_responses_this_month); partials never consume allowance.\n //\n // shopify_plan_handle is null until the matching Partner Dashboard plans\n // exist - so planVersionForShopifyPlan still maps Shopify's \"Pro\" to pro_v1\n // ($25 unlimited) while web signups get this band. Creating those plans is\n // what closes that cross-channel gap.\n pro_v2_1k: {\n tier: 1,\n name: 'Pro',\n price: '$24',\n period: '/month',\n price_cents: 2400,\n stripe_price_id: {\n test: 'price_1U0lA6EJOD9ik3Lhube5eBcK',\n live: 'price_1U115SEJOD9ik3LhOU9OkqJk',\n },\n shopify_plan_handle: null,\n // Paid tier - platform takes 0% (#3831).\n platform_fee_bps: 0,\n node_limit: null,\n form_limit: null,\n workspace_limit: null,\n show_branding: false,\n custom_theme: true,\n dynamic_links: true,\n custom_domain: true,\n response_limit: 1000,\n features: [\n 'Unlimited forms',\n 'Unlimited questions',\n '1,000 completed responses per month',\n 'Custom themes & colors',\n 'Remove Clipform branding',\n 'Dynamic links - repoint a printed URL to a new form',\n 'Send form events to Google Tag Manager and Meta Pixel',\n ],\n },\n pro_v2_5k: {\n tier: 1,\n name: 'Pro',\n price: '$49',\n period: '/month',\n price_cents: 4900,\n stripe_price_id: { test: null, live: null },\n shopify_plan_handle: null,\n // Paid tier - platform takes 0% (#3831).\n platform_fee_bps: 0,\n node_limit: null,\n form_limit: null,\n workspace_limit: null,\n show_branding: false,\n custom_theme: true,\n dynamic_links: true,\n custom_domain: true,\n response_limit: 5000,\n features: [\n 'Unlimited forms',\n 'Unlimited questions',\n '5,000 completed responses per month',\n 'Custom themes & colors',\n 'Remove Clipform branding',\n 'Dynamic links - repoint a printed URL to a new form',\n 'Send form events to Google Tag Manager and Meta Pixel',\n ],\n },\n pro_v2_20k: {\n tier: 1,\n name: 'Pro',\n price: '$99',\n period: '/month',\n price_cents: 9900,\n stripe_price_id: { test: null, live: null },\n shopify_plan_handle: null,\n // Paid tier - platform takes 0% (#3831).\n platform_fee_bps: 0,\n node_limit: null,\n form_limit: null,\n workspace_limit: null,\n show_branding: false,\n custom_theme: true,\n dynamic_links: true,\n custom_domain: true,\n response_limit: 20000,\n features: [\n 'Unlimited forms',\n 'Unlimited questions',\n '20,000 completed responses per month',\n 'Custom themes & colors',\n 'Remove Clipform branding',\n 'Dynamic links - repoint a printed URL to a new form',\n 'Send form events to Google Tag Manager and Meta Pixel',\n ],\n },\n};\n\n/**\n * Whether a workspace's response_limit counts only COMPLETED submissions -\n * i.e. an in-progress (not yet completed) response never consumes the cap.\n * True today for every plan (#4118, apps/api's\n * count_workspace_responses_this_month RPC is the actual enforcement). A\n * policy fact repeated here - NOT a mirror of the SQL - so marketing's\n * `partial_responses_free` claim (PRICING_CLAIMS below) has something to\n * assert against; keep this in step BY HAND with the RPC if that counting\n * rule ever changes.\n */\nexport const RESPONSE_LIMIT_COUNTS_COMPLETED_ONLY = true;\n\n/**\n * Pricing claims marketing copy may cite by key (ads `claims: string[]`,\n * #4338 - mirrors FEATURES for pricing facts, which have no\n * enabled/status lifecycle). Each key's truth is asserted directly against\n * PLAN_LIMITS (or another named config truth) in test/pricing-claims.test.js -\n * a plan change that breaks the assertion fails CI instead of leaving a\n * stale claim live in ad copy or content.\n */\nexport const PRICING_CLAIMS = {\n free_plan: {\n description: 'Clipform has a genuinely free plan, not a time-limited trial',\n },\n no_credit_card: {\n description: 'Signing up for the free plan never asks for a card',\n },\n partial_responses_free: {\n description: \"An in-progress response never counts against the free plan's response cap\",\n },\n unlimited_questions: {\n description: 'The free plan has no limit on questions per form',\n },\n};\n\n/**\n * Maps tier integer → version string assigned to new signups.\n *\n * Tier 1 is a BAND (#1937): new Pro signups get pro_v2_1k ($24 / 1,000\n * completed responses). Existing companies keep their stored plan_version, so\n * the pro_v1 accounts predating this stay on unlimited - grandfathered, never\n * migrated. Nothing charges for exceeding a band yet (#2651 meters usage,\n * #2652 makes checkout two-item); until then an over-band customer keeps\n * collecting, stays fully visible, and the excess is absorbed.\n */\nexport const CURRENT_PLAN_VERSIONS = { 0: 'free_v1', 1: 'pro_v2_1k' };\n\n/**\n * Ordered Pro bands for the pricing slider (#1937). DERIVED from PLAN_LIMITS -\n * never define band prices or limits here. Ascending by response_limit.\n *\n * The pricing page renders a final \"talk to us\" stop beyond the last band;\n * that is presentation, not a plan version, so it lives in the component.\n */\nexport const PRO_BANDS = ['pro_v2_1k', 'pro_v2_5k', 'pro_v2_20k'].map(\n (version) => ({ version, ...PLAN_LIMITS[version] })\n);\n\n/**\n * The single volume-tiered METERED Stripe price that carries banded Pro usage\n * (#1937 / #2652). ONE price spans every band: Stripe's `tiers_mode: 'volume'`\n * selects the band from the MAX usage in the period, so the band a customer\n * lands in is decided by usage, never by swapping plan_version. It is therefore\n * a tier-level fact and lives here ONCE, not on each pro_v2_* entry.\n *\n * Deliberately NOT any PLAN_LIMITS[*].stripe_price_id: it is metered and billed\n * in ARREARS (the licensed base is billed in advance), and it must NEVER resolve\n * through planVersionForStripePrice - that maps the LICENSED base price to a\n * plan version, and letting the band price match would reintroduce #2678 (the\n * webhook picking the band item as the \"plan\" item, writing the wrong\n * plan_version and billing period). Checkout appends it as a second\n * subscription item (#2652); the webhook plan projection ignores it.\n *\n * NEVER attach Stripe billing thresholds to this price: combined with volume\n * tiers they can produce NEGATIVE invoice line items (#1937).\n *\n * Both `test` and `live` are set: the live price (volume-tiered $0/$25/$75/$75,\n * metered against `mtr_61VAPLMBymP6O56H441EJOD9ik3LhCfA` on Pro product\n * `prod_UOCjM0hFrt0XYw`, tax_behavior exclusive) was created by hand in the\n * live Stripe dashboard. So LIVE checkout is two-item the moment this deploys -\n * see the deploy-gated HUMAN LEGAL REVIEW note on LEGAL.billing below.\n */\nexport const STRIPE_BAND_PRICE_ID = {\n test: 'price_1U0lEsEJOD9ik3Lhs4ttMplT',\n live: 'price_1U1RABEJOD9ik3LhBDfNGlfZ',\n};\n\n/**\n * Whether a plan hides over-limit responses behind the paygate.\n *\n * Only the free tier redacts. A PAID plan with a finite response_limit\n * (banded Pro - pro_v2_*) escalates the charge to the band reached and keeps\n * everything visible (#1937), so a numeric response_limit alone must never\n * imply redaction. See #2650.\n */\nexport function planRedactsOverLimit(limits) {\n return limits?.tier === 0 && limits?.response_limit != null;\n}\n\n/**\n * Whether a plan's completed responses should be reported to the Stripe usage\n * meter (#2651).\n *\n * A metered band is a PAID plan (tier > 0) with a finite response_limit -\n * i.e. banded Pro (pro_v2_*). Deliberately NOT a `pro_v2_*` string match:\n * config is the source of truth for which versions meter, so a future band\n * (or a grandfathered pro_v1 unlimited account, which must never meter)\n * follows from its shape alone. pro_v1 has `response_limit: null` (unlimited)\n * so it correctly never meters; free_v1 is tier 0 so it correctly never\n * meters either (its cap is enforced by paygate/redaction, not billing).\n */\nexport function planMetersUsage(limits) {\n return limits?.tier > 0 && limits?.response_limit != null;\n}\n\n/**\n * Pricing-card feature lines for a plan version - `PLAN_LIMITS[version].features`\n * plus a derived platform-commission line (#3831), single source so a pricing\n * card never hand-writes the fee copy. Lights up automatically off whatever\n * `platform_fee_bps` carries per tier - no caller change needed. Never\n * hardcode a percentage - always derive it from here.\n *\n * - A tier whose OWN `platform_fee_bps` is > 0 gets its real rate:\n * `${bps / 100}% commission on payments collected`.\n * - Once ANY tier in PLAN_LIMITS carries a commission, every OTHER (0-bps)\n * paid tier (`tier > 0`) gets the contrasting `Keep 100% of payments - no\n * platform fee` line, so Pro reads as the fee-free alternative the moment\n * Free's fee is live. A paid tier never gets its own commission line today\n * (every paid `platform_fee_bps` is permanently 0), but the check is written against\n * the tier's own bps first so a future paid-tier fee would still show its\n * real rate instead of the contrasting copy.\n */\nexport function planFeatureLines(version) {\n const limits = PLAN_LIMITS[version];\n if (!limits) return [];\n\n const bps = limits.platform_fee_bps ?? 0;\n if (bps > 0) {\n return [...limits.features, `${bps / 100}% commission on payments collected`];\n }\n\n const anyFeeActive = Object.values(PLAN_LIMITS).some((p) => (p.platform_fee_bps ?? 0) > 0);\n if (anyFeeActive && limits.tier > 0) {\n return [...limits.features, 'Keep 100% of payments - no platform fee'];\n }\n\n return [...limits.features];\n}\n\n/**\n * Product information and features\n */\nexport const PRODUCT = {\n features: {\n get core() {\n return getLiveFeatures()\n .filter(f => ['node-types', 'responses', 'builder', 'analytics', 'ai'].includes(f.category))\n .map(f => f.name);\n },\n get premium() {\n return getLiveFeatures()\n .filter(f => ['sharing', 'api'].includes(f.category))\n .map(f => f.name);\n },\n },\n // Derived from PLAN_LIMITS (source of truth)\n get pricing() {\n const free = PLAN_LIMITS[CURRENT_PLAN_VERSIONS[0]];\n const pro = PLAN_LIMITS[CURRENT_PLAN_VERSIONS[1]];\n return {\n free: { name: free.name, price: free.price, period: free.period, features: free.features },\n pro: { name: pro.name, price: pro.price, period: pro.period, features: pro.features },\n };\n },\n};\n\n/**\n * Social media links\n */\nexport const SOCIAL = {\n twitter: \"@clipform\",\n linkedin: \"company/clipform\",\n github: \"clipform\",\n urls: {\n twitter: \"https://twitter.com/clipform\",\n linkedin: \"https://linkedin.com/company/clipform\",\n github: \"https://github.com/clipform\",\n },\n};\n\n/**\n * Ad tracking switch (#4900). When false, nothing reaches an ad platform:\n * neither app loads the GTM container (Google Ads tag + Meta Pixel), and\n * `fireSignupConversion` neither pushes the `sign_up` event nor calls the\n * server relay for Meta CAPI / Google Ads (so no hashed email is sent).\n * NEXT_PUBLIC_GTM_ID and the META_CAPI_* / GOOGLE_ADS_* env vars can stay set.\n *\n * Before turning this on: add consent (banner or GTM Consent Mode - ad tags\n * aren't \"strictly necessary\" under UK GDPR/PECR) and update the privacy\n * policy, which says there are no advertising trackers and that Google user\n * data is never used for advertising.\n */\nexport const AD_TRACKING_ENABLED = false;\n\n/**\n * Legal and compliance\n */\n/**\n * Legal facts - single source of truth for /terms and /privacy (#459).\n * Pages derive entity names, contacts, dates, and numbers from here;\n * never hardcode them in page copy.\n *\n * Drafting principle: minimum legally-required disclosure only. No voluntary\n * commitments, no named vendors in public docs (categories of recipients\n * satisfy UK GDPR Art 13(1)(e)), no published DPA until a customer requests\n * one. Shortest legally-sufficient wording everywhere.\n */\nexport const LEGAL = {\n company: \"Reco Ventures Ltd.\",\n companyCountry: \"United Kingdom\",\n governingLaw: \"England and Wales\",\n copyright: \"© 2026 Clipform. All rights reserved.\",\n privacy: \"/privacy\",\n terms: \"/terms\",\n privacyEmail: \"hello@clipform.io\", // GDPR contact - no separate DPO mailbox\n termsUpdated: \"2026-09-08\",\n privacyUpdated: \"2026-11-12\",\n minAge: 18, // contract capacity; no parental-consent handling\n billing: {\n processor: \"Stripe\", // live\n // Banded Pro (#1937/#2652) is a hybrid charge on ONE subscription: a flat\n // monthly base billed in ADVANCE, plus variable usage-based charges for\n // completed responses above the base band, billed in ARREARS at period end\n // and auto-escalated to the band reached. Auto-renews; cancellation is\n // effective at the end of the current period.\n // HUMAN LEGAL REVIEW REQUIRED before go-live (#2652): the rendered /terms\n // prose does not yet describe variable/auto-escalating usage charges, and\n // UK consumer rules want express consent to variable charges captured at\n // checkout.\n model: \"base-plus-usage-recurring\",\n // HUMAN LEGAL REVIEW REQUIRED before go-live (#2652): \"none\" pairs badly\n // with auto-escalating usage charges - the first bot storm or viral spike\n // that inflates a bill needs discretion to exist in writing.\n refunds: \"none\", // except at our sole discretion\n },\n // Total liability capped at fees paid in the prior 12 months (free = zero),\n // plus standard as-is / no indirect damages wording.\n liabilityCapMonths: 12,\n // Account/data deletion completed within this window (incl. Mux assets +\n // Supabase storage; backups may persist briefly beyond).\n deletionDays: 30,\n // Aggregated/anonymized data: rights reserved via quiet drafting - folded\n // into the content licence (terms s5) and lawful-bases (privacy s3) rather\n // than a standalone billboard section. Covers product improvement,\n // benchmarks, published insights; never re-identified.\n //\n // Internal only - NOT rendered anywhere. Kept current so a DPA can be\n // produced the day a customer requests one. Public docs disclose\n // categories of recipients only.\n subprocessors: [\n { name: \"Supabase\", purpose: \"Database and file storage\" },\n { name: \"Mux\", purpose: \"Video hosting and streaming\" },\n { name: \"Vercel\", purpose: \"Web hosting\" },\n { name: \"Render\", purpose: \"API hosting\" },\n { name: \"AWS\", purpose: \"Video rendering (Lambda)\" },\n { name: \"PostHog\", purpose: \"Product analytics and error tracking\" },\n { name: \"Cloudflare\", purpose: \"DNS, CDN, email routing\" },\n { name: \"Stripe\", purpose: \"Payment processing\" },\n { name: \"Anthropic\", purpose: \"AI form generation\" },\n { name: \"OpenAI\", purpose: \"AI form generation; content moderation of responses\" },\n { name: \"Groq\", purpose: \"Transcription and AI summaries of voice and video responses\" },\n ],\n};\n\n/**\n * Standard contact form field definitions\n * Source of truth for both dashboard (field picker) and viewer (form rendering)\n */\nexport const CONTACT_FIELDS = [\n { id: 'first_name', label: 'First Name', type: 'text', placeholder: 'Enter first name', order: 1 },\n { id: 'last_name', label: 'Last Name', type: 'text', placeholder: 'Enter last name', order: 2 },\n { id: 'email', label: 'Email Address', type: 'email', placeholder: 'you@example.com', order: 3 },\n { id: 'phone', label: 'Phone Number', type: 'tel', placeholder: '(555) 123-4567', order: 4 },\n];\n\nexport const CONTACT_FIELDS_MAP = Object.fromEntries(\n CONTACT_FIELDS.map(f => [f.id, f])\n);\n\n// Fields that used to be standard; kept only so old forms keep readable names.\nconst RETIRED_CONTACT_FIELD_LABELS = {\n company: 'Company',\n job_title: 'Job Title',\n website: 'Website',\n linkedin: 'LinkedIn Profile',\n message: 'Message',\n};\n\n/**\n * The one name a details field shows on every creator surface (#5577): the\n * Responses table, the response panel and the CSV/Excel export. A standard\n * field (email, phone, ...) always shows its CONTACT_FIELDS label, whatever an\n * agent or import stored; a custom field shows its own label; any other id\n * config does not define falls back to its stored label, then the id. A blank\n * label, or one equal to the id, counts as no label.\n */\nexport function contactFieldLabel(field) {\n if (Object.hasOwn(CONTACT_FIELDS_MAP, field.id) && !field.is_custom) {\n return CONTACT_FIELDS_MAP[field.id].label;\n }\n const stored = typeof field.label === 'string' ? field.label.trim() : '';\n if (stored && stored !== field.id) return stored;\n if (!field.is_custom && Object.hasOwn(RETIRED_CONTACT_FIELD_LABELS, field.id)) {\n return RETIRED_CONTACT_FIELD_LABELS[field.id];\n }\n return field.id;\n}\n\n/**\n * The input type of a details field (#6267), the one rule the viewer and the dashboard share so they can't disagree\n * about which fields are emails: a custom field's own `type`, a standard field's config type, else `text`.\n */\nexport function contactFieldType(field) {\n if (field?.is_custom) return field.type || 'text';\n const def = Object.hasOwn(CONTACT_FIELDS_MAP, field?.id) ? CONTACT_FIELDS_MAP[field.id] : undefined;\n return def?.type || 'text';\n}\n\n/**\n * The one order details steps are named, laid out and read in: created_at,\n * then id. Returns a new array; callers pass nodes with `id` and `created_at`.\n */\nexport function sortDetailsSteps(detailsNodes) {\n const key = (n) => (typeof n?.created_at === 'string' ? n.created_at : '');\n return (Array.isArray(detailsNodes) ? [...detailsNodes] : []).sort((a, b) => {\n const x = key(a);\n const y = key(b);\n if (x !== y) return x < y ? -1 : 1;\n const i = String(a?.id ?? '');\n const j = String(b?.id ?? '');\n return i < j ? -1 : i > j ? 1 : 0;\n });\n}\n\n/**\n * One name per details step (#5535), the same on every surface (table, export,\n * response panel). Pass every details step to consider, in creation order:\n * that is the stable key, so rewiring the flow never renames a step. A step is\n * named by, first that applies: its label (unless blank or the default type\n * name), its config.title, else \"Details N\" (N = 1-based creation position).\n * Steps that end up with the same name each get \" N\" appended.\n * Steps are sorted here by created_at then id (a duplicated form inserts every\n * node with one now(), so created_at alone can tie), so no caller can drift.\n * Returns Map<nodeId, name>.\n * With `recall` (5696) a label or title holding recall codes shows its chip labels.\n */\nexport function detailsStepNames(detailsNodes, recall) {\n const defaultLabel = NODE_TYPE_DEFS.details.label;\n const clean = (v) => (typeof v === 'string' ? (recall ? recallDisplayText(v, recall) : v).trim() : '');\n const nodes = sortDetailsSteps(detailsNodes);\n const names = nodes.map((node, i) => {\n const label = clean(node?.label);\n if (label && label !== defaultLabel) return label;\n const title = clean(node?.config?.title);\n if (title) return title;\n return `${defaultLabel} ${i + 1}`;\n });\n const counts = new Map();\n for (const name of names) counts.set(name, (counts.get(name) ?? 0) + 1);\n const out = new Map();\n nodes.forEach((node, i) => {\n out.set(node.id, counts.get(names[i]) > 1 ? `${names[i]} ${i + 1}` : names[i]);\n });\n return out;\n}\n\n/**\n * The columns a form's details steps produce in the Responses table and the\n * CSV/Excel export (#5535). One rule for both: a field or agreement asked in\n * one step is one column (bare id, no nodeId); asked in more than one step it\n * is one column per step, named after the step. The first step keeps the bare\n * id (so an existing pin keeps working); later steps get `${id}:${nodeId}`.\n * `detailsNodes` are sorted here by created_at then id (the order\n * detailsStepNames numbers them in); `stepNames` is detailsStepNames'\n * map (node id -> step name), so every surface names a step the same way.\n * Returns { fields: [{ id, fieldId, label, nodeId? }],\n * consent: [{ id, itemId, label, hasDocument, nodeId? }] }.\n */\nexport function detailsColumns(detailsNodes, stepNames) {\n const nodes = sortDetailsSteps(detailsNodes);\n const fieldSteps = new Map();\n const itemSteps = new Map();\n for (const node of nodes) {\n for (const field of node?.config?.fields ?? []) {\n if (!field?.id) continue;\n const set = fieldSteps.get(field.id) ?? new Set();\n set.add(node.id);\n fieldSteps.set(field.id, set);\n }\n for (const item of node?.config?.consent_items ?? []) {\n if (!item?.id) continue;\n const set = itemSteps.get(item.id) ?? new Set();\n set.add(node.id);\n itemSteps.set(item.id, set);\n }\n }\n const fields = [];\n const consent = [];\n const seenField = new Map();\n const seenItem = new Map();\n nodes.forEach((node) => {\n const title = () => (stepNames?.get(node.id) ?? NODE_TYPE_DEFS.details.label);\n for (const field of node?.config?.fields ?? []) {\n if (!field?.id) continue;\n const seen = seenField.get(field.id) ?? new Set();\n if (seen.has(node.id)) continue;\n const first = seen.size === 0;\n seen.add(node.id);\n seenField.set(field.id, seen);\n const name = contactFieldLabel({ id: field.id, label: field.label, is_custom: field.is_custom });\n if (fieldSteps.get(field.id).size <= 1) {\n fields.push({ id: field.id, fieldId: field.id, label: name });\n } else {\n fields.push({\n id: first ? field.id : `${field.id}:${node.id}`,\n fieldId: field.id,\n label: `${name} - ${title()}`,\n nodeId: node.id,\n });\n }\n }\n for (const item of node?.config?.consent_items ?? []) {\n if (!item?.id) continue;\n const seen = seenItem.get(item.id) ?? new Set();\n if (seen.has(node.id)) continue;\n const first = seen.size === 0;\n seen.add(node.id);\n seenItem.set(item.id, seen);\n const name = item.name || 'Agreement';\n const hasDocument = !!item.document;\n if (itemSteps.get(item.id).size <= 1) {\n consent.push({ id: `consent:${item.id}`, itemId: item.id, label: name, hasDocument });\n } else {\n consent.push({\n id: first ? `consent:${item.id}` : `consent:${item.id}:${node.id}`,\n itemId: item.id,\n label: `${name} - ${title()}`,\n hasDocument,\n nodeId: node.id,\n });\n }\n }\n });\n return { fields, consent };\n}\n\n// The details steps whose answers a column reads: its own step when scoped,\n// else every details step in the caller's order.\nfunction stepsFor(detailsNodeIds, column) {\n return column.nodeId ? [column.nodeId] : detailsNodeIds;\n}\n\nfunction answerOf(nodeResponses, nodeId) {\n if (!nodeResponses || !Object.hasOwn(nodeResponses, nodeId)) return undefined;\n const value = nodeResponses[nodeId]?.value;\n return value && typeof value === 'object' ? value : undefined;\n}\n\n/**\n * A details column's answer text (#5535). Scoped column (nodeId): that step's\n * answer only. Unscoped: first non-empty match across the details steps.\n * `nodeResponses` is a submission's node_responses map. Returns '' when none.\n */\nexport function detailsFieldValue(nodeResponses, detailsNodeIds, column) {\n for (const nodeId of stepsFor(detailsNodeIds, column)) {\n const fields = answerOf(nodeResponses, nodeId)?.fields;\n if (!Array.isArray(fields)) continue;\n const match = fields.find((f) => f?.id === column.fieldId);\n if (match?.value) {\n return typeof match.value === 'object' ? JSON.stringify(match.value) : String(match.value);\n }\n }\n return '';\n}\n\n/**\n * A details agreement column's stored record (#5535), same scoping as\n * detailsFieldValue. Undefined when the respondent has no record for it.\n */\nexport function detailsConsentValue(nodeResponses, detailsNodeIds, column) {\n for (const nodeId of stepsFor(detailsNodeIds, column)) {\n const consent = answerOf(nodeResponses, nodeId)?.consent;\n if (!Array.isArray(consent)) continue;\n const match = consent.find((c) => c?.id === column.itemId);\n if (match) return match;\n }\n return undefined;\n}\n\n/**\n * The write-side half of contactFieldLabel (#5586): a standard details field\n * (first_name, last_name, email, phone) is always the standard field, so its\n * stored label is dropped; a non-custom field with an id config does not define\n * becomes a custom field so it still has a real name. Pure - returns a new\n * array and never mutates the input. Non-array input passes through unchanged.\n * Returns { fields, ignoredLabels, madeCustom }: the ids whose label was\n * dropped (only when it differed from the config name, ignoring case) and the\n * ids converted to custom fields.\n */\nexport function normalizeContactFields(fields) {\n if (!Array.isArray(fields)) return { fields, ignoredLabels: [], keptStandard: [], madeCustom: [] };\n const ignoredLabels = [];\n const keptStandard = [];\n const madeCustom = [];\n const out = fields.map((field) => {\n if (!field || typeof field !== 'object' || typeof field.id !== 'string') return field;\n if (Object.hasOwn(CONTACT_FIELDS_MAP, field.id)) {\n const { label, ...rest } = field;\n const stored = typeof label === 'string' ? label.trim() : '';\n const differs = stored !== '' && stored.toLowerCase() !== CONTACT_FIELDS_MAP[field.id].label.toLowerCase();\n if (differs) ignoredLabels.push(field.id);\n else if (field.is_custom === true) keptStandard.push(field.id);\n return { ...rest, is_custom: false };\n }\n // A blank id is not a field we can name: leave it for validation, unnoted.\n if (!field.is_custom && field.id.trim() !== '') {\n madeCustom.push(field.id);\n return { ...field, is_custom: true, label: contactFieldLabel(field) };\n }\n return field;\n });\n return { fields: out, ignoredLabels, keptStandard, madeCustom };\n}\n\n// Notes stay one sentence each and well under the openapi warnings maxLength (2000).\nconst NOTE_MAX_IDS = 5;\nconst NOTE_MAX_ID_LENGTH = 40;\nfunction noteIds(ids) {\n const unique = [...new Set(ids)];\n const shown = unique\n .slice(0, NOTE_MAX_IDS)\n .map((id) => `\"${id.length > NOTE_MAX_ID_LENGTH ? id.slice(0, NOTE_MAX_ID_LENGTH) + '...' : id}\"`);\n const more = unique.length - NOTE_MAX_IDS;\n return shown.join(', ') + (more > 0 ? ` and ${more} more` : '');\n}\nconst standardNames = (ids) => [...new Set(ids)].map((id) => `\"${CONTACT_FIELDS_MAP[id]?.label ?? id}\"`).join(', ');\n\n/** Tool-result note for standard-field labels dropped by normalizeContactFields. */\nexport function ignoredContactLabelNote(ids) {\n return `Standard field(s) ${noteIds(ids)} always show their config name (${standardNames(ids)}), so their labels were ignored. ` +\n 'For other wording or another language, add a custom field ({ id, is_custom: true, label, type }).';\n}\n\n/** Tool-result note for standard ids sent as custom, kept as the standard field. */\nexport function keptStandardContactNote(ids) {\n return `Standard field(s) ${noteIds(ids)} cannot be custom, so they were kept as the standard field (${standardNames(ids)}).`;\n}\n\n/** Tool-result note for unknown non-custom ids converted to custom fields. */\nexport function madeCustomContactNote(ids) {\n return `Field(s) ${noteIds(ids)} are not standard fields (first_name, last_name, email, phone), so they were saved as custom fields.`;\n}\n\n/** All notes for a normalizeContactFields result (empty when nothing changed). */\nexport function contactFieldNotes(result) {\n const notes = [];\n if (result.ignoredLabels.length) notes.push(ignoredContactLabelNote(result.ignoredLabels));\n if (result.keptStandard?.length) notes.push(keptStandardContactNote(result.keptStandard));\n if (result.madeCustom.length) notes.push(madeCustomContactNote(result.madeCustom));\n return notes;\n}\n\n/**\n * Details-node consent item types (#5614). A value in CONSENT_TYPES passes\n * through; 'optional' / 'opt-in' / 'optin' (case-insensitive) mean 'opt_in';\n * undefined / null stay as they are (a missing type is allowed); anything else\n * becomes 'consent' (a required agreement). Pure.\n */\nexport function normalizeConsentType(type) {\n if (type === undefined || type === null) return type;\n const v = typeof type === 'string' ? type.trim().toLowerCase() : type;\n if (CONSENT_TYPES.includes(v)) return v;\n if (['optional', 'opt-in', 'optin', 'opt in'].includes(v)) return 'opt_in';\n return 'consent';\n}\n\n/**\n * Normalize every consent item's type. Pure - returns new objects and never\n * mutates the input. Non-array input passes through. `coerced` lists only the\n * items whose type actually changed.\n */\nexport function normalizeConsentItems(items) {\n if (!Array.isArray(items)) return { items, coerced: [] };\n const coerced = [];\n const out = items.map((item) => {\n if (!item || typeof item !== 'object') return item;\n const to = normalizeConsentType(item.type);\n if (to === item.type) return { ...item };\n coerced.push({ id: item.id, from: item.type, to });\n return { ...item, type: to };\n });\n return { items: out, coerced };\n}\n\n/** All notes for a normalizeConsentItems result (empty when nothing changed). */\nexport function consentItemNotes(result) {\n if (!result.coerced.length) return [];\n const clip = (v) => {\n const t = typeof v === 'string' ? v : v === undefined || v === null ? '(none)' : JSON.stringify(v) ?? String(v);\n return t.length > NOTE_MAX_ID_LENGTH ? t.slice(0, NOTE_MAX_ID_LENGTH) + '...' : t;\n };\n const shown = result.coerced\n .slice(0, NOTE_MAX_IDS)\n .map((c) => `\"${clip(typeof c.id === 'string' ? c.id : '(no id)')}\" (\"${clip(c.from)}\" -> \"${clip(c.to)}\")`);\n const more = result.coerced.length - NOTE_MAX_IDS;\n return [\n `Consent item(s) ${shown.join(', ')}${more > 0 ? ` and ${more} more` : ''} had a type that is not a consent type, so they were saved as shown. ` +\n 'Use \"consent\" for a required agreement or \"opt_in\" for an optional one.',\n ];\n}\n\n/**\n * Details-node field icons — single source of truth (#2826). Both the Builder\n * (ContactNode) and the Responses table resolve through resolveContactFieldIcon\n * so a field shows the same icon on both surfaces. Values are Lucide component\n * name strings; each consumer maps the string to the component.\n */\nexport {\n CONTACT_FIELD_TYPE_ICONS,\n CONTACT_FIELD_STANDARD_ICONS,\n CONTACT_FIELD_ICON_FALLBACK,\n resolveContactFieldIcon,\n} from './field-icons.js';\n\n/**\n * The public \"Templates\" workspace. Curated template forms live here (promoted\n * via scripts/promote-form.ts); the template gallery (GET /v1/forms/templates)\n * is scoped to this workspace so a form flagged is_template in ANY other\n * workspace can't leak into it (#1370). Re-exported from\n * apps/api/src/lib/constants.ts so api and scripts/promote-form.ts share one\n * definition.\n */\nexport const CLIPFORM_TEMPLATES_WORKSPACE_ID = \"00000000-0000-4000-b000-000000000100\";\n\n/**\n * Curated allowlist for the dashboard \"New Form -> Select Template\" picker,\n * in display order (#3928). This is the single curation lever for the picker -\n * `is_live` no longer trims it. Every template in the Templates workspace stays\n * `is_live=true` (so its poster/embed/preview resolves via the is_live-gated\n * public path, and marketing pages that embed a template never break); which\n * ones a user sees when creating a form is decided here.\n *\n * PROD `share_id`s. Templates get a fresh share_id when promoted dev->prod\n * (scripts/promote-form.ts mints a new dynamic_link), so these match nothing in\n * dev - GET /v1/forms/templates falls back to showing all templates when the\n * allowlist matches none (see list-templates.ts). So this curates prod; dev\n * shows everything. Every id here MUST be is_live=true or its preview 404s.\n */\nexport const TEMPLATE_PICKER_SHARE_IDS = [\n \"78a5fc05c\", // Client Intake\n \"51e1b300b\", // Customer Feedback\n \"0f9c3f829\", // Event Registration\n \"3986f0fbb\", // Lead Capture\n \"14868ac21\", // Video Testimonial\n \"13fe6ff6a\", // Video Interview\n \"b9d64f65c\", // General Knowledge Quiz\n];\n\n/**\n * Node type definitions — re-exported from node-types.js\n */\nexport {\n NODE_TYPES,\n NODE_TYPES_LIST,\n getActiveNodeTypes,\n ACTIVE_NODE_TYPES,\n NODE_TYPE_KEYS,\n END_SCREEN_ICONS,\n resolveEndScreenIcon,\n OWNER_SCOPED_CONFIG_KEYS,\n gatedConfigKeys,\n gatedEnumValues,\n stripGatedConfigKeys,\n validateFeatureMarkers,\n RESPONSE_FORMATS,\n CONSENT_TYPES,\n CONTACT_FIELD_TYPES,\n CHOICE_MAX_OPTIONS,\n CHOICE_MAX_LETTERS_OPTIONS,\n CHOICE_MAX_OPTION_LENGTH,\n DRAW_GAME_DEFAULT_TIERS,\n isDarkPaper,\n inkFor,\n DEFAULT_OPTIONS_REVEAL_SECONDS,\n DEFAULT_MAX_RECORDING_SECONDS,\n BOOKING_WEEKDAYS,\n GOOGLE_MEET_BOOKING_DEFAULTS,\n MAX_RECORDING_SECONDS_MIN,\n MAX_RECORDING_SECONDS_MAX,\n cameraCaptureUnit,\n resolveCameraCaptureOrder,\n cameraCaptureSources,\n NODE_TYPE_METADATA,\n RESPONSE_SCHEMAS,\n CONFIG_SCHEMAS,\n OUTPUT_SCHEMAS,\n TERMINAL_TYPES,\n NON_COUNTABLE_TYPES,\n NON_COUNTABLE_FILTER,\n RESULTS_EXCLUDED_TYPES,\n PUBLIC_RESULTS_EXCLUDED_TYPES,\n PII_NODE_TYPES,\n RESPONDENT_MEDIA_NODE_TYPES,\n FILE_ANSWER_NODE_TYPES,\n RESPONSES_EXCLUDED_TYPES,\n STEP_COUNTED_TYPES,\n ANON_MCP_BLOCKED_NODE_TYPES,\n ANON_MCP_OUTBOUND_LINK_RULES,\n ANON_MCP_STRIPPED_FIELD_RULES,\n ANON_MCP_KEPT_TEXT_KEYS,\n isAnonMcpLockedNode,\n stripAnonMcpLockedNode,\n isTerminalType,\n countsAsStep,\n} from './node-types.js';\n\nexport {\n validateAgainstSchema,\n validateConfig,\n validateOptions,\n lettersCapError,\n maxOptionsError,\n validateResponse,\n validateOutput,\n collectsResponse,\n} from './validate.js';\n\nexport { FEATURE_FLAGS, FEATURES, getLiveFeatures, getPlannedFeatures, getFeaturesByCategory, getWhatsNew, getAnnouncements, getUnreadAnnouncements, getRecentAnnouncements, isNewFeature, WHATS_NEW_POPUP_LIMIT, ANNOUNCE_PALETTES, INTEGRATION_COMPANY_ALLOWLIST, companyHasIntegration, companyHasAnyIntegration, NODE_COMPANY_ALLOWLIST, companyHasNodeType, FEATURE_COMPANY_ALLOWLIST, companyHasPublicResults, companyHasCustomDomains, companyHasConsentDocuments, companyHasResponseSummary, companyHasMultiSelect, companyHasResponseTrash, companyHasVariables, companyHasTranscriptCopy, companyHasMediaPlayer, getFeatureAccess, getFeatureAllowlist, combineFeatureAccess } from './features.js';\n\nexport { DIGEST_EMAIL_KEY, ACTIVATION_STEP_EVENT, ACTIVATION_STEP_KINDS, ACTIVATION_STEP_SOURCES, USER_FAILURE_EVENT, USER_FAILURE_REASONS, PENDING_ACTION_CEILING_MS, ANALYTICS_METRICS, FORM_EVENTS, TEMPLATE_TOUR_EVENTS, RESULT_STAT_LABELS, ANALYTICS_INVARIANTS, ANALYTICS_BREAKDOWNS, ANALYTICS_FUNNEL_ORDER, ANALYTICS_EXCLUDED_TRIGGERS, LIFECYCLE_EVENTS, getMetricLabel, normalizeCountryFilter } from './analytics.js';\n\n/**\n * Form type definitions — re-exported from form-types.js\n */\nexport {\n FORM_TYPES,\n FORM_TYPES_LIST,\n FORM_TYPE_KEYS,\n WORKFLOW_TYPES,\n FORM_TYPE_ALIASES,\n ALL_VARIANTS,\n resolveFormType,\n getDiscoveryParams,\n isFormTypeAvailable,\n getAvailableFormTypes,\n} from './form-types.js';\n\nexport { validateFormForPublish, getNodeContentError, buildAdjacencyMap, getReachableIds, resolveRedirectUrl, resolveLinkListConfig } from './graph-validation.js';\n\n/**\n * Video template layer (#1736) — re-exported from video-templates.js. Data\n * + a pure expander that fills a curated control surface into Scene props;\n * video templates render through the existing Scene composition, never a\n * new primitive.\n */\nexport { VIDEO_TEMPLATE_REGISTRY, VIDEO_TEMPLATE_NAMES, buildVideoTemplate, exposedVideoTemplateNames, VIDEO_LOOK_NAMES, expandVideoLook, resolveVideoStyle, KEN_BURNS_RANDOM_POOL, SLIDESHOW_MAX_ITEMS, SLIDESHOW_COMPOSITION_TRANSITIONS, SLIDESHOW_TRANSITION_DURATION, NARRATION_TAIL_SECONDS, isHttpUrl, HTTP_URL_MESSAGE } from './video-templates.js';\n\n/**\n * Form update accept-list — re-exported from form-update-fields.js\n * (source of truth for the fields PATCH /v1/forms/:id accepts, #1219)\n */\nexport { FORM_UPDATE_FIELDS, FORM_UPDATE_FIELD_KEYS } from './form-update-fields.js';\n\n/**\n * Starter-form archetype resolver (#3600) — re-exported from starter-forms.js.\n * Maps a marketing page (use-case/for-page/blog) to a workflow archetype and\n * (once #3599 fills ARCHETYPE_STARTERS) a concrete starter form share_id for\n * \"Build\" CTAs. Blank-safe: every archetype's starter is 'TBD' until #3599\n * lands, so resolveStarterForm returns null everywhere in this PR.\n */\nexport {\n STARTER_ARCHETYPES,\n ARCHETYPE_STARTERS,\n USE_CASE_ARCHETYPE,\n PERSONA_ARCHETYPE,\n BLOG_CATEGORY_ARCHETYPE,\n BASIC_STARTER_SHARE_ID,\n STARTER_FORM_TITLE,\n UNTITLED_FORM_TITLE,\n IMPORTED_FORM_TITLES,\n DEFAULT_FORM_TITLES,\n isUnsetFormTitle,\n resolveArchetype,\n resolveStarterForm,\n} from './starter-forms.js';\n\n/**\n * Placement tag vocabulary (#2017) — re-exported from placement-tags.js. The\n * closed `for:*`/`usecase:*` namespace mirrored against active `/for/*` and\n * `/use-case/*` marketing pages; write-time enforcement lives in\n * apps/api's set-form-tags route.\n */\nexport {\n PLACEMENT_FOR_ROLES,\n PLACEMENT_USECASE_WORKFLOWS,\n PLACEMENT_TAGS,\n isPlacementNamespace,\n invalidPlacementTags,\n} from './placement-tags.js';\n\n/** Reserved vanity-link slugs (#3273, #4493) - API validation + dashboard client check. */\nexport { RESERVED_VANITY_SLUGS } from './reserved-slugs.js';\nexport { DRAW_PRESETS, DRAW_PRESET_GROUPS, DRAW_PRESET_IDS, DRAW_PRESET_PATH_PREFIX, getDrawPreset, drawPresetPath } from './draw-presets.js';\n\n/**\n * Signup origin vocabulary (#4026) — re-exported from signup-origin.js. The\n * first-touch acquisition dimension for account creation (MCP/bot channel,\n * direct web/email, or the /try anonymous builder).\n */\nexport {\n SIGNUP_ORIGINS,\n isSignupOrigin,\n} from './signup-origin.js';\n\n/**\n * Connector signup origin resolver (#4048) - resolves an OAuth `client_id`\n * string (ChatGPT/Claude contain the provider's own domain) to the\n * SignupOrigin a logged-out connector visitor's signup should be tagged\n * with, instead of the generic web/email default. Resolved from the\n * client_id string, NOT a DB lookup - `oauth_clients` RLS has no anon SELECT\n * policy, so a logged-out visitor can never read it.\n */\nexport { connectorOriginFromClientId, connectorNameFromClientId } from './connector-signup-origin.js';\n\nexport {\n ANON_MCP_RESPONSE_CAP,\n ANON_MCP_STARTED_SESSION_MULTIPLE,\n ANON_MCP_STARTED_SESSION_CAP,\n ANON_MCP_LIVE_TTL_DAYS,\n ANON_MCP_UPLOADS_PER_SESSION,\n} from './anon-mcp-limits.js';\n\n/** Builder chat turn time budget (#6139): server persona + dashboard client timeout. */\nexport { BUILDER_CHAT_TURN_TIMEOUT_MS, BUILDER_CHAT_CLIENT_TIMEOUT_MS } from './builder-chat-limits.js';\n\n/**\n * Node logic grammar constants — re-exported from logic-types.js\n */\nexport {\n LOGIC_ACTION_TYPES,\n LOGIC_CONDITION_OPS,\n LOGIC_VAR_TYPES,\n LOGIC_TARGET_TYPES,\n LOGIC_REMAPPABLE_VAR_TYPES,\n ROUTABLE_VARIABLES,\n getFormVariableIds,\n isBranchingActive,\n isMultiSelectChoice,\n gateSelectionMode,\n gateNodeSelectionMode,\n gateNodesSelectionMode,\n isAnswerKeyActive,\n isCorrectOption,\n isOptionEdge,\n isInactiveOptionEdge,\n isNodeLevelAction,\n replaceNodeLevelActions,\n dropStaleRefs,\n ensureNodeVarFallback,\n actionReferenceErrors,\n} from './logic-types.js';\n\n/**\n * Pure, branch-aware logic-chain graph helpers — re-exported from\n * logic-chain.js (#1058). apps/api's DB-backed chain ops (getOrderedNodes,\n * insertAfter, removeFromChain, findLastBeforeTerminal) call these.\n */\nexport {\n outgoingTargets,\n isBranched,\n defaultTarget,\n bfsOrder,\n computeRemovalRewrites,\n} from './logic-chain.js';\n\n/**\n * Template walkthrough notes and company checklists on node.config.guide (#6269, #6275) - re-exported from guide.js.\n */\nexport {\n GUIDE_CONFIG_KEY,\n GUIDE_LIMITS,\n GUIDE_TOUR_ANCHORS,\n GUIDE_SECTIONS,\n GUIDE_NODE_SECTIONS,\n guideSectionsFor,\n COMPANY_CHECKLIST_KINDS,\n checklistConnectableIntegrations,\n validateNodeGuide,\n mergeNodeGuide,\n stripNodeGuide,\n buildTemplateTourSteps,\n buildTemplateChecklist,\n buildTemplateTourIntro,\n} from './guide.js';\n\n/**\n * Integration catalog definitions — re-exported from integration-catalog.js\n */\nexport {\n INTEGRATION_CATALOG,\n INTEGRATION_CATALOG_LIST,\n INTEGRATION_SLUGS,\n getIntegrationsByCategory,\n getIntegrationsByTags,\n getIntegrationHubAccess,\n getHubIntegrations,\n} from './integration-catalog.js';\n\n/**\n * API key prefixes — shared between API (validation) and dashboard (generation)\n */\nexport const API_KEY_PREFIXES = ['cf_', 'cf_live_', 'cf_test_'];\nexport const API_KEY_PREFIX = 'cf_';\n\n/**\n * OAuth token prefixes — shared between the API's oauth.ts (minting/validation)\n * and api-key-auth.ts (distinguishing an OAuth token from a workspace API key)\n */\nexport const OAUTH_TOKEN_PREFIXES = ['cf_at_', 'cf_rt_', 'cf_code_'];\n\n/**\n * Input validation limits — shared between API routes and MCP server\n */\nexport const VALIDATION_LIMITS = {\n form: {\n title: { max: 1000 },\n nodes: { max: 100 },\n },\n node: {\n prompt: { max: 5000, media_max: 60 },\n options: { max: 50 },\n },\n workspace: {\n name: { max: 100 },\n },\n // company.name is varchar(255) (#4587: renamed from Company settings).\n company: {\n name: { max: 255 },\n },\n};\n\n/**\n * Theme defaults and colour validation — single source of truth\n * All colours must be 6-digit hex (#RRGGBB). No rgba, no shorthand.\n */\nexport const HEX_COLOR_REGEX = /^#[0-9A-Fa-f]{6}$/;\n\nexport const THEME_DEFAULTS = {\n primary_color: '#374151',\n background_color: '#F3F4F6',\n font_family: 'Inter',\n};\n\n/**\n * AI-protected form fields — fields the AI must NOT set unless the user\n * explicitly requests it. Everything else is AI-mutable (set freely).\n *\n * Used by MCP tools to guard descriptions and omit defaults.\n */\nexport const AI_PROTECTED_FIELDS = {\n font_family: {\n reason: 'Brand/design decision — do not set unless the user explicitly requests a different font.',\n },\n author: {\n reason: 'Brand identity — do not invent. Only set when the user provides a value.',\n },\n brand_name: {\n reason: 'Brand identity — do not invent. Only set when the user provides a value.',\n },\n logo_url: {\n reason: 'Brand identity — do not invent. Only set when the user provides a value.',\n },\n is_live: {\n reason: 'Going live is a deliberate action. Never auto-publish unless the user asks.',\n },\n};\n\n/**\n * Ken Burns / Slideshow constants — single source of truth.\n * Used by Remotion compositions, API slideshow route, and MCP tools.\n */\nexport const KEN_BURNS_EFFECTS = [\n 'pan-left',\n 'pan-right',\n 'pan-up',\n 'pan-down',\n 'zoom-in-pan-left',\n 'zoom-in-pan-right',\n 'zoom-in',\n 'zoom-out',\n 'static',\n];\n\nexport const KEN_BURNS_PRESETS = [\n 'cinematic',\n 'dramatic',\n 'calm',\n 'documentary',\n 'dreamy',\n 'moody',\n 'energetic',\n];\n\nexport const KEN_BURNS_EASINGS = ['ease-in-out', 'ease-in', 'ease-out', 'linear'];\n\nexport const KEN_BURNS_FIT_MODES = ['cover', 'blur-pad', 'auto'];\n\nexport const SLIDESHOW_TRANSITIONS = [\n 'fade',\n 'fadeblack',\n 'fadewhite',\n 'slideleft',\n 'slideright',\n 'circlecrop',\n 'circleopen',\n 'circleclose',\n 'dissolve',\n 'pixelize',\n 'radial',\n 'smoothleft',\n 'smoothright',\n 'wipeleft',\n 'wiperight',\n 'diagtl',\n 'diagbr',\n 'hblur',\n];\n\n// SLIDESHOW_COMPOSITION_TRANSITIONS (the narrow set Slideshow actually\n// renders, distinct from the broad ffmpeg list above) is DEFINED in\n// video-templates.js, next to the VIDEO_LOOKS code that consumes it, and\n// re-exported below - see that file for why. Defining it here and having\n// video-templates.js import it back created a real index.js <-> video-templates.js\n// import cycle (index.js already re-exports FROM video-templates.js), fixed\n// in #4038 review.\n\n/**\n * Composition IDs that require a Mapbox access token.\n * Map is the primitive (#453); GlobeToCity/CityToGlobe/MapPin are its\n * presets/aliases.\n */\nexport const MAP_COMPOSITIONS = ['Map', 'GlobeToCity', 'CityToGlobe', 'MapPin'];\n\n/**\n * Composition registry - single source of truth for which compositions the MCP\n * server exposes and at what access tier, plus their kind (for docs/tooling).\n *\n * - `tier`: 'public' (everyone) | 'labs' (non-prod, power users/dogfooding) |\n * 'social' (non-prod, marketing templates). The MCP PUBLIC/LABS/SOCIAL\n * lists derive from this (see packages/mcp-server/src/lib/config.ts).\n * - `kind`: 'bed' (full-bleed Scene layer 0) | 'overlay' (Scene asset layer) |\n * 'container' (Scene itself) | 'video' (whole standalone pre-baked video).\n * - `scene_layer`: usable as a Scene layer (#652). SCENE_LAYER_IDS in\n * packages/remotion derives from this - never hand-list layer ids there.\n * `kind` says where a comp sits when layered; `scene_layer` says whether it\n * may be (most beds render standalone only).\n *\n * Variant presets (e.g. a 'neon' Text) are NOT separate entries - they\n * are the base composition + a `preset` prop. Render-only/dev compositions\n * (test cards, Map preset-aliases, StatOverlay) are intentionally absent: they\n * are registered in Remotion but not advertised on the MCP. The GridList/\n * FourImageGrid/OddOneOutReveal Grid layout-aliases that used to live here\n * were deleted outright (#1615) - a list is just Grid with\n * `layout: { columns: 1 }`, not its own primitive. FlagReveal, ColorCards and\n * TitleCard were folded the same way (#1736) - they are VIDEO_TEMPLATE_REGISTRY\n * entries (video-templates.js) that expand onto Slideshow/Grid/Text through Scene,\n * not COMPOSITION_REGISTRY primitives.\n */\nexport const COMPOSITION_REGISTRY = [\n // Beds (full-bleed backgrounds)\n { id: 'Slideshow', tier: 'public', kind: 'bed', scene_layer: true },\n { id: 'Map', tier: 'public', kind: 'bed', scene_layer: true },\n { id: 'Grid', tier: 'public', kind: 'bed', scene_layer: true },\n { id: 'Timeline', tier: 'labs', kind: 'bed' },\n { id: 'Silhouette', tier: 'labs', kind: 'bed', scene_layer: true },\n // Overlays (assets layered on a bed)\n { id: 'Text', tier: 'labs', kind: 'overlay', scene_layer: true },\n { id: 'Rebus', tier: 'labs', kind: 'overlay', scene_layer: true },\n // Container\n { id: 'Scene', tier: 'labs', kind: 'container' },\n // Social marketing templates (gated)\n { id: 'ShortFormQuiz', tier: 'social', kind: 'video' },\n { id: 'ScorecardQuiz', tier: 'social', kind: 'video' },\n { id: 'ScorecardGK', tier: 'social', kind: 'video' },\n { id: 'CountrySilhouetteQuiz', tier: 'social', kind: 'video' },\n];\n\nconst compositionIdsByTier = (tier) =>\n COMPOSITION_REGISTRY.filter((c) => c.tier === tier).map((c) => c.id);\n\nexport const PUBLIC_COMPOSITION_IDS = compositionIdsByTier('public');\nexport const LABS_COMPOSITION_IDS = compositionIdsByTier('labs');\nexport const SOCIAL_COMPOSITION_IDS = compositionIdsByTier('social');\n\n/**\n * The composition surface exposed for a given environment (#1674, #1789).\n * `labs`/`social` are a pure environment gate - not a per-workspace/billing\n * concept - so this takes a single boolean rather than reading `process.env`\n * itself (this package stays dependency-free; callers resolve NODE_ENV at\n * their own edge). Single derivation shared by the MCP server\n * (packages/mcp-server/src/lib/config.ts) and the API's render gate\n * (apps/api/src/routes/internal/render.ts) - never hand-roll a second copy\n * of this list.\n */\nexport function exposedCompositionIds(includeNonPublic) {\n return [\n ...PUBLIC_COMPOSITION_IDS,\n ...(includeNonPublic ? LABS_COMPOSITION_IDS : []),\n ...(includeNonPublic ? SOCIAL_COMPOSITION_IDS : []),\n ];\n}\n\n/** Compositions usable as Scene layers (#652) - the single source for\n * SCENE_LAYER_IDS in packages/remotion and (via sync-schemas) the API's\n * per-layer validation allowlist. */\nexport const SCENE_LAYER_COMPOSITION_IDS = COMPOSITION_REGISTRY\n .filter((c) => c.scene_layer)\n .map((c) => c.id);\n\n/**\n * Minimum plan tier for an MCP tool to appear in tools/list on the remote\n * (OAuth) MCP server (#471). Tools not listed default to 0 (every plan).\n * Presentation-level only - real enforcement (rate limits, plan checks)\n * stays in the API routes. stdio/API-key sessions always see all tools.\n *\n * To gate a tool, add e.g. `clipform_render_composition: 1`.\n */\nexport const MCP_TOOL_TIERS = {};\n\n/**\n * Connect-time MCP toolset partition (#3309). A client may opt into a subset\n * of tools via `/mcp?features=account,forms,media` (apps/api/src/mcp/handler.ts),\n * so `tools/list` only ships the schemas it needs - a form-only client drops\n * the media-tool payload entirely instead of downloading it and ignoring it.\n * Every registered clipform_* tool maps to exactly ONE toolset here - enforced\n * by a parity test that statically walks packages/mcp-server/src (same\n * pattern as MCP_TOOL_TIERS' sibling tests).\n *\n * This is a DIFFERENT axis than apps/api/src/lib/tool-phases.ts: tool-phases\n * groups tools by build STEP (research/build/attach) for the dashboard bot's\n * dynamic per-turn filtering, and its RESEARCH_TOOLS list straddles both\n * `forms` and `media` below. Toolsets group by connect-time CLIENT INTENT\n * (account/forms/research/media) and are static for the life of a session -\n * one grouping per axis, not a re-label of the other.\n *\n * `research` (#3681) holds the content-research helpers that proxy third\n * parties or exist only for generation workflows (news lookup, generation\n * audit log). They are excluded from the Claude Connectors Directory surface\n * (mcp.clipform.io/forms = account + forms) so that surface is pure first\n * party form building - a client with native web search has no use for them.\n */\nexport const MCP_TOOLSETS = ['account', 'forms', 'research', 'media'];\n\n/**\n * Tools registered only per session, not by default (#6052): dark behind a company allowlist, so\n * `createServer()` / stdio leave them out and apps/api opts in per request. Parity tests that\n * compare MCP_TOOL_TOOLSETS with the default surface skip these.\n * clipform_set_node_guide: template walkthrough notes (#6269), template_walkthrough allowlist.\n */\nexport const MCP_SESSION_GATED_TOOLS = Object.freeze(['clipform_set_link_variables', 'clipform_set_node_guide']);\n\nexport const MCP_TOOL_TOOLSETS = {\n // account: workspace/account-scoped read + admin tools.\n clipform_list_forms: 'account',\n clipform_get_form: 'account',\n clipform_delete_form: 'account',\n clipform_whoami: 'account',\n clipform_get_results: 'account',\n clipform_get_responses: 'account',\n\n // forms: form/node structure + craft guidance used while building.\n clipform_create_form: 'forms',\n clipform_import_form: 'forms',\n clipform_add_node: 'forms',\n clipform_update_node: 'forms',\n clipform_delete_node: 'forms',\n clipform_update_form: 'forms',\n clipform_set_logic: 'forms',\n clipform_set_link_variables: 'forms',\n clipform_set_node_guide: 'forms',\n clipform_get_guide: 'forms',\n clipform_get_workflow: 'forms',\n\n // research: third-party content lookup + generation-workflow audit.\n clipform_search_news: 'research',\n clipform_log_generation: 'research',\n\n // media: creative/render/asset tools. fetch_boundary only feeds the Map\n // composition's `boundary` prop, so it lives with the render tools.\n clipform_fetch_boundary: 'media',\n clipform_generate_tts: 'media',\n clipform_render_composition: 'media',\n clipform_render_video_template: 'media',\n clipform_check_render: 'media',\n clipform_upload_media_asset: 'media',\n clipform_complete_media_upload: 'media',\n clipform_attach_node_media: 'media',\n clipform_get_node_media: 'media',\n clipform_delete_node_media: 'media',\n clipform_search_media: 'media',\n clipform_search_music: 'media',\n clipform_list_compositions: 'media',\n clipform_list_assets: 'media',\n clipform_list_video_templates: 'media',\n};\n\n/**\n * Per-tool OAuth security declaration (#4088) - the OpenAI Apps SDK\n * convention for telling a host \"anonymous calls work, linking unlocks\n * privileged behaviour.\" This is NOT part of the MCP core spec (the Tool\n * type has no `securitySchemes` field), but the Apps SDK's own reference\n * implementation emits it as a TOP-LEVEL `securitySchemes` key on each\n * `tools/list` entry (not an `mcp/`-namespaced `_meta` key - no host reads\n * one). OpenAI's own reference docs (developers.openai.com/plugins/reference,\n * tool descriptor `_meta` table) separately document an un-namespaced\n * `_meta.securitySchemes` as a back-compat MIRROR of the same array, for a\n * client that only reads `_meta` - packages/mcp-server's server.ts sets\n * BOTH (top-level + the `_meta` mirror) from this one array via its\n * `tools/list` wrapper, so they can never drift from each other. See\n * api-client.ts's `authChallengeMeta` for the separate runtime half of the\n * contract (a tool result's own `_meta[\"mcp/www_authenticate\"]` carries the\n * matching WWW-Authenticate challenge when a feature actually needs an\n * account).\n *\n * Every tool that can run anonymously declares the mixed scheme `noauth` +\n * `oauth2`; a `sign_in` tool (MCP_ANON_TOOLS below, #4657) declares\n * `oauth2` only, because it has nothing to show an anonymous caller.\n * `scopes` matches apps/api/src/mcp/handler.ts's REQUIRED_SCOPE (\"mcp\").\n *\n * Derived off MCP_TOOL_TOOLSETS's own key set (every registered tool already\n * has exactly one toolset entry there) so the two tables structurally can't\n * drift apart - a newly registered clipform_* tool that's missing from\n * MCP_TOOL_TOOLSETS fails that table's own parity test first. A static\n * parity test mirroring toolset-parity.test.ts additionally re-derives the\n * registered-tool list directly from packages/mcp-server/src/tools, so a\n * tool can never ship with no MCP_TOOL_SECURITY entry at all.\n */\nexport const MCP_TOOL_SECURITY_SCHEMES = Object.freeze([\n Object.freeze({ type: 'noauth' }),\n Object.freeze({ type: 'oauth2', scopes: ['mcp'] }),\n]);\n\n/** The `oauth2`-only declaration for a `sign_in` tool (#4657). */\nexport const MCP_TOOL_SECURITY_SCHEMES_SIGN_IN = Object.freeze([\n Object.freeze({ type: 'oauth2', scopes: ['mcp'] }),\n]);\n\n/**\n * Anonymous-access classification of every registered MCP tool (#4657) - the\n * ONE allowlist behind the anonymous boundary. Before this the boundary was a\n * denylist of one (the publish gate, since removed in #4847), so every other anonymous tools/call\n * without a form_id minted a throwaway workspace just to answer from an empty\n * one (list_forms, whoami, get_results ...).\n *\n * - `anon`: runs for an anonymous caller inside the caller's own anon\n * workspace (build tools, `get_form` by form_id, media + research tools -\n * media keeps the existing expensive-op throttle).\n * - `anon_no_workspace`: runs anonymously but needs NO workspace (static craft\n * content and the static creative-asset catalog), so a request made only of\n * these never mints and runs with no credential at all.\n * - `sign_in`: needs a signed-in account. An anonymous call is refused before\n * any mint (apps/api/src/mcp/handler.ts).\n *\n * `sign_in` is the DEFAULT (see `getMcpAnonAccess`): a tool with no entry is\n * refused to anonymous callers. The parity test\n * (packages/mcp-server/src/__tests__/anon-tools-parity.test.ts) still demands\n * an explicit entry per registered tool so the choice is always deliberate.\n */\nexport const MCP_ANON_ACCESS_LEVELS = ['anon', 'anon_no_workspace', 'sign_in'];\n\nexport const MCP_ANON_TOOLS = Object.freeze({\n // account\n clipform_list_forms: 'sign_in',\n clipform_get_form: 'anon',\n clipform_delete_form: 'sign_in',\n clipform_whoami: 'sign_in',\n clipform_get_results: 'sign_in',\n clipform_get_responses: 'sign_in',\n\n // forms\n clipform_create_form: 'anon',\n clipform_import_form: 'anon',\n clipform_add_node: 'anon',\n clipform_update_node: 'anon',\n clipform_delete_node: 'anon',\n clipform_update_form: 'anon',\n clipform_set_logic: 'anon',\n clipform_set_link_variables: 'sign_in',\n clipform_set_node_guide: 'sign_in',\n clipform_get_guide: 'anon_no_workspace',\n clipform_get_workflow: 'anon_no_workspace',\n\n // research\n clipform_search_news: 'anon',\n clipform_log_generation: 'anon',\n\n // media\n clipform_fetch_boundary: 'anon',\n clipform_generate_tts: 'anon',\n clipform_render_composition: 'anon',\n clipform_render_video_template: 'anon',\n clipform_check_render: 'anon',\n clipform_upload_media_asset: 'anon',\n clipform_complete_media_upload: 'anon',\n clipform_attach_node_media: 'anon',\n clipform_get_node_media: 'anon',\n clipform_delete_node_media: 'anon',\n clipform_search_media: 'anon',\n clipform_search_music: 'anon',\n clipform_list_compositions: 'anon',\n clipform_list_assets: 'anon_no_workspace',\n clipform_list_video_templates: 'anon',\n});\n\n/**\n * Virtual tools the `@posthog/mcp` wrapper injects into tools/list (e.g.\n * `get_more_tools`, packages/mcp-server's instrumentServer) - never registered\n * by packages/mcp-server/src/tools, so deliberately not in MCP_ANON_TOOLS. They\n * need no API or workspace, so they are `anon_no_workspace` (#4657).\n */\nexport const MCP_VIRTUAL_TOOLS = Object.freeze(['get_more_tools']);\n\n/** Anonymous access level for a tool; an unclassified tool is `sign_in`. */\nexport function getMcpAnonAccess(toolName) {\n if (MCP_VIRTUAL_TOOLS.includes(toolName)) return 'anon_no_workspace';\n return Object.prototype.hasOwnProperty.call(MCP_ANON_TOOLS, toolName)\n ? MCP_ANON_TOOLS[toolName]\n : 'sign_in';\n}\n\nexport const MCP_TOOL_SECURITY = Object.freeze(\n Object.fromEntries(\n Object.keys(MCP_TOOL_TOOLSETS).map((name) => [\n name,\n getMcpAnonAccess(name) === 'sign_in'\n ? MCP_TOOL_SECURITY_SCHEMES_SIGN_IN\n : MCP_TOOL_SECURITY_SCHEMES,\n ])\n )\n);\n\n/**\n * Workspace-library MCP tools with no form_id of their own to resolve a\n * workspace off (#4621) - they write/read the workspace media library\n * directly, never a node. An anonymous MCP request made up ENTIRELY of\n * calls to these tools, with no form_id anywhere in it, would otherwise\n * mint a brand-new throwaway workspace (same mint branch as create_form),\n * so the result lands somewhere clipform_attach_node_media can never find\n * it - apps/api/src/mcp/anon-form-context.ts's requiresFormContext() blocks\n * that shape before the mint runs. Each tool here must declare a `form_id`\n * input (packages/mcp-server's formIdTargetInput, workspace-target.ts) -\n * form-context-schema.test.ts asserts it off this SAME array, so the two\n * halves of this fix can never drift apart. clipform_list_assets is\n * deliberately excluded: it serves static, non-workspace-scoped creative\n * assets (handleAssets - apps/api/src/lib/creative-handlers.ts), so gating\n * it would 400 an anon agent for simply listing available fonts/sfx, with\n * no orphan-asset bug to fix.\n */\nexport const MCP_TOOLS_REQUIRING_FORM_CONTEXT = [\n 'clipform_upload_media_asset',\n 'clipform_generate_tts',\n 'clipform_complete_media_upload',\n];\n\n/**\n * Form-scoped MCP tools whose input REQUIRES a form_id (#4717): they edit or\n * read an existing form or node, so a call without one can never succeed in a\n * freshly minted (empty) anonymous workspace. Same treatment as\n * MCP_TOOLS_REQUIRING_FORM_CONTEXT above: an anonymous request made up entirely\n * of these, with no form_id and no session binding (#4652), is refused before\n * the mint instead of creating a throwaway account. Kept separate because these\n * tools' form_id is required (the #4621 tools take an optional target form_id).\n * form-context-schema.test.ts asserts each declares a required form_id, and that\n * every anon tool with a required form_id input is listed here.\n */\nexport const MCP_TOOLS_REQUIRING_FORM_ID = [\n 'clipform_get_form',\n 'clipform_add_node',\n 'clipform_update_node',\n 'clipform_delete_node',\n 'clipform_update_form',\n 'clipform_set_logic',\n 'clipform_log_generation',\n 'clipform_attach_node_media',\n 'clipform_get_node_media',\n 'clipform_delete_node_media',\n];\n\n/**\n * Documentation RAG embeddings (the `docs.chunks` vector store powering the\n * dashboard docs chatbot). SINGLE SOURCE OF TRUTH for the OpenAI embedding\n * model + dimensions.\n *\n * BOTH sides must use these or retrieval silently breaks: the ingest side\n * (`scripts/embed-docs.mjs`, which writes the chunk vectors) and the query\n * side (`apps/api/src/routes/v1/docs/chat.ts`, which embeds the user's\n * question). If they drift, questions get embedded in a different vector\n * space than the stored chunks and `match_chunks` returns garbage.\n *\n * Pinned to 1536 dims (not text-embedding-3-large's native 3072) so the\n * vectors fit the `docs.chunks vector(1536)` column AND stay under pgvector's\n * 2000-dim HNSW index limit - no schema migration needed. Changing either\n * value requires a full re-embed (`FULL_REEMBED=1 node scripts/embed-docs.mjs`):\n * a model/dim swap doesn't change content hashes, so the incremental path\n * would skip every chunk.\n */\nexport const DOCS_EMBEDDING_MODEL = 'text-embedding-3-large';\nexport const DOCS_EMBEDDING_DIMENSIONS = 1536;\n\n/**\n * Effective response-moderation setting for a form (#1835, #1837). The form's\n * `moderate_responses` wins when set (true or false); null/undefined inherits\n * the workspace default. A missing workspace value defaults to true (moderation\n * on), matching the workspaces column's `NOT NULL DEFAULT true`. Shared by the\n * API (what gets checked) and the dashboard (whether flagged answers blur).\n */\nexport function resolveEffectiveModeration(form, workspace) {\n const formValue = form?.moderate_responses;\n if (formValue === true || formValue === false) return formValue;\n return workspace?.moderate_responses ?? true;\n}\n\n/**\n * Clip caps (#4622). A render or voiceover is for ONE step node in a Clipform\n * form, so it is short. Single source for the API checks (production) and the\n * MCP tool copy. 400 chars of narration is about 27s of speech.\n */\nexport const MAX_CLIP_SECONDS = 30;\nexport const MAX_NARRATION_CHARS = 400;\n\n/**\n * Grid cadence defaults and animation floor (#4622). Single source: remotion's\n * grid-timing imports these, and the API's clip-length gate mirrors Grid's real\n * length with them (a caller-set stagger/entrance/reveal stretches the clip).\n */\nexport const GRID_DEFAULT_STAGGER_SECONDS = 0.45;\nexport const GRID_DEFAULT_ENTRANCE_SECONDS = 0.5;\nexport const GRID_DEFAULT_REVEAL_SECONDS = 0.5;\n\n/** The animation's own end (entrances + reveal + a short settle) - the clip never shortens below it. */\nexport function gridMinSeconds(cellCount, timing) {\n const stagger = timing?.staggerSeconds ?? GRID_DEFAULT_STAGGER_SECONDS;\n const entrance = timing?.entranceSeconds ?? GRID_DEFAULT_ENTRANCE_SECONDS;\n const reveal = timing?.revealSeconds ?? GRID_DEFAULT_REVEAL_SECONDS;\n return (cellCount - 1) * stagger + entrance + reveal + 0.5;\n}\n\n/**\n * Custom form variables (#5647) - key rules, coercion and the shared\n * deriveVariables engine, re-exported from variables.js.\n */\nexport {\n VARIABLE_KEY_MAX_LENGTH,\n VARIABLE_KEY_PATTERN,\n VARIABLE_TYPES,\n VARIABLE_TEXT_MAX_LENGTH,\n VARIABLE_LABEL_MAX_LENGTH,\n VARIABLE_NUMBER_MAX,\n VARIABLE_MAX_CUSTOM_PER_FORM,\n SAVE_TO_NODE_TYPES,\n SAVE_TO_OPS,\n RESERVED_VARIABLE_KEYS,\n RESERVED_VARIABLE_KEY_PREFIXES,\n isReservedVariableKey,\n validateVariableKey,\n coerceVariableValue,\n validateSaveTo,\n optionValueError,\n deriveVariables,\n pointsAvailable,\n scoreLinePreset,\n hasPointOptions,\n choiceQuestionKind,\n choicePoints,\n CHOICE_POINTS_MAX,\n qualifiesForScoreWiring,\n withScoreVariable,\n isWiredToVariable,\n nodeHasPointsMap,\n findScoreVariableId,\n customNumberKeys,\n findScoreVariable,\n nodeHasPointsFor,\n pointsDormantFor,\n withoutVariableRefs,\n addTargetVariable,\n optionPoints,\n legacyCategoryScores,\n pointsMapError,\n VARIABLE_MAX_LINK_PER_FORM,\n normalizeLinkValue,\n pickLinkValues,\n capRawLinkPairs,\n isUnsafeLinkChar,\n hasUnsafeLinkChar,\n stripUnsafeLinkChars,\n LINK_UNSAFE_RANGES,\n LINK_RAW_VALUE_MAX,\n LINK_RAW_KEY_MAX,\n LINK_RAW_PAIRS_MAX,\n LINK_RAW_TOTAL_MAX,\n VARIABLE_LINK_WARN_CHARS,\n isPersonalLinkKey,\n LINK_VARIABLE_PRESETS,\n linkVariablePreset,\n buildVariableLink,\n} from './variables.js';\n\n/** Third-party deep links (#6216), re-exported from third-party-links.js. */\nexport { THIRD_PARTY_LINKS } from './third-party-links.js';\nexport { KLAVIYO_KX_KEY, KLAVIYO_KX_MAX_LENGTH, isKlaviyoKx } from './klaviyo-kx.js';\nexport { EMAIL_LINK_IDS, isKitSubscriberId, emailLinkIdByStoreKey, emailLinkIdByVendor, isValidEmailLinkId } from './email-link-ids.js';\n\n/** Email tool tagging vocabulary (#6174), re-exported from email-tools.js. */\nexport {\n EMAIL_TOOL_TRIGGERS,\n EMAIL_TOOL_TRIGGER_IDS,\n EMAIL_TOOL_TAG_NAME_MAX,\n defaultEmailToolTagName,\n normalizeTagRules,\n respondentEmailPick,\n} from './email-tools.js';\n\n/**\n * Variable recall (#5671) - `{{key}}` short codes in node text, re-exported from recall.js.\n */\nexport {\n RECALL_TOKEN_SOURCE,\n RECALL_TOKEN_PATTERN,\n RECALL_RESERVED_LABELS,\n RECALL_FALLBACK_MAX_LENGTH,\n RECALL_CHIP_DISPLAY_LENGTH,\n parseRecallRef,\n parseRecallToken,\n sanitizeRecallFallback,\n RECALL_FIELD_ID_MAX_LENGTH,\n findRecallRefs,\n findRecallAnswerRefs,\n textUsesRecallAnswer,\n nodeUsesRecallAnswer,\n nodeRecallAnswerRefs,\n recallDisplayLength,\n recallAnswerText,\n formatRecallValue,\n findRecallKeys,\n textUsesRecallKey,\n valueUsesRecallKey,\n nodeUsesRecallKey,\n interpolateRecall,\n interpolateRecallParts,\n startingRecallValues,\n} from './recall.js';\n\n/**\n * What a recalled answer is called on every surface (#5696): the builder chip, owner tables, exports, webhooks. The node's\n * trimmed `label`, else its type's name; a Details field appends ` - <field label>`. `node` is a plain\n * `{ type, label, config }`.\n */\nexport function recallAnswerLabel(node, fieldId) {\n const label = typeof node?.label === 'string' ? node.label.trim() : '';\n const type = node?.type ?? '';\n const base = label || NODE_TYPE_DEFS[type]?.label || type;\n if (!fieldId) return base;\n const fields = Array.isArray(node?.config?.fields) ? node.config.fields : [];\n const f = fields.find((x) => x?.id === fieldId);\n return `${base} - ${contactFieldLabel({ id: fieldId, is_custom: f?.is_custom, label: f?.label })}`;\n}\n\nfunction variableDisplayName(key, variables) {\n const list = Array.isArray(variables) ? variables : [];\n const v = list.find((x) => x?.key === key);\n const label = typeof v?.label === 'string' ? v.label.trim() : '';\n if (label) return label;\n if (Object.hasOwn(RECALL_RESERVED_LABELS, key)) return RECALL_RESERVED_LABELS[key];\n return key;\n}\n\n/**\n * Owner-facing text for stored text with recall codes (#5696): each code becomes its chip label in square brackets\n * (`[Name]`, `[Score]`, `[Question - Email]`, `[Deleted question]`, `[Label · fallback]`). Surfaces that cannot show a\n * chip (tables, exports, webhooks) use it. A node label that itself holds codes renders one level deep, variables only\n * (a nested answer code is `[Earlier answer]`). Text without `{{` comes back as the same string.\n */\nexport function recallDisplayText(text, ctx) {\n if (typeof text !== 'string' || !text.includes('{{')) return text;\n const variables = ctx?.variables;\n const nodes = Array.isArray(ctx?.nodes) ? ctx.nodes : [];\n const render = (input, nested) =>\n input.replace(new RegExp(RECALL_TOKEN_SOURCE, 'g'), (_whole, ref, fallback) => {\n const parsed = parseRecallRef(ref);\n let name;\n if (parsed?.kind === 'answer') {\n if (nested) {\n name = 'Earlier answer';\n } else {\n const node = nodes.find((n) => n?.id === parsed.nodeId);\n if (!node) {\n name = 'Deleted question';\n } else {\n name = recallAnswerLabel(node, parsed.fieldId);\n if (name.includes('{{')) name = render(name, true);\n }\n }\n } else {\n name = variableDisplayName(parsed?.key ?? ref, variables);\n }\n return fallback !== undefined ? `[${name} · ${fallback}]` : `[${name}]`;\n });\n return render(text, false);\n}\n\n// Step pastel (NODE_TYPES[type].color) -> What's new palette family.\nexport const STEP_COLOR_PALETTE = {\n '#E9D5FF': 'violet',\n '#ECFCCB': 'lime',\n '#D1FAE5': 'lime',\n '#DBEAFE': 'sky',\n '#FFEDD5': 'peach',\n '#E0E7FF': 'indigo',\n};\n\n// FEATURES.category -> palette for launches that are not a step.\nconst CATEGORY_PALETTE = {\n builder: 'violet',\n ai: 'violet',\n analytics: 'sky',\n responses: 'sky',\n sharing: 'peach',\n integrations: 'indigo',\n api: 'lime',\n};\n\n/**\n * The mesh-gradient palette ({ name, stops, ink }) for a launch's pop-up hero:\n * an explicit `announce.palette`, else the step colour family for `node_<type>`\n * keys, else the feature's category, else sky.\n */\nexport function getAnnouncementPalette(key) {\n const feature = FEATURES[key];\n let name = feature?.announce?.palette;\n if (!name && key.startsWith('node_')) {\n name = STEP_COLOR_PALETTE[NODE_TYPE_DEFS[key.slice('node_'.length)]?.color];\n }\n if (!name) name = CATEGORY_PALETTE[feature?.category];\n if (!name) name = 'sky';\n return { name, ...ANNOUNCE_PALETTES[name] };\n}\n","import { BUSINESS } from \"@vid-master/config\";\nimport {\n getMcpAuth,\n MCP_ANONYMOUS_HEADER,\n MCP_AUTH_VIA_HEADER,\n MCP_MINT_PROOF_HEADER,\n MCP_SESSION_ID_HEADER,\n MCP_SESSION_PROOF_HEADER,\n} from \"./auth-context.js\";\nimport { reportError, isServerFault, isAuthFault } from \"./telemetry.js\";\nimport { ERROR_KIND_META_KEY } from \"./error-kind.js\";\n\nfunction getApiBaseUrl(): string {\n const url = process.env.API_URL;\n if (!url) {\n const message =\n \"API_URL must be set (e.g. http://localhost:3003 or https://api.clipform.io)\";\n // Reachable in production only through the in-process reporter\n // (apps/api/src/lib/mcp-telemetry-bridge.ts) - the default HTTP reporter\n // needs this same API_URL to know where to POST, so it can never fire\n // here on its own (telemetry.ts's reportError, #2599 blocker 5).\n reportError({\n error_type: \"config_error\",\n error_message: message,\n tool_name: getMcpAuth()?.tool_name,\n });\n throw new Error(message);\n }\n return url;\n}\n\n\nfunction getAuthHeaders(): Record<string, string> {\n const authCtx = getMcpAuth();\n // #4657: the no-workspace anon lane has no credential by design. Fail\n // closed: never fall back to the process's CLIPFORM_API_KEY either.\n if (authCtx?.loadInternalContent && !authCtx.api_key) {\n throw new Error(\"The anonymous no-workspace lane cannot call the API.\");\n }\n const apiKey = authCtx?.api_key || process.env.CLIPFORM_API_KEY;\n if (!apiKey) {\n const message = \"CLIPFORM_API_KEY must be set.\";\n reportError({\n error_type: \"config_error\",\n error_message: message,\n tool_name: authCtx?.tool_name,\n });\n throw new Error(message);\n }\n\n const headers: Record<string, string> = { \"Authorization\": `Bearer ${apiKey}` };\n // Propagate anonymity into the bot-key lane (#2983): the app-chat persona\n // for an anonymous Supabase session runs as an API-key caller under the\n // hood (ensureBotApiKey), so without this marker the API can't tell that\n // request apart from a real integration's key and would let it publish /\n // mint credentials that a direct anonymous-JWT call is denied. See\n // MCP_ANONYMOUS_HEADER's own doc comment for why trusting it is safe.\n if (authCtx?.is_anonymous) {\n headers[MCP_ANONYMOUS_HEADER] = \"1\";\n }\n // #3716: propagate the OAuth-connected label onto the bot-key lane's\n // request so /v1/me reports auth_mode \"oauth\" instead of \"api_key\" - see\n // MCP_AUTH_VIA_HEADER's own doc comment for why trusting it is safe.\n if (authCtx?.auth_via === \"oauth\") {\n headers[MCP_AUTH_VIA_HEADER] = \"oauth\";\n }\n // #3330 review fix: propagate the mint proof (if this request's anon lane\n // freshly minted an identity) so create-form.ts can safely offer a\n // same-UID claim link - see MCP_MINT_PROOF_HEADER's doc comment.\n if (authCtx?.mcp_mint_proof) {\n headers[MCP_MINT_PROOF_HEADER] = authCtx.mcp_mint_proof;\n }\n // #4090: session-reuse sibling of the mint proof.\n if (authCtx?.mcp_session_proof) {\n headers[MCP_SESSION_PROOF_HEADER] = authCtx.mcp_session_proof;\n }\n if (authCtx?.mcp_session_id) {\n headers[MCP_SESSION_ID_HEADER] = authCtx.mcp_session_id;\n }\n return headers;\n}\n\ninterface ApiOptions {\n method?: string;\n body?: Record<string, unknown>;\n params?: Record<string, string>;\n timeoutMs?: number;\n}\n\ntype ApiResult =\n | { ok: true; data: Record<string, unknown> }\n // code/reason are the API's own `{ code, error }` body fields (errorCode\n // below) and `details.reason` - optional because not every failure path\n // (network error, a 204/timeout) has a parsed error body to read them\n // from. Pure addition: every existing consumer reads status/error only.\n // apiMessage is the API's own message WITHOUT the recoveryHint `error`\n // appends - for surfaces (the OAuth challenge's error_description) that\n // must carry only the API text (#4649).\n | { ok: false; status: number; error: string; apiMessage?: string; code?: string; reason?: string };\n\nexport async function callApi(\n path: string,\n options: ApiOptions = {}\n): Promise<ApiResult> {\n const { body, params, timeoutMs = 30_000 } = options;\n const method = options.method || (body ? \"POST\" : \"GET\");\n\n const base = getApiBaseUrl();\n const prefix = path.startsWith(\"/internal/\") ? \"\" : \"/v1\";\n let url = `${base}${prefix}${path}`;\n if (params) {\n const searchParams = new URLSearchParams(params);\n url += `?${searchParams.toString()}`;\n }\n\n // Creative endpoints (/internal/*) authenticate with the same Bearer API\n // key as everything else. The X-Service-Secret header the MCP used to send\n // is webhook-trigger auth only and was dropped here (#412 F7).\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n ...getAuthHeaders(),\n };\n\n const fetchOptions: RequestInit = {\n method,\n headers,\n signal: AbortSignal.timeout(timeoutMs),\n };\n\n if (body && method !== \"GET\") {\n fetchOptions.body = JSON.stringify(body);\n }\n\n let response: Response;\n try {\n response = await fetch(url, fetchOptions);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n // A client-side AbortSignal.timeout() abort is a genuine post-ceiling\n // timeout, not a network drop - classify it separately so it doesn't get\n // misfiled as connection_error (#4070). Node 18+/undici names this\n // DOMException \"TimeoutError\"; also match \"AbortError\" / the message\n // substring as a fallback in case the runtime differs. Still reported\n // either way (#2976), just bucketed distinctly.\n const isTimeout =\n err instanceof Error &&\n (err.name === \"TimeoutError\" ||\n err.name === \"AbortError\" ||\n /aborted due to timeout/i.test(message));\n // Full error stays in our own telemetry (internal, never returned to the\n // model) - the tool response gets a stable, friendly message with no\n // internal URL or raw fetch error text (response hygiene, #2976).\n reportError({\n error_type: isTimeout ? \"timeout\" : \"connection_error\",\n error_message: message,\n tool_name: getMcpAuth()?.tool_name,\n api_path: `${prefix}${path}`,\n });\n return {\n ok: false,\n status: 0,\n error: \"Unable to reach the Clipform API right now. Please try again in a moment.\",\n };\n }\n\n if (response.status === 204) {\n return { ok: true, data: {} };\n }\n\n const data = (await response.json()) as Record<string, unknown>;\n\n if (!response.ok) {\n const apiMsg = (data.error as string) || `API error (${response.status})`;\n const details = data.details as Record<string, unknown> | undefined;\n const reason = details && typeof details.reason === \"string\" ? details.reason : undefined;\n const hint = recoveryHint(response.status, path, reason);\n const errorMsg = hint ? `${apiMsg} - ${hint}` : apiMsg;\n // The API's own error `code` (index.ts's onError: `{ code, error }`) is\n // what tells a genuine auth 403 (FORBIDDEN) apart from an ordinary\n // business-logic 403 (e.g. PLAN_LIMIT) - see isAuthFault (#2599).\n const errorCode = typeof data.code === \"string\" ? data.code : undefined;\n if (isServerFault(response.status) || isAuthFault(response.status, errorCode)) {\n reportError({\n error_type: `http_${response.status}`,\n error_message: errorMsg,\n tool_name: getMcpAuth()?.tool_name,\n status_code: response.status,\n api_path: `${prefix}${path}`,\n });\n }\n return {\n ok: false,\n status: response.status,\n error: errorMsg,\n apiMessage: apiMsg,\n code: errorCode,\n reason,\n };\n }\n\n return { ok: true, data };\n}\n\n/** Next-step hint by status + path so an agent can recover instead of\n * retrying blind (#651). The raw API message stays first, hint second. */\nexport function recoveryHint(status: number, path: string, reason?: string): string | undefined {\n if (status === 401 || status === 403) {\n // An anonymous caller has no key to check (#4653): point at the claim URL\n // from clipform_create_form / sign-up instead.\n if (reason === \"anonymous_not_allowed\" || getMcpAuth()?.is_anonymous) {\n return \"This session is anonymous - open the claim URL from clipform_create_form (or sign up) to claim your workspace, then retry.\";\n }\n return \"Check credentials: the key comes from CLIPFORM_API_KEY or the OAuth session - read clipform://context/session for the active workspace and auth mode.\";\n }\n if (status === 404) {\n if (/^\\/forms\\/[^/]+\\/nodes\\//.test(path)) {\n return \"Call clipform_get_form to list this form's nodes and their IDs.\";\n }\n if (/^\\/forms\\/[^/]+/.test(path)) {\n return \"Call clipform_list_forms to find valid form IDs (UUIDs, not the share_id from a form URL).\";\n }\n }\n return undefined;\n}\n\nexport function errorResult(message: string, meta?: Record<string, unknown>) {\n return {\n content: [{ type: \"text\" as const, text: message }],\n isError: true,\n ...(meta ? { _meta: meta } : {}),\n };\n}\n\n/**\n * An error the caller can fix (missing/conflicting args, a broken rule),\n * labelled for telemetry (#5917, see error-kind.ts). It stays `isError: true`:\n * the MCP spec makes input-validation and business-logic errors tool execution\n * errors so the model can see the call failed and self-correct.\n */\nexport function refusedResult(message: string, meta?: Record<string, unknown>) {\n return errorResult(message, { ...meta, [ERROR_KIND_META_KEY]: \"refused\" });\n}\n\n/**\n * True when an API failure refused the caller's request rather than broke:\n * any 4xx except auth faults (401, a FORBIDDEN 403), a timeout (408) or rate\n * limiting (429). A PLAN_LIMIT 403, 404, 409 or 422 is a refusal.\n */\nexport function isRefusedStatus(status: number, code?: string): boolean {\n if (status < 400 || status >= 500) return false;\n if (status === 408 || status === 429) return false;\n return !isAuthFault(status, code);\n}\n\n/** Error result for a callApi failure, labelled refused when the API refused the request. */\nexport function apiErrorResult(\n failure: { status: number; code?: string; error: string },\n message: string = failure.error,\n meta?: Record<string, unknown>\n) {\n return isRefusedStatus(failure.status, failure.code) ? refusedResult(message, meta) : errorResult(message, meta);\n}\n\n// The bare-endpoint Protected Resource Metadata document (RFC 9728) - same\n// URL apps/api/src/mcp/handler.ts derives for its own HTTP-level\n// WWW-Authenticate challenge on the non-forms-surface lane. Derived from\n// config, never hardcoded, so a domain change can't drift the two apart.\nconst PROTECTED_RESOURCE_METADATA_URL = `${BUSINESS.urls.mcp}/.well-known/oauth-protected-resource`;\n\n/**\n * Escapes a value destined for an RFC 6750 quoted-string auth-param\n * (`error=\"...\"`, `error_description=\"...\"`). Strips `\\r`/`\\n` (RFC 6750\n * quoted-string forbids CTLs, and this value is API error text that could\n * contain one) and escapes embedded backslashes/double quotes - without the\n * latter, a value containing a double quote could break out of its quoted\n * segment and inject extra auth-params into the challenge. Mirrors the\n * OpenAI Apps SDK reference implementation, which escapes the same way for\n * the same reason.\n */\nfunction escapeChallengeValue(value: string): string {\n return value.replace(/[\\r\\n]/g, \"\").replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"');\n}\n\n/**\n * True exactly when a callApi failure is the `assertNotAnonymous` account\n * gate (apps/api/src/lib/anonymous-guard.ts) - triple-keyed on status + code\n * + reason so an ordinary 403 (PLAN_LIMIT, a genuine authorization denial, a\n * 500) never escalates an already-logged-in caller into a pointless OAuth\n * re-auth (#4088 over-escalation guard). The only MCP-reachable trigger\n * today is `clipform_update_form`'s `is_live: true` (publish) - see that\n * tool's own comment for why `clipform_create_form`'s use of this same\n * predicate is currently dead code.\n */\nexport function isAnonymousAccountRequired(result: {\n status: number;\n code?: string;\n reason?: string;\n}): boolean {\n return result.status === 403 && result.code === \"FORBIDDEN\" && result.reason === \"anonymous_not_allowed\";\n}\n\n/**\n * Builds the `_meta[\"mcp/www_authenticate\"]` array a tool result carries to\n * trigger the Apps SDK's tool-level OAuth escalation (#4088): an array of\n * RFC 6750 Bearer challenge strings, the runtime half of the two-part\n * contract (the other half is the static MCP_TOOL_SECURITY declaration) -\n * per the Apps SDK auth docs, metadata alone never triggers the flow,\n * only a runtime error carrying this `_meta` key does. Same challenge shape\n * `apps/api/src/mcp/handler.ts` already emits as a real `WWW-Authenticate`\n * HTTP header for a bad/missing Bearer - this is the tool-result equivalent\n * for a caller that reached a tool (anonymously) but hit a feature that\n * requires an account.\n *\n * Callers pass \"insufficient_scope\" (#4844): OpenAI's Apps SDK auth doc\n * (developers.openai.com/plugins/build/auth) shows exactly that code, with a\n * scope, for the no-token tool-result case; \"invalid_token\" reads to the host\n * as a token that went bad and shows a \"connection expired\" card to a user who\n * never connected. This is the tool-RESULT path only - the real HTTP 401\n * headers in apps/api/src/mcp/handler.ts stay \"invalid_token\" (Claude's doc).\n */\n/** OAuth scope named in the tool-result challenge - matches handler.ts REQUIRED_SCOPE. */\nconst CHALLENGE_SCOPE = \"mcp\";\n\nexport function authChallengeMeta(\n errorCode: string,\n description: string,\n resourceMetadata: string = PROTECTED_RESOURCE_METADATA_URL\n): Record<string, unknown> {\n const challenge = [\n `Bearer error=\"${escapeChallengeValue(errorCode)}\"`,\n `error_description=\"${escapeChallengeValue(description)}\"`,\n `resource_metadata=\"${escapeChallengeValue(resourceMetadata)}\"`,\n `scope=\"${CHALLENGE_SCOPE}\"`,\n ].join(\", \");\n return { \"mcp/www_authenticate\": [challenge] };\n}\n\nexport function textResult(text: string) {\n return {\n content: [{ type: \"text\" as const, text }],\n };\n}\n\n/** Like textResult, but also carries a machine-readable `structuredContent`.\n * A tool that declares an `outputSchema` MUST return `structuredContent` on\n * every non-error result (the MCP SDK validates it and throws otherwise) - use\n * this for every success/empty path, and `errorResult` (exempt) for failures.\n * Project to the schema's explicit field set here - never pass raw API rows\n * (response-hygiene invariant, #797). */\nexport function structuredResult(\n text: string,\n structuredContent: Record<string, unknown>\n) {\n return {\n content: [{ type: \"text\" as const, text }],\n structuredContent,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA8BO,IAAM,WAAW;AAAA;AAAA,EAEtB,qBAAqB;AAAA,IACnB,MAAM;AAAA,IACN,aAAa;AAAA,IACb,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,UAAU;AAAA,EACZ;AAAA,EACA,aAAa;AAAA,IACX,MAAM;AAAA,IACN,aAAa;AAAA,IACb,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,UAAU;AAAA,EACZ;AAAA,EACA,eAAe;AAAA,IACb,MAAM;AAAA,IACN,aAAa;AAAA,IACb,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,UAAU;AAAA,EACZ;AAAA,EACA,mBAAmB;AAAA,IACjB,MAAM;AAAA,IACN,aAAa;AAAA,IACb,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,UAAU;AAAA,IACV,YAAY;AAAA,IACZ,UAAU;AAAA,MACR,UAAU;AAAA,MACV,SAAS;AAAA,IACX;AAAA,EACF;AAAA,EACA,YAAY;AAAA,IACV,MAAM;AAAA,IACN,aAAa;AAAA,IACb,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,UAAU;AAAA,EACZ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,w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