@adminide-stack/yantra-mobile 12.0.173 → 12.0.174-alpha.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.
Files changed (130) hide show
  1. package/lib/compute.js +54 -1
  2. package/lib/compute.js.map +1 -1
  3. package/lib/features/apps/AppsCatalog.js +10 -0
  4. package/lib/features/apps/AppsCatalog.js.map +1 -1
  5. package/lib/features/apps/mobileAppCatalog.js +6 -1
  6. package/lib/features/apps/mobileAppCatalog.js.map +1 -1
  7. package/lib/features/apps/nativeAppHandoff.js +4 -1
  8. package/lib/features/apps/nativeAppHandoff.js.map +1 -1
  9. package/lib/features/apps/nativeSurfaceTwin.js +2 -1
  10. package/lib/features/apps/nativeSurfaceTwin.js.map +1 -1
  11. package/lib/features/channels/ChannelIcon.js +13 -3
  12. package/lib/features/channels/ChannelIcon.js.map +1 -1
  13. package/lib/features/channels/ConnectAppsSheet.js +5 -5
  14. package/lib/features/channels/ConnectAppsSheet.js.map +1 -1
  15. package/lib/features/channels/HomeImessage.js +5 -3
  16. package/lib/features/channels/HomeImessage.js.map +1 -1
  17. package/lib/features/channels/channelLinks.js +13 -1
  18. package/lib/features/channels/channelLinks.js.map +1 -1
  19. package/lib/features/computer/ComputerAgentChatPane.js +45 -0
  20. package/lib/features/computer/ComputerAgentChatPane.js.map +1 -0
  21. package/lib/features/computer/ComputerDesktop.js +164 -0
  22. package/lib/features/computer/ComputerDesktop.js.map +1 -0
  23. package/lib/features/computer/ComputerExperience.js +79 -0
  24. package/lib/features/computer/ComputerExperience.js.map +1 -0
  25. package/lib/features/computer/ComputerHandoff.js +142 -0
  26. package/lib/features/computer/ComputerHandoff.js.map +1 -0
  27. package/lib/features/computer/FilesPane.js +179 -0
  28. package/lib/features/computer/FilesPane.js.map +1 -0
  29. package/lib/features/computer/LivePage.js +1093 -0
  30. package/lib/features/computer/LivePage.js.map +1 -0
  31. package/lib/features/computer/TerminalPane.js +139 -0
  32. package/lib/features/computer/TerminalPane.js.map +1 -0
  33. package/lib/features/computer/computerApi.js +819 -0
  34. package/lib/features/computer/computerApi.js.map +1 -0
  35. package/lib/features/computer/computerChat.js +42 -0
  36. package/lib/features/computer/computerChat.js.map +1 -0
  37. package/lib/features/computer/computerControls.js +227 -0
  38. package/lib/features/computer/computerControls.js.map +1 -0
  39. package/lib/features/computer/computerStyles.js +384 -0
  40. package/lib/features/computer/computerStyles.js.map +1 -0
  41. package/lib/features/computer/computerTheme.js +133 -0
  42. package/lib/features/computer/computerTheme.js.map +1 -0
  43. package/lib/features/computer/handoff.js +73 -0
  44. package/lib/features/computer/handoff.js.map +1 -0
  45. package/lib/features/computer/inputLane.js +171 -0
  46. package/lib/features/computer/inputLane.js.map +1 -0
  47. package/lib/features/computer/inputPump.js +77 -0
  48. package/lib/features/computer/inputPump.js.map +1 -0
  49. package/lib/features/computer/inputSocket.js +148 -0
  50. package/lib/features/computer/inputSocket.js.map +1 -0
  51. package/lib/features/computer/keyboardBridge.js +176 -0
  52. package/lib/features/computer/keyboardBridge.js.map +1 -0
  53. package/lib/features/computer/pageCoordinates.js +19 -0
  54. package/lib/features/computer/pageCoordinates.js.map +1 -0
  55. package/lib/features/computer/pageZoom.js +12 -0
  56. package/lib/features/computer/pageZoom.js.map +1 -0
  57. package/lib/features/computer/pictureGeometry.js +68 -0
  58. package/lib/features/computer/pictureGeometry.js.map +1 -0
  59. package/lib/features/computer/tabsState.js +7 -0
  60. package/lib/features/computer/tabsState.js.map +1 -0
  61. package/lib/features/computer/useComputerHooks.js +146 -0
  62. package/lib/features/computer/useComputerHooks.js.map +1 -0
  63. package/lib/features/links/openInApp.js +10 -1
  64. package/lib/features/links/openInApp.js.map +1 -1
  65. package/lib/features/webbuilder/WebBuilderExperience.js +180 -44
  66. package/lib/features/webbuilder/WebBuilderExperience.js.map +1 -1
  67. package/lib/features/webbuilder/buildFragments.js +16 -3
  68. package/lib/features/webbuilder/buildFragments.js.map +1 -1
  69. package/lib/features/webbuilder/codezenHandoff.js +29 -1
  70. package/lib/features/webbuilder/codezenHandoff.js.map +1 -1
  71. package/lib/features/webbuilder/components/CodeView.js +69 -23
  72. package/lib/features/webbuilder/components/CodeView.js.map +1 -1
  73. package/lib/features/webbuilder/components/PreviewFrame.js +62 -2
  74. package/lib/features/webbuilder/components/PreviewFrame.js.map +1 -1
  75. package/lib/features/webbuilder/components/PreviewScreen.js +37 -2
  76. package/lib/features/webbuilder/components/PreviewScreen.js.map +1 -1
  77. package/lib/features/webbuilder/components/ProjectChat.js +2 -1
  78. package/lib/features/webbuilder/components/ProjectChat.js.map +1 -1
  79. package/lib/features/webbuilder/components/ProjectSheets.js +147 -57
  80. package/lib/features/webbuilder/components/ProjectSheets.js.map +1 -1
  81. package/lib/features/webbuilder/components/PublishSheet.js +106 -2
  82. package/lib/features/webbuilder/components/PublishSheet.js.map +1 -1
  83. package/lib/features/webbuilder/components/ReferenceModeChoice.js +105 -0
  84. package/lib/features/webbuilder/components/ReferenceModeChoice.js.map +1 -0
  85. package/lib/features/webbuilder/components/RetentionBanner.js +17 -6
  86. package/lib/features/webbuilder/components/RetentionBanner.js.map +1 -1
  87. package/lib/features/webbuilder/components/SiteUploadSheet.js +327 -0
  88. package/lib/features/webbuilder/components/SiteUploadSheet.js.map +1 -0
  89. package/lib/features/webbuilder/components/StreamStallNote.js +38 -0
  90. package/lib/features/webbuilder/components/StreamStallNote.js.map +1 -0
  91. package/lib/features/webbuilder/components/StudioHome.js +18 -8
  92. package/lib/features/webbuilder/components/StudioHome.js.map +1 -1
  93. package/lib/features/webbuilder/previewRoutes.js +30 -1
  94. package/lib/features/webbuilder/previewRoutes.js.map +1 -1
  95. package/lib/features/webbuilder/studioCatalog.js +9 -2
  96. package/lib/features/webbuilder/studioCatalog.js.map +1 -1
  97. package/lib/features/webbuilder/web/chat/referenceMode.js +11 -0
  98. package/lib/features/webbuilder/web/chat/referenceMode.js.map +1 -0
  99. package/lib/features/webbuilder/web/chat/siteCopy.js +5 -2
  100. package/lib/features/webbuilder/web/chat/siteCopy.js.map +1 -1
  101. package/lib/features/webbuilder/web/chat/streamStall.js +6 -0
  102. package/lib/features/webbuilder/web/chat/streamStall.js.map +1 -0
  103. package/lib/features/webbuilder/web/code/savedCode.js +7 -0
  104. package/lib/features/webbuilder/web/code/savedCode.js.map +1 -0
  105. package/lib/features/webbuilder/web/design/directions.js.map +1 -1
  106. package/lib/features/webbuilder/web/history/versions.js.map +1 -1
  107. package/lib/features/webbuilder/web/import/websiteImport.js +27 -0
  108. package/lib/features/webbuilder/web/import/websiteImport.js.map +1 -0
  109. package/lib/features/webbuilder/web/preview/setupPhase.js +31 -0
  110. package/lib/features/webbuilder/web/preview/setupPhase.js.map +1 -0
  111. package/lib/features/webbuilder/web/publish/siteInsights.js +23 -1
  112. package/lib/features/webbuilder/web/publish/siteInsights.js.map +1 -1
  113. package/lib/features/webbuilder/web/upload/sitePhotos.js +102 -0
  114. package/lib/features/webbuilder/web/upload/sitePhotos.js.map +1 -0
  115. package/lib/routes.json +54 -0
  116. package/lib/screens/ComputerNative/index.js +124 -0
  117. package/lib/screens/ComputerNative/index.js.map +1 -0
  118. package/lib/screens/ComputerNative/useComputerHostChat.js +83 -0
  119. package/lib/screens/ComputerNative/useComputerHostChat.js.map +1 -0
  120. package/lib/screens/Home/components/homeCatalog.js +2 -1
  121. package/lib/screens/Home/components/homeCatalog.js.map +1 -1
  122. package/lib/screens/WebBuilder/nativeWebBuilderRedirect.js +6 -2
  123. package/lib/screens/WebBuilder/nativeWebBuilderRedirect.js.map +1 -1
  124. package/lib/screens/WebBuilderNative/index.js +15 -3
  125. package/lib/screens/WebBuilderNative/index.js.map +1 -1
  126. package/lib/screens/WebBuilderNative/useWebBuilderHost.js +18 -3
  127. package/lib/screens/WebBuilderNative/useWebBuilderHost.js.map +1 -1
  128. package/lib/screens/WebBuilderNative/webbuilderTransport.js +16 -7
  129. package/lib/screens/WebBuilderNative/webbuilderTransport.js.map +1 -1
  130. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"siteCopy.js","sources":["../../../../../src/features/webbuilder/web/chat/siteCopy.ts"],"sourcesContent":["/**\n * A website copy seen from the build view. Pure.\n *\n * \"Make resortifi.com here\": the agent copies a live site into the sandbox with yantra-webbuilder's\n * WEBBUILDER_CLONE_WEBSITE (1.1.0+), and one call waits minutes. The build view polls\n * WEBBUILDER_CLONE_WEBSITE_STATUS and shows the page being copied (a small picture of it), the counts\n * and the newest pages, so the person sees it working instead of a spinner.\n *\n * The page cannot see the agent's tool params (in project mode every step reads\n * WEBBUILDER_PROJECT_ACTION), so it learns about a copy from the agent's own line, which design-pro\n * makes exact: \"Copying resortifi.com into the live preview (preview `https://3000-<sandbox>…`)\".\n */\n/** The sandbox id of a live preview address in a line (web `agentBuild.previewFrom`). */\nfunction previewFrom(text: string): { sandboxId: string } | null {\n const m = /https?:\\/\\/\\d{2,5}-([a-z0-9]{4,128})\\.[a-z0-9.-]+/i.exec(text);\n return m ? { sandboxId: m[1].toLowerCase() } : null;\n}\n\nexport const COPY_STATUS_ACTION = 'WEBBUILDER_CLONE_WEBSITE_STATUS' as const;\n\nexport type SiteCopyStatus = 'none' | 'running' | 'done' | 'failed';\n\nexport interface SiteCopyPage {\n url: string;\n /** \"Rooms & Suites\", else the path (\"/rooms\"). */\n label: string;\n}\n\nexport interface SiteCopyView {\n status: SiteCopyStatus;\n jobId: string | null;\n /** \"resortifi.com\" */\n site: string;\n /** \"Visiting pages\", \"Downloading images, fonts and files\"... */\n phase: string;\n summary: string;\n elapsedSec: number;\n pagesDone: number;\n pagesQueued: number;\n files: number;\n /** Pages being copied right now. */\n current: SiteCopyPage[];\n /** Newest first. */\n recent: SiteCopyPage[];\n /** Id of the newest picture the connector has (sent back as sinceThumb). */\n thumbId: number | null;\n /** The newest picture received so far (kept between polls that leave it out). */\n thumb: (SiteCopyPage & { id: number; src: string }) | null;\n matchPercent: number | null;\n error: string | null;\n}\n\nconst PHASES: Record<string, string> = {\n starting: 'Starting',\n setup: 'Preparing the browser',\n discover: 'Reading the sitemap',\n capture: 'Visiting pages',\n assets: 'Downloading images, fonts and files',\n write: 'Writing the copy',\n verify: 'Comparing the copy with the original',\n install: 'Putting the copy in your project',\n done: 'Done',\n failed: 'Stopped',\n};\n\nconst isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);\nconst num = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) ? v : 0);\nconst str = (v: unknown): string => (typeof v === 'string' ? v : '');\n\nfunction hostOf(url: string): string {\n try {\n return new URL(url).host.replace(/^www\\./, '');\n } catch {\n return url;\n }\n}\n\n/** A page as people name it: its title before \" | Brand\", else its path. */\nexport function pageLabel(url: string, title?: string | null): string {\n const t = (title ?? '').replace(/\\s+/g, ' ').trim();\n if (t) {\n const head = t.split(/\\s+[|\\u00b7\\u2022\\u2013\\u2014-]\\s+/)[0].trim();\n return (head || t).slice(0, 80);\n }\n try {\n const u = new URL(url);\n const path = decodeURI(u.pathname).replace(/\\/+$/, '');\n return path || '/';\n } catch {\n return url.slice(0, 80);\n }\n}\n\nfunction page(v: unknown): SiteCopyPage | null {\n if (typeof v === 'string') return v ? { url: v, label: pageLabel(v) } : null;\n if (!isObj(v)) return null;\n const url = str(v.url);\n return url ? { url, label: pageLabel(url, str(v.title)) } : null;\n}\n\nconst JPEG_DATA_URL = /^data:image\\/jpeg;base64,[A-Za-z0-9+/]+=*$/;\n\n/** The status answer as the build view's model; `prev` keeps the picture the answer leaves out. */\nexport function siteCopyView(data: unknown, prev: SiteCopyView | null): SiteCopyView {\n const d = isObj(data) ? data : {};\n const statusRaw = str(d.status);\n const status: SiteCopyStatus =\n statusRaw === 'running' || statusRaw === 'done' || statusRaw === 'failed' ? statusRaw : 'none';\n const p = isObj(d.progress) ? d.progress : {};\n const thumbId = Number.isInteger(d.thumbId) ? (d.thumbId as number) : null;\n let thumb = prev && prev.jobId === (str(d.jobId) || null) ? prev.thumb : null;\n if (isObj(d.thumb) && Number.isInteger(d.thumb.id) && JPEG_DATA_URL.test(str(d.thumb.dataUrl))) {\n const url = str(d.thumb.url);\n thumb = { id: d.thumb.id as number, url, label: pageLabel(url, str(d.thumb.title)), src: str(d.thumb.dataUrl) };\n }\n const result = isObj(d.result) ? d.result : {};\n const error = isObj(d.error) ? str(d.error.message) || null : null;\n const pages = (v: unknown, max: number) =>\n (Array.isArray(v) ? v : [])\n .map(page)\n .filter((x): x is SiteCopyPage => !!x)\n .slice(0, max);\n return {\n status,\n jobId: str(d.jobId) || null,\n site: str(d.site) || hostOf(str(d.url)),\n phase:\n status === 'done'\n ? PHASES.done\n : status === 'failed'\n ? PHASES.failed\n : PHASES[str(d.phase)] || PHASES.starting,\n summary: str(d.summary),\n elapsedSec: num(d.elapsedSec),\n pagesDone: num(p.pagesDone),\n pagesQueued: num(p.pagesQueued),\n files: num(p.assets),\n current: pages(d.current, 3),\n recent: pages(d.recent, 6),\n thumbId,\n thumb,\n matchPercent: typeof result.matchPercent === 'number' ? result.matchPercent : null,\n error,\n };\n}\n\n/** \"6 pages copied\", \"9 to go\", \"160 files\": the counts worth showing. */\nexport function copyCounts(v: Pick<SiteCopyView, 'pagesDone' | 'pagesQueued' | 'files'>): string[] {\n const out = [`${v.pagesDone} page${v.pagesDone === 1 ? '' : 's'} copied`];\n if (v.pagesQueued) out.push(`${v.pagesQueued} to go`);\n if (v.files) out.push(`${v.files} file${v.files === 1 ? '' : 's'}`);\n return out;\n}\n\nconst COPY_LINE = /\\bCopying\\s+(\\S+)[^\\n]{0,160}?\\blive preview\\b[^\\n]*/gi;\n\n/**\n * The site and sandbox of the agent's latest copy line (\"Copying resortifi.com into the live preview\n * (preview `https://3000-<sandbox>…`)\"); null when it said none.\n */\nexport function copyLine(text: string | null | undefined): { sandboxId: string; site: string } | null {\n let found: { sandboxId: string; site: string } | null = null;\n for (const m of String(text || '').matchAll(COPY_LINE)) {\n const sandboxId = previewFrom(m[0])?.sandboxId;\n if (!sandboxId) continue;\n const site = m[1]\n .replace(/^[`*_\"'(]+|[`*_\"'),.:;!?]+$/g, '')\n .replace(/^https?:\\/\\//i, '')\n .replace(/\\/+$/, '');\n found = { sandboxId, site };\n }\n return found;\n}\n\n/** The turn ran (or runs) a website copy directly (not through the project proxy): its step's label names the action. */\nexport function copyStepSeen(steps: ReadonlyArray<{ label?: string; detail?: string }>): boolean {\n return steps.some((st) => /(?:^|_)CLONE_WEBSITE\\b/.test(`${st.label ?? ''} ${st.detail ?? ''}`));\n}\n\n/** Poll fast while pages are being copied, slower while waiting for the copy to start or after 3 minutes. */\nexport function copyPollIntervalMs(elapsedMs: number, status: SiteCopyStatus | undefined): number {\n if (status !== 'running') return 5_000;\n return elapsedMs < 3 * 60_000 ? 3_000 : 5_000;\n}\n\n/** A status answer that says the action is not there (older connector or server): stop asking. */\nexport function copyStatusUnavailable(error: string | null | undefined): boolean {\n return /unknown webbuilder action|not on its allow-list|unknown sandbox action|view access/i.test(error ?? '');\n}\n"],"names":[],"mappings":"AAaA,SAAS,YAAY,IAEZ,EAAA;AACP,EAAM,MAAA,CAAA,GAAI,oDAAqD,CAAA,IAAA,CAAK,IAAI,CAAA;AACxE,EAAA,OAAO,CAAI,GAAA;AAAA,IACT,SAAW,EAAA,CAAA,CAAE,CAAC,CAAA,CAAE,WAAY;AAAA,GAC1B,GAAA,IAAA;AACN;AACO,MAAM,kBAAqB,GAAA;AAiClC,MAAM,MAAiC,GAAA;AAAA,EACrC,QAAU,EAAA,UAAA;AAAA,EACV,KAAO,EAAA,uBAAA;AAAA,EACP,QAAU,EAAA,qBAAA;AAAA,EACV,OAAS,EAAA,gBAAA;AAAA,EACT,MAAQ,EAAA,qCAAA;AAAA,EACR,KAAO,EAAA,kBAAA;AAAA,EACP,MAAQ,EAAA,sCAAA;AAAA,EACR,OAAS,EAAA,kCAAA;AAAA,EACT,IAAM,EAAA,MAAA;AAAA,EACN,MAAQ,EAAA;AACV,CAAA;AACA,MAAM,KAAQ,GAAA,CAAC,CAA6C,KAAA,CAAC,CAA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GhB,EAAA;AAjKT,EAAA,IAAA,EAAA;AAkKE,EAAA,IAAI,KAGO,GAAA,IAAA;AACX,EAAA,KAAA,MAAW,KAAK,MAAO,CAAA,IAAA,IAAQ,EAAE,CAAE,CAAA,QAAA,CAAS,SAAS,CAAG,EAAA;AACtD,IAAA,MAAM,aAAY,EAAY,GAAA,WAAA,CAAA,CAAA,CAAE,CAAC,CAAC,MAAhB,IAAmB,GAAA,MAAA,GAAA,EAAA,CAAA,SAAA;AACrC,IAAA,IAAI,CAAC,SAAW,EAAA;AAChB,IAAA,MAAM,IAAO,GAAA,CAAA,CAAE,CAAC,CAAA,CAAE,QAAQ,8BAAgC,EAAA,EAAE,CAAE,CAAA,OAAA,CAAQ,eAAiB,EAAA,EAAE,CAAE,CAAA,OAAA,CAAQ,QAAQ,EAAE,CAAA;AAC7G,IAAQ,KAAA,GAAA;AAAA,MACN,SAAA;AAAA,MACA;AAAA,KACF;AAAA;AAEF,EAAO,OAAA,KAAA;AACT;AAWgB,SAAA,kBAAA,CAAmB,WAAmB,MAA4C,EAAA;AAChG,EAAI,IAAA,MAAA,KAAW,WAAkB,OAAA,GAAA;AACjC,EAAO,OAAA,SAAA,GAAY,CAAI,GAAA,GAAA,GAAS,GAAQ,GAAA,GAAA;AAC1C;AAGO,SAAS,sBAAsB,KAA2C,EAAA;AAC/E,EAAO,OAAA,qFAAA,CAAsF,IAAK,CAAA,KAAA,IAAA,IAAA,GAAA,KAAA,GAAS,EAAE,CAAA;AAC/G"}
1
+ {"version":3,"file":"siteCopy.js","sources":["../../../../../src/features/webbuilder/web/chat/siteCopy.ts"],"sourcesContent":["/**\n * A website copy seen from the build view. Pure.\n *\n * \"Make resortifi.com here\": the agent copies a live site into the sandbox with yantra-webbuilder's\n * WEBBUILDER_CLONE_WEBSITE (1.1.0+), and one call waits minutes. The build view polls\n * WEBBUILDER_CLONE_WEBSITE_STATUS and shows the page being copied (a small picture of it), the counts\n * and the newest pages, so the person sees it working instead of a spinner.\n *\n * The page cannot see the agent's tool params (in project mode every step reads\n * WEBBUILDER_PROJECT_ACTION), so it learns about a copy from the agent's own line, which design-pro\n * makes exact: \"Copying resortifi.com into the live preview (preview `https://3000-<sandbox>…`)\".\n */\n/** The sandbox id of a live preview address in a line (web `agentBuild.previewFrom`). */\nfunction previewFrom(text: string): { sandboxId: string } | null {\n const m = /https?:\\/\\/\\d{2,5}-([a-z0-9]{4,128})\\.[a-z0-9.-]+/i.exec(text);\n return m ? { sandboxId: m[1].toLowerCase() } : null;\n}\n\nexport const COPY_STATUS_ACTION = 'WEBBUILDER_CLONE_WEBSITE_STATUS' as const;\n\nexport type SiteCopyStatus = 'none' | 'running' | 'done' | 'failed';\n\nexport interface SiteCopyPage {\n url: string;\n /** \"Rooms & Suites\", else the path (\"/rooms\"). */\n label: string;\n}\n\nexport interface SiteCopyView {\n status: SiteCopyStatus;\n jobId: string | null;\n /** \"resortifi.com\" */\n site: string;\n /** \"Visiting pages\", \"Downloading images, fonts and files\"... */\n phase: string;\n summary: string;\n elapsedSec: number;\n pagesDone: number;\n pagesQueued: number;\n files: number;\n /** Pages being copied right now. */\n current: SiteCopyPage[];\n /** Newest first. */\n recent: SiteCopyPage[];\n /** Id of the newest picture the connector has (sent back as sinceThumb). */\n thumbId: number | null;\n /** The newest picture received so far (kept between polls that leave it out). */\n thumb: (SiteCopyPage & { id: number; src: string }) | null;\n matchPercent: number | null;\n error: string | null;\n}\n\nconst PHASES: Record<string, string> = {\n starting: 'Starting',\n setup: 'Preparing the browser',\n discover: 'Reading the sitemap',\n capture: 'Visiting pages',\n assets: 'Downloading images, fonts and files',\n write: 'Writing the copy',\n verify: 'Comparing the copy with the original',\n install: 'Putting the copy in your project',\n done: 'Done',\n failed: 'Stopped',\n};\n\nconst isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);\nconst num = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) ? v : 0);\nconst str = (v: unknown): string => (typeof v === 'string' ? v : '');\n\nfunction hostOf(url: string): string {\n try {\n return new URL(url).host.replace(/^www\\./, '');\n } catch {\n return url;\n }\n}\n\n/** A page as people name it: its title before \" | Brand\", else its path. */\nexport function pageLabel(url: string, title?: string | null): string {\n const t = (title ?? '').replace(/\\s+/g, ' ').trim();\n if (t) {\n const head = t.split(/\\s+[|\\u00b7\\u2022\\u2013\\u2014-]\\s+/)[0].trim();\n return (head || t).slice(0, 80);\n }\n try {\n const u = new URL(url);\n const path = decodeURI(u.pathname).replace(/\\/+$/, '');\n return path || '/';\n } catch {\n return url.slice(0, 80);\n }\n}\n\nfunction page(v: unknown): SiteCopyPage | null {\n if (typeof v === 'string') return v ? { url: v, label: pageLabel(v) } : null;\n if (!isObj(v)) return null;\n const url = str(v.url);\n return url ? { url, label: pageLabel(url, str(v.title)) } : null;\n}\n\nconst JPEG_DATA_URL = /^data:image\\/jpeg;base64,[A-Za-z0-9+/]+=*$/;\n\n/** The status answer as the build view's model; `prev` keeps the picture the answer leaves out. */\nexport function siteCopyView(data: unknown, prev: SiteCopyView | null): SiteCopyView {\n const d = isObj(data) ? data : {};\n const statusRaw = str(d.status);\n const status: SiteCopyStatus =\n statusRaw === 'running' || statusRaw === 'done' || statusRaw === 'failed' ? statusRaw : 'none';\n const p = isObj(d.progress) ? d.progress : {};\n const thumbId = Number.isInteger(d.thumbId) ? (d.thumbId as number) : null;\n let thumb = prev && prev.jobId === (str(d.jobId) || null) ? prev.thumb : null;\n if (isObj(d.thumb) && Number.isInteger(d.thumb.id) && JPEG_DATA_URL.test(str(d.thumb.dataUrl))) {\n const url = str(d.thumb.url);\n thumb = { id: d.thumb.id as number, url, label: pageLabel(url, str(d.thumb.title)), src: str(d.thumb.dataUrl) };\n }\n const result = isObj(d.result) ? d.result : {};\n const error = isObj(d.error) ? str(d.error.message) || null : null;\n const pages = (v: unknown, max: number) =>\n (Array.isArray(v) ? v : [])\n .map(page)\n .filter((x): x is SiteCopyPage => !!x)\n .slice(0, max);\n return {\n status,\n jobId: str(d.jobId) || null,\n site: str(d.site) || hostOf(str(d.url)),\n phase:\n status === 'done'\n ? PHASES.done\n : status === 'failed'\n ? PHASES.failed\n : PHASES[str(d.phase)] || PHASES.starting,\n summary: str(d.summary),\n elapsedSec: num(d.elapsedSec),\n pagesDone: num(p.pagesDone),\n pagesQueued: num(p.pagesQueued),\n files: num(p.assets),\n current: pages(d.current, 3),\n recent: pages(d.recent, 6),\n thumbId,\n thumb,\n matchPercent: typeof result.matchPercent === 'number' ? result.matchPercent : null,\n error,\n };\n}\n\n/** \"6 pages copied\", \"9 to go\", \"160 files\": the counts worth showing. */\nexport function copyCounts(v: Pick<SiteCopyView, 'pagesDone' | 'pagesQueued' | 'files'>): string[] {\n const out = [`${v.pagesDone} page${v.pagesDone === 1 ? '' : 's'} copied`];\n if (v.pagesQueued) out.push(`${v.pagesQueued} to go`);\n if (v.files) out.push(`${v.files} file${v.files === 1 ? '' : 's'}`);\n return out;\n}\n\nconst COPY_LINE = /\\bCopying\\s+(\\S+)[^\\n]{0,160}?\\blive preview\\b[^\\n]*/gi;\n\n/**\n * The site and sandbox of the agent's latest copy line (\"Copying resortifi.com into the live preview\n * (preview `https://3000-<sandbox>…`)\"); null when it said none.\n */\nexport function copyLine(text: string | null | undefined): { sandboxId: string; site: string } | null {\n let found: { sandboxId: string; site: string } | null = null;\n for (const m of String(text || '').matchAll(COPY_LINE)) {\n const sandboxId = previewFrom(m[0])?.sandboxId;\n if (!sandboxId) continue;\n const site = m[1]\n .replace(/^[`*_\"'(]+|[`*_\"'),.:;!?]+$/g, '')\n .replace(/^https?:\\/\\//i, '')\n .replace(/\\/+$/, '');\n found = { sandboxId, site };\n }\n return found;\n}\n\n/** The turn ran (or runs) a website copy directly (not through the project proxy): its step's label names the action. */\nexport function copyStepSeen(steps: ReadonlyArray<{ label?: string; detail?: string }>): boolean {\n return steps.some((st) => /(?:^|_)CLONE_WEBSITE\\b/.test(`${st.label ?? ''} ${st.detail ?? ''}`));\n}\n\n/** Poll fast while pages are being copied, slower while waiting for the copy to start or after 3 minutes. */\nexport function copyPollIntervalMs(elapsedMs: number, status: SiteCopyStatus | undefined): number {\n if (status !== 'running') return 5_000;\n return elapsedMs < 3 * 60_000 ? 3_000 : 5_000;\n}\n\n/** A status answer that says the action is not there (older connector or server): stop asking. */\nexport function copyStatusUnavailable(error: string | null | undefined): boolean {\n return /unknown webbuilder action|not on its allow-list|unknown sandbox action|doesn't support|view access/i.test(\n error ?? '',\n );\n}\n\n/**\n * The running turn's copy, once its line was seen (web fa1a5d6c, 0.16.2). A dropped connection puts a status where\n * the stream text was, so the line is gone while the copy runs on: the live view must not go with it. Forgotten\n * when the turn ends.\n */\nexport function heldCopyLine<T>(held: T | null, now: T | null, turnRunning: boolean): T | null {\n return turnRunning ? (now ?? held) : null;\n}\n"],"names":[],"mappings":"AAaA,SAAS,YAAY,IAEZ,EAAA;AACP,EAAM,MAAA,CAAA,GAAI,oDAAqD,CAAA,IAAA,CAAK,IAAI,CAAA;AACxE,EAAA,OAAO,CAAI,GAAA;AAAA,IACT,SAAW,EAAA,CAAA,CAAE,CAAC,CAAA,CAAE,WAAY;AAAA,GAC1B,GAAA,IAAA;AACN;AACO,MAAM,kBAAqB,GAAA;AAiClC,MAAM,MAAiC,GAAA;AAAA,EACrC,QAAU,EAAA,UAAA;AAAA,EACV,KAAO,EAAA,uBAAA;AAAA,EACP,QAAU,EAAA,qBAAA;AAAA,EACV,OAAS,EAAA,gBAAA;AAAA,EACT,MAAQ,EAAA,qCAAA;AAAA,EACR,KAAO,EAAA,kBAAA;AAAA,EACP,MAAQ,EAAA,sCAAA;AAAA,EACR,OAAS,EAAA,kCAAA;AAAA,EACT,IAAM,EAAA,MAAA;AAAA,EACN,MAAQ,EAAA;AACV,CAAA;AACA,MAAM,KAAQ,GAAA,CAAC,CAA6C,KAAA,CAAC,CAAC,CAAA,IAAK,OAAO,CAAA,KAAM,QAAY,IAAA,CAAC,KAAM,CAAA,OAAA,CAAQ,CAAC,CAAA;AAC5G,M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KAAK,MAAO,CAAA,IAAA,IAAQ,EAAE,CAAE,CAAA,QAAA,CAAS,SAAS,CAAG,EAAA;AACtD,IAAA,MAAM,aAAY,EAAY,GAAA,WAAA,CAAA,CAAA,CAAE,CAAC,CAAC,MAAhB,IAAmB,GAAA,MAAA,GAAA,EAAA,CAAA,SAAA;AACrC,IAAA,IAAI,CAAC,SAAW,EAAA;AAChB,IAAA,MAAM,IAAO,GAAA,CAAA,CAAE,CAAC,CAAA,CAAE,QAAQ,8BAAgC,EAAA,EAAE,CAAE,CAAA,OAAA,CAAQ,eAAiB,EAAA,EAAE,CAAE,CAAA,OAAA,CAAQ,QAAQ,EAAE,CAAA;AAC7G,IAAQ,KAAA,GAAA;AAAA,MACN,SAAA;AAAA,MACA;AAAA,KACF;AAAA;AAEF,EAAO,OAAA,KAAA;AACT;AAWgB,SAAA,kBAAA,CAAmB,WAAmB,MAA4C,EAAA;AAChG,EAAI,IAAA,MAAA,KAAW,WAAkB,OAAA,GAAA;AACjC,EAAO,OAAA,SAAA,GAAY,CAAI,GAAA,GAAA,GAAS,GAAQ,GAAA,GAAA;AAC1C;AAGO,SAAS,sBAAsB,KAA2C,EAAA;AAC/E,EAAO,OAAA,qGAAA,CAAsG,IAAK,CAAA,KAAA,IAAA,IAAA,GAAA,KAAA,GAAS,EAAE,CAAA;AAC/H;AAOgB,SAAA,YAAA,CAAgB,IAAgB,EAAA,GAAA,EAAe,WAAgC,EAAA;AAC7F,EAAO,OAAA,WAAA,GAAc,oBAAO,IAAO,GAAA,IAAA;AACrC"}
@@ -0,0 +1,6 @@
1
+ const STREAM_STALL_AFTER_MS = 8e3;
2
+ function stallNote(sinceChangeMs, busy) {
3
+ if (!busy || sinceChangeMs < STREAM_STALL_AFTER_MS) return null;
4
+ const s = Math.floor(sinceChangeMs / 1e3);
5
+ return `Still working \xB7 ${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")} since the last update`;
6
+ }export{STREAM_STALL_AFTER_MS,stallNote};//# sourceMappingURL=streamStall.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"streamStall.js","sources":["../../../../../src/features/webbuilder/web/chat/streamStall.ts"],"sourcesContent":["/** How long a running reply has shown no new text, and the note for it (web 83af6246, 0.15). Pure. */\nexport const STREAM_STALL_AFTER_MS = 8_000;\n\nexport function stallNote(sinceChangeMs: number, busy: boolean): string | null {\n if (!busy || sinceChangeMs < STREAM_STALL_AFTER_MS) return null;\n const s = Math.floor(sinceChangeMs / 1000);\n return `Still working · ${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')} since the last update`;\n}\n"],"names":[],"mappings":"AACO,MAAM,qBAAwB,GAAA;AACrB,SAAA,SAAA,CAAU,eAAuB,IAA8B,EAAA;AAC7E,EAAA,IAAI,CAAC,IAAA,IAAQ,aAAgB,GAAA,qBAAA,EAA8B,OAAA,IAAA;AAC3D,EAAA,MAAM,CAAI,GAAA,IAAA,CAAK,KAAM,CAAA,aAAA,GAAgB,GAAI,CAAA;AACzC,EAAA,OAAO,CAAmB,mBAAA,EAAA,IAAA,CAAK,KAAM,CAAA,CAAA,GAAI,EAAE,CAAC,CAAA,CAAA,EAAI,MAAO,CAAA,CAAA,GAAI,EAAE,CAAA,CAAE,QAAS,CAAA,CAAA,EAAG,GAAG,CAAC,CAAA,sBAAA,CAAA;AACjF"}
@@ -0,0 +1,7 @@
1
+ import {projectNameOfLiveUrl}from'../../publishTools.js';function handEditBackupRepo(c) {
2
+ if (!c) return null;
3
+ const published = projectNameOfLiveUrl(c.liveUrl);
4
+ if (published) return published;
5
+ const m = /(?:^|github\.com\/)yantra-userbase\/[0-9a-f]{24}-([A-Za-z0-9._-]+?)(?:\.git)?\/?$/i.exec(String(c.backupRepo || "").trim());
6
+ return m ? m[1] : null;
7
+ }export{handEditBackupRepo};//# sourceMappingURL=savedCode.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"savedCode.js","sources":["../../../../../src/features/webbuilder/web/code/savedCode.ts"],"sourcesContent":["/**\n * Hand edits and the project's private backup (web 88f4ced3, 0.18). Pure.\n */\nimport { projectNameOfLiveUrl } from '../../publishTools';\n\n/**\n * The backup repo name a project's hand edits are pushed to (WEBBUILDER_BACKUP_GITHUB `repo`): its publish name,\n * else the `<repo>` part of its `yantra-userbase/<account id>-<repo>` backup. Null when neither is known.\n */\nexport function handEditBackupRepo(\n c: { liveUrl?: string | null; backupRepo?: string | null } | null | undefined,\n): string | null {\n if (!c) return null;\n const published = projectNameOfLiveUrl(c.liveUrl);\n if (published) return published;\n const m = /(?:^|github\\.com\\/)yantra-userbase\\/[0-9a-f]{24}-([A-Za-z0-9._-]+?)(?:\\.git)?\\/?$/i.exec(\n String(c.backupRepo || '').trim(),\n );\n return m ? m[1] : null;\n}\n"],"names":[],"mappings":"yDASO,SAAS,mBAAmB,CAGE,EAAA;AACnC,EAAI,IAAA,CAAC,GAAU,OAAA,IAAA;AACf,EAAM,MAAA,SAAA,GAAY,oBAAqB,CAAA,CAAA,CAAE,OAAO,CAAA;AAChD,EAAA,IAAI,WAAkB,OAAA,SAAA;AACtB,EAAM,MAAA,CAAA,GAAI,qFAAqF,IAAK,CAAA,MAAA,CAAO,EAAE,UAAc,IAAA,EAAE,CAAE,CAAA,IAAA,EAAM,CAAA;AACrI,EAAO,OAAA,CAAA,GAAI,CAAE,CAAA,CAAC,CAAI,GAAA,IAAA;AACpB"}
@@ -1 +1 @@
1
- {"version":3,"file":"directions.js","sources":["../../../../../src/features/webbuilder/web/design/directions.ts"],"sourcesContent":["/**\n * G4 (aicode-stack#343): guided style directions before a NEW build.\n *\n * The user sees three distinct directions (palette, font pair, radius /\n * density / imagery) and picks one or skips; the pick rides the build as\n * `props.designDirection` and is saved in the project settings so later edits\n * keep the same tokens.\n *\n * - `validateDirection`: hex colours, fonts from an allow-list of common\n * Google Fonts, enums, and a COMPUTED WCAG AA check (text and muted text on\n * the background); a failing text colour is adjusted, never assumed fine.\n * - `CURATED_DIRECTIONS` + `pickDirectionsForBrief`: works with no AI call.\n * - `buildDirectionsPrompt` / `parseDirectionsReply` / `resolveDirections`:\n * the optional AI lane (plain chat, strict JSON), best-effort with a\n * timeout and the curated set as the fallback.\n *\n * Pure: no React, no browser globals - runs under `node --test`. The server\n * re-validates with the same rules (page-creator `webbuilderDesignDirection.ts`);\n * keep the font allow-list and the enums in step with it.\n */\n\nexport const PALETTE_ROLES = ['background', 'surface', 'text', 'muted', 'primary', 'accent'] as const;\nexport type PaletteRole = (typeof PALETTE_ROLES)[number];\n/** `muted` is optional (5-6 colours); the others are required. */\nexport type DesignPalette = Record<Exclude<PaletteRole, 'muted'>, string> & { muted?: string };\n\nexport const RADIUS_STYLES = ['none', 'sm', 'md', 'lg', 'full'] as const;\nexport type RadiusStyle = (typeof RADIUS_STYLES)[number];\nexport const DENSITY_STYLES = ['compact', 'comfortable', 'airy'] as const;\nexport type DensityStyle = (typeof DENSITY_STYLES)[number];\nexport const IMAGERY_STYLES = ['photo', 'illustration', 'gradient', 'geometric', 'texture', 'minimal'] as const;\nexport type ImageryStyle = (typeof IMAGERY_STYLES)[number];\n\nexport interface DesignDirection {\n /** Slug, e.g. `golden-hour`. */\n id: string;\n name: string;\n /** One line: how the site should feel. */\n mood: string;\n palette: DesignPalette;\n fonts: { heading: string; body: string };\n radius: RadiusStyle;\n density: DensityStyle;\n imagery: ImageryStyle;\n}\n\nexport const MAX_NAME_CHARS = 40;\nexport const MAX_MOOD_CHARS = 160;\n/** WCAG 2.x AA for normal text. */\nexport const AA_CONTRAST = 4.5;\n\n// ---------------------------------------------------------------- fonts\n\nexport type FontCategory = 'sans-serif' | 'serif' | 'display' | 'monospace' | 'handwriting';\ninterface FontSpec {\n category: FontCategory;\n /** False: the family has one weight (400); the css2 API refuses a `wght@…;700` request for it. */\n bold: boolean;\n}\n\n/** Common Google Fonts the agent may use. Keys are the exact family names. */\nexport const GOOGLE_FONTS: Readonly<Record<string, FontSpec>> = {\n Inter: { category: 'sans-serif', bold: true },\n Roboto: { category: 'sans-serif', bold: true },\n 'Open Sans': { category: 'sans-serif', bold: true },\n Lato: { category: 'sans-serif', bold: true },\n Montserrat: { category: 'sans-serif', bold: true },\n Poppins: { category: 'sans-serif', bold: true },\n Nunito: { category: 'sans-serif', bold: true },\n 'Nunito Sans': { category: 'sans-serif', bold: true },\n Raleway: { category: 'sans-serif', bold: true },\n 'Work Sans': { category: 'sans-serif', bold: true },\n Rubik: { category: 'sans-serif', bold: true },\n Karla: { category: 'sans-serif', bold: true },\n Mulish: { category: 'sans-serif', bold: true },\n Manrope: { category: 'sans-serif', bold: true },\n 'DM Sans': { category: 'sans-serif', bold: true },\n 'Plus Jakarta Sans': { category: 'sans-serif', bold: true },\n Outfit: { category: 'sans-serif', bold: true },\n Sora: { category: 'sans-serif', bold: true },\n 'Space Grotesk': { category: 'sans-serif', bold: true },\n 'IBM Plex Sans': { category: 'sans-serif', bold: true },\n Archivo: { category: 'sans-serif', bold: true },\n 'Libre Franklin': { category: 'sans-serif', bold: true },\n 'Source Sans 3': { category: 'sans-serif', bold: true },\n Figtree: { category: 'sans-serif', bold: true },\n Lexend: { category: 'sans-serif', bold: true },\n Urbanist: { category: 'sans-serif', bold: true },\n Quicksand: { category: 'sans-serif', bold: true },\n Barlow: { category: 'sans-serif', bold: true },\n 'Josefin Sans': { category: 'sans-serif', bold: true },\n Syne: { category: 'sans-serif', bold: true },\n Fredoka: { category: 'sans-serif', bold: true },\n Oswald: { category: 'sans-serif', bold: true },\n 'Archivo Black': { category: 'display', bold: false },\n 'Bebas Neue': { category: 'display', bold: false },\n Anton: { category: 'display', bold: false },\n 'Abril Fatface': { category: 'display', bold: false },\n Righteous: { category: 'display', bold: false },\n 'DM Serif Display': { category: 'serif', bold: false },\n 'Playfair Display': { category: 'serif', bold: true },\n Lora: { category: 'serif', bold: true },\n Merriweather: { category: 'serif', bold: true },\n 'Libre Baskerville': { category: 'serif', bold: true },\n 'Cormorant Garamond': { category: 'serif', bold: true },\n 'EB Garamond': { category: 'serif', bold: true },\n Fraunces: { category: 'serif', bold: true },\n 'Source Serif 4': { category: 'serif', bold: true },\n 'Crimson Pro': { category: 'serif', bold: true },\n 'IBM Plex Mono': { category: 'monospace', bold: true },\n 'JetBrains Mono': { category: 'monospace', bold: true },\n 'Space Mono': { category: 'monospace', bold: true },\n Pacifico: { category: 'handwriting', bold: false },\n Caveat: { category: 'handwriting', bold: true },\n};\n\nconst FONT_BY_LOWER = new Map(Object.keys(GOOGLE_FONTS).map((n) => [n.toLowerCase(), n]));\n\n/** The allow-listed family name (canonical case), or null. */\nexport function canonicalFont(name: unknown): string | null {\n if (typeof name !== 'string') return null;\n const key = name.replace(/[\"']/g, '').replace(/\\s+/g, ' ').trim().toLowerCase();\n return FONT_BY_LOWER.get(key) ?? null;\n}\n\n/** A CSS `font-family` value with a generic fallback: `'Playfair Display', Georgia, serif`. */\nexport function fontStack(name: string): string {\n const spec = GOOGLE_FONTS[name];\n const fallback =\n spec?.category === 'serif'\n ? 'Georgia, serif'\n : spec?.category === 'monospace'\n ? 'ui-monospace, monospace'\n : spec?.category === 'handwriting'\n ? 'cursive'\n : 'system-ui, sans-serif';\n return `'${name}', ${fallback}`;\n}\n\n/** One css2 URL for the families (allow-listed only, de-duplicated, sorted so the URL is stable). */\nexport function googleFontsHref(families: Iterable<string>): string | null {\n const names = [...new Set([...families].map(canonicalFont).filter((n): n is string => Boolean(n)))].sort();\n if (!names.length) return null;\n const params = names.map((n) => `family=${n.replace(/ /g, '+')}${GOOGLE_FONTS[n].bold ? ':wght@400;700' : ''}`);\n return `https://fonts.googleapis.com/css2?${params.join('&')}&display=swap`;\n}\n\n// ---------------------------------------------------------------- colour + contrast\n\nconst HEX_RE = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i;\n\n/** `#abc` / `ABCDEF` -> `#aabbcc` (lower case), or null. */\nexport function normalizeHex(v: unknown): string | null {\n if (typeof v !== 'string') return null;\n const m = HEX_RE.exec(v.trim());\n if (!m) return null;\n const h = m[1].length === 3 ? m[1].replace(/./g, (c) => c + c) : m[1];\n return `#${h.toLowerCase()}`;\n}\n\nfunction rgb(hex: string): [number, number, number] {\n const n = parseInt(hex.slice(1), 16);\n return [(n >> 16) & 255, (n >> 8) & 255, n & 255];\n}\n\nfunction toHex([r, g, b]: [number, number, number]): string {\n return `#${[r, g, b]\n .map((c) =>\n Math.round(Math.min(255, Math.max(0, c)))\n .toString(16)\n .padStart(2, '0'),\n )\n .join('')}`;\n}\n\n/** WCAG relative luminance of a normalized hex colour. */\nexport function relativeLuminance(hex: string): number {\n const [r, g, b] = rgb(hex).map((c) => {\n const s = c / 255;\n return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;\n });\n return 0.2126 * r + 0.7152 * g + 0.0722 * b;\n}\n\n/** WCAG contrast ratio (1-21) between two normalized hex colours. */\nexport function contrastRatio(a: string, b: string): number {\n const la = relativeLuminance(a);\n const lb = relativeLuminance(b);\n return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);\n}\n\n/**\n * `text` when it already reaches `min` on `bg`; else `text` mixed step by step\n * toward black (light backgrounds) or white (dark ones) until it does. Keeps\n * the hue as long as possible; black / white is the last resort.\n */\nexport function ensureContrast(text: string, bg: string, min = AA_CONTRAST): string {\n if (contrastRatio(text, bg) >= min) return text;\n const towardBlack = contrastRatio('#000000', bg) >= contrastRatio('#ffffff', bg);\n const target: [number, number, number] = towardBlack ? [0, 0, 0] : [255, 255, 255];\n const [r, g, b] = rgb(text);\n for (let t = 0.05; t <= 1.0001; t += 0.05) {\n const mixed = toHex([r + (target[0] - r) * t, g + (target[1] - g) * t, b + (target[2] - b) * t]);\n if (contrastRatio(mixed, bg) >= min) return mixed;\n }\n return towardBlack ? '#000000' : '#ffffff';\n}\n\n/**\n * `color` when it reaches `min` on EVERY background (page and surface); else\n * mixed toward black or white (picked by the first background) until it does.\n * When no mix works, the extreme with the best worst-case contrast.\n */\nexport function ensureContrastOn(color: string, backgrounds: string[], min = AA_CONTRAST): string {\n const worst = (c: string) => Math.min(...backgrounds.map((bg) => contrastRatio(c, bg)));\n if (worst(color) >= min) return color;\n const first = backgrounds[0];\n const towardBlack = contrastRatio('#000000', first) >= contrastRatio('#ffffff', first);\n const target = towardBlack ? [0, 0, 0] : [255, 255, 255];\n const src = rgb(color);\n for (let t = 0.05; t <= 1.0001; t += 0.05) {\n const mixed = toHex(src.map((c, i) => c + (target[i] - c) * t) as [number, number, number]);\n if (worst(mixed) >= min) return mixed;\n }\n return worst('#000000') >= worst('#ffffff') ? '#000000' : '#ffffff';\n}\n\n/**\n * Button label colour on `primary`: black or white, whichever has more\n * contrast (one of them always reaches at least 4.58:1, so labels pass AA).\n */\nexport function onColor(bg: string): string {\n return contrastRatio('#ffffff', bg) >= contrastRatio('#000000', bg) ? '#ffffff' : '#000000';\n}\n\n// ---------------------------------------------------------------- validation\n\nexport type DirectionValidation =\n | {\n ok: true;\n direction: DesignDirection;\n /** What was fixed (e.g. text colour for contrast). */ adjusted: string[];\n }\n | { ok: false; errors: string[] };\n\nconst isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);\n\n/** Identical to the server's `cleanLine` (webbuilderDesignDirection.ts), so the card and the agent show the same name. */\nexport function cleanLine(v: unknown, max: number): string {\n if (typeof v !== 'string') return '';\n const t = v\n .slice(0, max * 4)\n .replace(/[\\u0000-\\u001f\\u007f]+/g, ' ')\n .replace(/[<>`{}#]/g, '')\n .replace(/\\s+/g, ' ')\n .trim();\n return t.length > max ? t.slice(0, max).trim() : t;\n}\n\nexport function slugify(v: string): string {\n return v\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 40);\n}\n\nconst oneOf = <T extends string>(list: readonly T[], v: unknown): T | null =>\n typeof v === 'string' && (list as readonly string[]).includes(v.trim().toLowerCase())\n ? (v.trim().toLowerCase() as T)\n : null;\n\n/**\n * Validate (and normalise) a direction from any source: the curated set, the\n * AI lane or stored settings. Text and muted colours that miss AA on the\n * background are adjusted (reported in `adjusted`); anything else invalid is\n * an error.\n */\nexport function validateDirection(raw: unknown): DirectionValidation {\n if (!isObj(raw)) return { ok: false, errors: ['direction must be an object'] };\n const errors: string[] = [];\n const adjusted: string[] = [];\n\n const name = cleanLine(raw.name, MAX_NAME_CHARS);\n if (!name) errors.push('name is required');\n const mood = cleanLine(raw.mood, MAX_MOOD_CHARS);\n if (!mood) errors.push('mood is required');\n const id = slugify(typeof raw.id === 'string' && raw.id.trim() ? raw.id : name) || 'direction';\n\n const palette: Partial<Record<PaletteRole, string>> = {};\n if (!isObj(raw.palette)) errors.push('palette must be an object');\n else {\n for (const role of PALETTE_ROLES) {\n const v = raw.palette[role];\n if (role === 'muted' && (v === undefined || v === null || v === '')) continue;\n const hex = normalizeHex(v);\n if (!hex) errors.push(`palette.${role} must be a hex colour`);\n else palette[role] = hex;\n }\n }\n\n const fonts = isObj(raw.fonts) ? raw.fonts : {};\n const heading = canonicalFont(fonts.heading);\n const body = canonicalFont(fonts.body);\n if (!heading) errors.push('fonts.heading must be one of the allowed Google Fonts');\n if (!body) errors.push('fonts.body must be one of the allowed Google Fonts');\n\n const radius = oneOf(RADIUS_STYLES, raw.radius);\n if (!radius) errors.push(`radius must be one of ${RADIUS_STYLES.join(', ')}`);\n const density = oneOf(DENSITY_STYLES, raw.density);\n if (!density) errors.push(`density must be one of ${DENSITY_STYLES.join(', ')}`);\n const imagery = oneOf(IMAGERY_STYLES, raw.imagery);\n if (!imagery) errors.push(`imagery must be one of ${IMAGERY_STYLES.join(', ')}`);\n\n if (errors.length) return { ok: false, errors };\n\n // Text and muted text sit on the page AND on cards: AA on both. Links use the text colour plus\n // an underline (primary is for button fills, labelled with `onColor`), so primary needs no check.\n const grounds = [palette.background!, palette.surface!];\n const text = ensureContrastOn(palette.text!, grounds);\n if (text !== palette.text) adjusted.push(`text ${palette.text} -> ${text} (contrast on background / surface)`);\n palette.text = text;\n if (palette.muted) {\n const muted = ensureContrastOn(palette.muted, grounds);\n if (muted !== palette.muted)\n adjusted.push(`muted ${palette.muted} -> ${muted} (contrast on background / surface)`);\n palette.muted = muted;\n }\n\n return {\n ok: true,\n adjusted,\n direction: {\n id,\n name,\n mood,\n palette: palette as DesignPalette,\n fonts: { heading: heading!, body: body! },\n radius: radius!,\n density: density!,\n imagery: imagery!,\n },\n };\n}\n\n/** The validated direction, or null. */\nexport function toDesignDirection(raw: unknown): DesignDirection | null {\n const r = validateDirection(raw);\n return r.ok ? r.direction : null;\n}\n\n/** `props.designDirection` for the build turn ({} when there is none). */\nexport function designDirectionTurnProps(d: DesignDirection | null | undefined): { designDirection?: DesignDirection } {\n const v = d ? toDesignDirection(d) : null;\n return v ? { designDirection: v } : {};\n}\n\nexport interface TurnDirectionPlan {\n /** Spread into the post props. `designDirection: null` = skipped on a new build (no settings fallback). */\n props: { designDirection?: DesignDirection | null };\n /** Write to the project settings after the turn is delivered (`null` clears); undefined = leave them. */\n save?: DesignDirection | null;\n}\n\n/**\n * What a connector turn sends and saves (the server falls back to settings on EDIT turns only):\n * - a new build that went through the picker (`designDirection` key present): the pick, saved; or an\n * explicit `null` when skipped / styles off, clearing an older pick in this channel's settings;\n * - an edit: the project's saved direction, so edits keep the same tokens;\n * - anything else: nothing.\n */\nexport function planTurnDirection(input: {\n isEdit: boolean;\n opts?: { designDirection?: DesignDirection | null } | null;\n saved?: DesignDirection | null;\n /** The channel was minted for this send (nothing saved to clear). */\n minted?: boolean;\n}): TurnDirectionPlan {\n const opts = input.opts;\n if (!input.isEdit && opts && 'designDirection' in opts) {\n const picked = opts.designDirection ? toDesignDirection(opts.designDirection) : null;\n if (picked) return { props: { designDirection: picked }, save: picked };\n return { props: { designDirection: null }, ...(!input.minted && input.saved ? { save: null } : {}) };\n }\n if (input.isEdit) return { props: designDirectionTurnProps(input.saved) };\n return { props: {} };\n}\n\n// ---------------------------------------------------------------- curated fallback set\n\nexport interface CuratedDirection extends DesignDirection {\n /** Brief keywords that make this direction a good fit. */\n keywords: string[];\n}\n\nexport const CURATED_DIRECTIONS: readonly CuratedDirection[] = [\n {\n id: 'quiet-minimal',\n name: 'Quiet Minimal',\n mood: 'Calm, precise and spacious - lots of white space and confident type.',\n palette: {\n background: '#ffffff',\n surface: '#f5f5f4',\n text: '#1c1917',\n muted: '#57534e',\n primary: '#1c1917',\n accent: '#a8a29e',\n },\n fonts: { heading: 'Manrope', body: 'Inter' },\n radius: 'sm',\n density: 'airy',\n imagery: 'minimal',\n keywords: [\n 'minimal',\n 'clean',\n 'simple',\n 'portfolio',\n 'architect',\n 'architecture',\n 'studio',\n 'photographer',\n 'photography',\n 'designer',\n 'resume',\n 'cv',\n ],\n },\n {\n id: 'golden-hour',\n name: 'Golden Hour',\n mood: 'Warm and welcoming, like late-afternoon light in a neighbourhood cafe.',\n palette: {\n background: '#fdf6ec',\n surface: '#f6e7d3',\n text: '#3b2a1e',\n muted: '#6b5444',\n primary: '#c2410c',\n accent: '#e9a23b',\n },\n fonts: { heading: 'Fraunces', body: 'Nunito Sans' },\n radius: 'lg',\n density: 'comfortable',\n imagery: 'photo',\n keywords: [\n 'bakery',\n 'cafe',\n 'coffee',\n 'restaurant',\n 'food',\n 'recipe',\n 'recipes',\n 'kitchen',\n 'family',\n 'home',\n 'wedding',\n 'bnb',\n 'catering',\n 'warm',\n ],\n },\n {\n id: 'loud-and-clear',\n name: 'Loud & Clear',\n mood: 'High-energy and bold - big type, hard edges, strong contrast.',\n palette: {\n background: '#0a0a0a',\n surface: '#1a1a1a',\n text: '#fafafa',\n muted: '#a3a3a3',\n primary: '#facc15',\n accent: '#ef4444',\n },\n fonts: { heading: 'Archivo Black', body: 'Archivo' },\n radius: 'none',\n density: 'compact',\n imagery: 'geometric',\n keywords: [\n 'fitness',\n 'gym',\n 'sport',\n 'sports',\n 'event',\n 'festival',\n 'music',\n 'band',\n 'launch',\n 'streetwear',\n 'bold',\n 'conference',\n 'marathon',\n ],\n },\n {\n id: 'broadsheet',\n name: 'Broadsheet',\n mood: 'Editorial and literate - classic serif headlines with a newspaper rhythm.',\n palette: {\n background: '#fbfaf7',\n surface: '#f0ede6',\n text: '#111111',\n muted: '#555048',\n primary: '#9f1239',\n accent: '#1e3a8a',\n },\n fonts: { heading: 'Playfair Display', body: 'Libre Franklin' },\n radius: 'none',\n density: 'comfortable',\n imagery: 'photo',\n keywords: [\n 'blog',\n 'magazine',\n 'news',\n 'journal',\n 'writer',\n 'writing',\n 'book',\n 'books',\n 'author',\n 'publication',\n 'newsletter',\n 'podcast',\n 'editorial',\n 'essay',\n ],\n },\n {\n id: 'candy-pop',\n name: 'Candy Pop',\n mood: 'Playful and friendly - round shapes, bright colour and a wink of fun.',\n palette: {\n background: '#fff7fb',\n surface: '#ffe4f1',\n text: '#2e1065',\n muted: '#5b4a7a',\n primary: '#db2777',\n accent: '#22c55e',\n },\n fonts: { heading: 'Fredoka', body: 'Nunito' },\n radius: 'full',\n density: 'comfortable',\n imagery: 'illustration',\n keywords: [\n 'kids',\n 'children',\n 'child',\n 'game',\n 'games',\n 'toy',\n 'toys',\n 'party',\n 'pet',\n 'pets',\n 'school',\n 'fun',\n 'candy',\n 'ice',\n 'playful',\n 'daycare',\n ],\n },\n {\n id: 'noir-gold',\n name: 'Noir & Gold',\n mood: 'Luxurious and refined - deep darks, gold accents and elegant serifs.',\n palette: {\n background: '#0f0e0c',\n surface: '#1c1a16',\n text: '#f5f0e6',\n muted: '#b5ab98',\n primary: '#c9a227',\n accent: '#8c6d1f',\n },\n fonts: { heading: 'Cormorant Garamond', body: 'Montserrat' },\n radius: 'none',\n density: 'airy',\n imagery: 'photo',\n keywords: [\n 'luxury',\n 'jewelry',\n 'jewellery',\n 'fashion',\n 'hotel',\n 'wine',\n 'watch',\n 'watches',\n 'premium',\n 'boutique',\n 'estate',\n 'perfume',\n 'cocktail',\n 'elegant',\n ],\n },\n {\n id: 'terminal-grid',\n name: 'Terminal Grid',\n mood: 'Technical and sharp - dark UI, crisp grids and a hint of neon.',\n palette: {\n background: '#0b1020',\n surface: '#131a2e',\n text: '#e2e8f0',\n muted: '#94a3b8',\n primary: '#22d3ee',\n accent: '#a78bfa',\n },\n fonts: { heading: 'Space Grotesk', body: 'IBM Plex Sans' },\n radius: 'md',\n density: 'compact',\n imagery: 'gradient',\n keywords: [\n 'saas',\n 'ai',\n 'developer',\n 'developers',\n 'api',\n 'crypto',\n 'dashboard',\n 'tech',\n 'software',\n 'analytics',\n 'data',\n 'devtools',\n 'cloud',\n 'startup',\n ],\n },\n {\n id: 'field-and-fern',\n name: 'Field & Fern',\n mood: 'Organic and grounded - earthy greens, natural textures, unhurried.',\n palette: {\n background: '#f4f1ea',\n surface: '#e6e2d3',\n text: '#23301f',\n muted: '#4f5b48',\n primary: '#3f6212',\n accent: '#b45309',\n },\n fonts: { heading: 'DM Serif Display', body: 'Karla' },\n radius: 'lg',\n density: 'airy',\n imagery: 'texture',\n keywords: [\n 'garden',\n 'gardening',\n 'farm',\n 'organic',\n 'eco',\n 'plant',\n 'plants',\n 'nature',\n 'sustainable',\n 'outdoor',\n 'florist',\n 'flowers',\n 'hiking',\n 'camping',\n ],\n },\n {\n id: 'clear-blue',\n name: 'Clear Blue',\n mood: 'Trustworthy and professional - clean layout, confident blue, no noise.',\n palette: {\n background: '#ffffff',\n surface: '#f1f5f9',\n text: '#0f172a',\n muted: '#475569',\n primary: '#2563eb',\n accent: '#0ea5e9',\n },\n fonts: { heading: 'Plus Jakarta Sans', body: 'Inter' },\n radius: 'md',\n density: 'comfortable',\n imagery: 'photo',\n keywords: [\n 'consulting',\n 'consultant',\n 'finance',\n 'law',\n 'lawyer',\n 'legal',\n 'clinic',\n 'medical',\n 'dentist',\n 'insurance',\n 'bank',\n 'accounting',\n 'business',\n 'agency',\n 'corporate',\n ],\n },\n {\n id: 'sunset-diner',\n name: 'Sunset Diner',\n mood: 'Retro and characterful - chunky display type and sun-faded colour.',\n palette: {\n background: '#fff4e0',\n surface: '#ffe3b3',\n text: '#3d1f0f',\n muted: '#6e4630',\n primary: '#c2410c',\n accent: '#0b7285',\n },\n fonts: { heading: 'Abril Fatface', body: 'Work Sans' },\n radius: 'md',\n density: 'comfortable',\n imagery: 'illustration',\n keywords: [\n 'diner',\n 'retro',\n 'vintage',\n 'barber',\n 'records',\n 'vinyl',\n 'brewery',\n 'beer',\n 'burger',\n 'pizza',\n 'taco',\n 'food truck',\n 'arcade',\n ],\n },\n {\n id: 'soft-sage',\n name: 'Soft Sage',\n mood: 'Calm and restorative - muted sage, gentle serif headings, room to breathe.',\n palette: {\n background: '#f6f8f5',\n surface: '#e7eee6',\n text: '#1f2d27',\n muted: '#4d5f56',\n primary: '#3f6b5c',\n accent: '#d4a373',\n },\n fonts: { heading: 'Lora', body: 'Mulish' },\n radius: 'lg',\n density: 'airy',\n imagery: 'photo',\n keywords: [\n 'wellness',\n 'yoga',\n 'spa',\n 'therapy',\n 'therapist',\n 'meditation',\n 'health',\n 'coach',\n 'coaching',\n 'skincare',\n 'massage',\n 'mindfulness',\n 'calm',\n ],\n },\n {\n id: 'neon-night',\n name: 'Neon Night',\n mood: 'Futuristic and electric - deep night tones lit by violet and pink glows.',\n palette: {\n background: '#09090f',\n surface: '#15152a',\n text: '#f4f4ff',\n muted: '#a1a1c2',\n primary: '#8b5cf6',\n accent: '#ec4899',\n },\n fonts: { heading: 'Sora', body: 'Outfit' },\n radius: 'lg',\n density: 'comfortable',\n imagery: 'gradient',\n keywords: [\n 'gaming',\n 'gamer',\n 'nightclub',\n 'club',\n 'esports',\n 'nft',\n 'web3',\n 'dj',\n 'synth',\n 'futuristic',\n 'nightlife',\n 'vr',\n ],\n },\n];\n\n/** Order used when the brief gives no hints: as different from each other as possible. */\nconst DEFAULT_ORDER = [\n 'quiet-minimal',\n 'golden-hour',\n 'terminal-grid',\n 'broadsheet',\n 'candy-pop',\n 'noir-gold',\n 'field-and-fern',\n 'loud-and-clear',\n 'clear-blue',\n 'soft-sage',\n 'neon-night',\n 'sunset-diner',\n];\n\nfunction keywordScore(d: CuratedDirection, brief: string): number {\n let score = 0;\n for (const k of d.keywords) {\n const re = new RegExp(`\\\\b${k.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}s?\\\\b`, 'i');\n if (re.test(brief)) score += 1;\n }\n return score;\n}\n\n/** Every curated direction, best fit for the brief first (ties keep the diverse default order). */\nexport function rankDirectionsForBrief(brief: string | null | undefined): CuratedDirection[] {\n const text = String(brief ?? '');\n const order = new Map(DEFAULT_ORDER.map((id, i) => [id, i]));\n return [...CURATED_DIRECTIONS]\n .map((d) => ({ d, score: keywordScore(d, text) }))\n .sort((a, b) => b.score - a.score || (order.get(a.d.id) ?? 99) - (order.get(b.d.id) ?? 99))\n .map((x) => x.d);\n}\n\n/** Strip the curated-only `keywords`. */\nexport function asDirection(d: DesignDirection): DesignDirection {\n const { id, name, mood, palette, fonts, radius, density, imagery } = d;\n return { id, name, mood, palette: { ...palette }, fonts: { ...fonts }, radius, density, imagery };\n}\n\n/**\n * Three distinct curated directions for the brief (keyword heuristic). `exclude`\n * (ids already shown) gives the \"Shuffle\" set; when too few are left, the\n * ranking starts over.\n */\nexport function pickDirectionsForBrief(\n brief: string | null | undefined,\n exclude: Iterable<string> = [],\n): DesignDirection[] {\n const ranked = rankDirectionsForBrief(brief);\n const skip = new Set(exclude);\n const fresh = ranked.filter((d) => !skip.has(d.id));\n const pool = fresh.length >= 3 ? fresh : [...fresh, ...ranked.filter((d) => skip.has(d.id))];\n return pool.slice(0, 3).map(asDirection);\n}\n\n// ---------------------------------------------------------------- AI lane (optional)\n\nexport const DIRECTIONS_SESSION_KEY = 'webbuilder-design-directions';\nexport const DIRECTIONS_TIMEOUT_MS = 12_000;\n\n/** One plain-chat session per build channel (reused across requests), not one per call. */\nexport function directionsSessionKey(channelId: string | null | undefined): string {\n const id = String(channelId ?? '')\n .trim()\n .replace(/[^A-Za-z0-9_-]/g, '')\n .slice(0, 80);\n return id ? `${DIRECTIONS_SESSION_KEY}-${id}` : DIRECTIONS_SESSION_KEY;\n}\n\n/** The strict-JSON prompt sent through the plain-chat lane. */\nexport function buildDirectionsPrompt(brief: string): string {\n return [\n 'You are an art director proposing visual style directions for a website BEFORE it is built.',\n 'Do NOT write code, do NOT build anything, do NOT ask questions, do NOT call any tool or connector.',\n 'Propose exactly 3 clearly DIFFERENT directions that fit the request below.',\n 'Reply with ONLY one JSON object, no prose and no code fence, in exactly this shape:',\n '{\"directions\":[{\"name\":\"2-3 words\",\"mood\":\"one sentence, max 140 characters\",' +\n '\"palette\":{\"background\":\"#rrggbb\",\"surface\":\"#rrggbb\",\"text\":\"#rrggbb\",\"muted\":\"#rrggbb\",\"primary\":\"#rrggbb\",\"accent\":\"#rrggbb\"},' +\n '\"fonts\":{\"heading\":\"<font>\",\"body\":\"<font>\"},\"radius\":\"<radius>\",\"density\":\"<density>\",\"imagery\":\"<imagery>\"}]}',\n `Fonts must be exact names from this list: ${Object.keys(GOOGLE_FONTS).join(', ')}.`,\n `radius: one of ${RADIUS_STYLES.join(', ')}. density: one of ${DENSITY_STYLES.join(', ')}. imagery: one of ${IMAGERY_STYLES.join(', ')}.`,\n 'The text and muted colours must have at least 4.5:1 contrast on both the background and the surface. Links use the text colour with an underline; primary is a button fill.',\n '',\n `Website request:\\n${String(brief ?? '')\n .trim()\n .slice(0, 2000)}`,\n ].join('\\n');\n}\n\n/** The validated directions in an AI reply (fenced or not, array or `{ directions }`); [] when none. */\nexport function parseDirectionsReply(reply: string | null | undefined): DesignDirection[] {\n let t = String(reply ?? '').trim();\n const fenced = /```(?:json)?\\s*\\n?([\\s\\S]*?)```/i.exec(t);\n if (fenced) t = fenced[1].trim();\n const start = t.search(/[[{]/);\n if (start < 0) return [];\n const end = Math.max(t.lastIndexOf('}'), t.lastIndexOf(']'));\n if (end <= start) return [];\n let data: unknown;\n try {\n data = JSON.parse(t.slice(start, end + 1));\n } catch {\n return [];\n }\n const list = Array.isArray(data) ? data : isObj(data) && Array.isArray(data.directions) ? data.directions : [];\n const out: DesignDirection[] = [];\n const seen = new Set<string>();\n for (const item of list.slice(0, 6)) {\n const d = toDesignDirection(item);\n if (!d || seen.has(d.name.toLowerCase())) continue;\n seen.add(d.name.toLowerCase());\n // A model-made id could collide with a curated one; keep ids unique.\n out.push({ ...d, id: `ai-${d.id}`.slice(0, 40) });\n }\n return out.slice(0, 3);\n}\n\nexport interface ResolvedDirections {\n directions: DesignDirection[];\n source: 'ai' | 'curated';\n}\n\n/**\n * The AI directions for the brief, topped up from the curated set; the curated\n * three on any failure, an empty reply or after `timeoutMs`. Never throws.\n */\nexport async function resolveDirections(\n brief: string,\n suggest: ((prompt: string, opts: { signal: AbortSignal }) => Promise<string>) | null | undefined,\n opts: { timeoutMs?: number; signal?: AbortSignal } = {},\n): Promise<ResolvedDirections> {\n const curated = (): ResolvedDirections => ({ directions: pickDirectionsForBrief(brief), source: 'curated' });\n if (!suggest) return curated();\n const ctrl = new AbortController();\n const onAbort = () => ctrl.abort();\n opts.signal?.addEventListener('abort', onAbort, { once: true });\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const timeout = new Promise<null>((resolve) => {\n timer = setTimeout(() => {\n ctrl.abort();\n resolve(null);\n }, opts.timeoutMs ?? DIRECTIONS_TIMEOUT_MS);\n });\n const reply = await Promise.race([\n suggest(buildDirectionsPrompt(brief), { signal: ctrl.signal }).catch(() => null),\n timeout,\n ]);\n const ai = reply ? parseDirectionsReply(reply) : [];\n if (!ai.length) return curated();\n const names = new Set(ai.map((d) => d.name.toLowerCase()));\n const fill = rankDirectionsForBrief(brief)\n .filter((d) => !names.has(d.name.toLowerCase()))\n .slice(0, 3 - ai.length)\n .map(asDirection);\n return { directions: [...ai, ...fill], source: 'ai' };\n } catch {\n return curated();\n } finally {\n if (timer) clearTimeout(timer);\n opts.signal?.removeEventListener('abort', onAbort);\n }\n}\n\n// ---------------------------------------------------------------- picker state\n\n/** The open style-direction picker for the next new build. */\nexport interface DirectionPickerState {\n brief: string;\n directions: DesignDirection[];\n source: 'ai' | 'curated';\n /** The AI lane is still working. */\n loading: boolean;\n /** The user hovered, focused or clicked the cards: never swap them under the cursor. */\n touched?: boolean;\n /** AI directions that arrived after the user touched the cards (\"Tailored styles ready\"). */\n tailored?: DesignDirection[];\n}\n\n/**\n * The AI lane answered: replace the curated cards only while the user hasn't\n * touched them; otherwise park the result behind the \"Tailored styles ready\" chip.\n */\nexport function withTailoredDirections(state: DirectionPickerState, result: ResolvedDirections): DirectionPickerState {\n const next: DirectionPickerState = { ...state, loading: false };\n if (result.source !== 'ai' || !result.directions.length) return next;\n if (state.touched) return { ...next, tailored: result.directions };\n return { ...next, directions: result.directions, source: 'ai', tailored: undefined };\n}\n\n/** \"Tailored styles ready\" clicked: show the parked AI directions. */\nexport function showTailoredDirections(state: DirectionPickerState): DirectionPickerState {\n if (!state.tailored?.length) return state;\n return { ...state, directions: state.tailored, source: 'ai', tailored: undefined };\n}\n\n// ---------------------------------------------------------------- when to offer\n\n/**\n * Directions are offered only before a NEW build: New app, a template remix or\n * \"New from this\" - never an edit of an open build, a plain chat turn, or a\n * turn that already carries a plan.\n */\nexport function isNewBuildTurn(\n opts:\n | {\n forceNew?: boolean;\n template?: unknown;\n editTarget?: unknown;\n referenceArtifact?: unknown;\n plan?: string;\n }\n | null\n | undefined,\n): boolean {\n if (!opts || opts.editTarget || opts.plan) return false;\n return Boolean(opts.forceNew || opts.template || opts.referenceArtifact);\n}\n\n/** Pixel radius used for the card preview (and documented to the agent). */\nexport const RADIUS_PX: Readonly<Record<RadiusStyle, number>> = { none: 0, sm: 6, md: 12, lg: 20, full: 9999 };\n"],"names":[],"mappings":"AAqBO,MAAM,gBAAgB,CAAC,YAAA,EAAc,WAAW,MAAQ,EAAA,OAAA,EAAS,WAAW,QAAQ;AAMpF,MAAM,gBAAgB,CAAC,MAAA,EAAQ,IAAM,EAAA,IAAA,EAAM,MAAM,MAAM;AAEvD,MAAM,cAAiB,GAAA,CAAC,SAAW,EAAA,aAAA,EAAe,MAAM;AAExD,MAAM,iBAAiB,CAAC,OAAA,EAAS,gBAAgB,UAAY,EAAA,WAA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;AAAA,MACA,OAAA;AAAA,MACA,KAAO,EAAA;AAAA,QACL,OAAA;AAAA,QACA;AAAA,OACF;AAAA,MACA,MAAA;AAAA,MACA,OAAA;AAAA,MACA;AAAA;AACF,GACF;AACF;AAGO,SAAS,kBAAkB,GAAsC,EAAA;AACtE,EAAM,MAAA,CAAA,GAAI,kBAAkB,GAAG,CAAA;AAC/B,EAAO,OAAA,CAAA,CAAE,EAAK,GAAA,CAAA,CAAE,SAAY,GAAA,IAAA;AAC9B"}
1
+ {"version":3,"file":"directions.js","sources":["../../../../../src/features/webbuilder/web/design/directions.ts"],"sourcesContent":["/**\n * G4 (aicode-stack#343): guided style directions before a NEW build.\n *\n * The user sees three distinct directions (palette, font pair, radius /\n * density / imagery) and picks one or skips; the pick rides the build as\n * `props.designDirection` and is saved in the project settings so later edits\n * keep the same tokens.\n *\n * - `validateDirection`: hex colours, fonts from an allow-list of common\n * Google Fonts, enums, and a COMPUTED WCAG AA check (text and muted text on\n * the background); a failing text colour is adjusted, never assumed fine.\n * - `CURATED_DIRECTIONS` + `pickDirectionsForBrief`: works with no AI call.\n * - `buildDirectionsPrompt` / `parseDirectionsReply` / `resolveDirections`:\n * the optional AI lane (plain chat, strict JSON), best-effort with a\n * timeout and the curated set as the fallback.\n *\n * Pure: no React, no browser globals - runs under `node --test`. The server\n * re-validates with the same rules (page-creator `webbuilderDesignDirection.ts`);\n * keep the font allow-list and the enums in step with it.\n */\n\nexport const PALETTE_ROLES = ['background', 'surface', 'text', 'muted', 'primary', 'accent'] as const;\nexport type PaletteRole = (typeof PALETTE_ROLES)[number];\n/** `muted` is optional (5-6 colors); the others are required. */\nexport type DesignPalette = Record<Exclude<PaletteRole, 'muted'>, string> & { muted?: string };\n\nexport const RADIUS_STYLES = ['none', 'sm', 'md', 'lg', 'full'] as const;\nexport type RadiusStyle = (typeof RADIUS_STYLES)[number];\nexport const DENSITY_STYLES = ['compact', 'comfortable', 'airy'] as const;\nexport type DensityStyle = (typeof DENSITY_STYLES)[number];\nexport const IMAGERY_STYLES = ['photo', 'illustration', 'gradient', 'geometric', 'texture', 'minimal'] as const;\nexport type ImageryStyle = (typeof IMAGERY_STYLES)[number];\n\nexport interface DesignDirection {\n /** Slug, e.g. `golden-hour`. */\n id: string;\n name: string;\n /** One line: how the site should feel. */\n mood: string;\n palette: DesignPalette;\n fonts: { heading: string; body: string };\n radius: RadiusStyle;\n density: DensityStyle;\n imagery: ImageryStyle;\n}\n\nexport const MAX_NAME_CHARS = 40;\nexport const MAX_MOOD_CHARS = 160;\n/** WCAG 2.x AA for normal text. */\nexport const AA_CONTRAST = 4.5;\n\n// ---------------------------------------------------------------- fonts\n\nexport type FontCategory = 'sans-serif' | 'serif' | 'display' | 'monospace' | 'handwriting';\ninterface FontSpec {\n category: FontCategory;\n /** False: the family has one weight (400); the css2 API refuses a `wght@…;700` request for it. */\n bold: boolean;\n}\n\n/** Common Google Fonts the agent may use. Keys are the exact family names. */\nexport const GOOGLE_FONTS: Readonly<Record<string, FontSpec>> = {\n Inter: { category: 'sans-serif', bold: true },\n Roboto: { category: 'sans-serif', bold: true },\n 'Open Sans': { category: 'sans-serif', bold: true },\n Lato: { category: 'sans-serif', bold: true },\n Montserrat: { category: 'sans-serif', bold: true },\n Poppins: { category: 'sans-serif', bold: true },\n Nunito: { category: 'sans-serif', bold: true },\n 'Nunito Sans': { category: 'sans-serif', bold: true },\n Raleway: { category: 'sans-serif', bold: true },\n 'Work Sans': { category: 'sans-serif', bold: true },\n Rubik: { category: 'sans-serif', bold: true },\n Karla: { category: 'sans-serif', bold: true },\n Mulish: { category: 'sans-serif', bold: true },\n Manrope: { category: 'sans-serif', bold: true },\n 'DM Sans': { category: 'sans-serif', bold: true },\n 'Plus Jakarta Sans': { category: 'sans-serif', bold: true },\n Outfit: { category: 'sans-serif', bold: true },\n Sora: { category: 'sans-serif', bold: true },\n 'Space Grotesk': { category: 'sans-serif', bold: true },\n 'IBM Plex Sans': { category: 'sans-serif', bold: true },\n Archivo: { category: 'sans-serif', bold: true },\n 'Libre Franklin': { category: 'sans-serif', bold: true },\n 'Source Sans 3': { category: 'sans-serif', bold: true },\n Figtree: { category: 'sans-serif', bold: true },\n Lexend: { category: 'sans-serif', bold: true },\n Urbanist: { category: 'sans-serif', bold: true },\n Quicksand: { category: 'sans-serif', bold: true },\n Barlow: { category: 'sans-serif', bold: true },\n 'Josefin Sans': { category: 'sans-serif', bold: true },\n Syne: { category: 'sans-serif', bold: true },\n Fredoka: { category: 'sans-serif', bold: true },\n Oswald: { category: 'sans-serif', bold: true },\n 'Archivo Black': { category: 'display', bold: false },\n 'Bebas Neue': { category: 'display', bold: false },\n Anton: { category: 'display', bold: false },\n 'Abril Fatface': { category: 'display', bold: false },\n Righteous: { category: 'display', bold: false },\n 'DM Serif Display': { category: 'serif', bold: false },\n 'Playfair Display': { category: 'serif', bold: true },\n Lora: { category: 'serif', bold: true },\n Merriweather: { category: 'serif', bold: true },\n 'Libre Baskerville': { category: 'serif', bold: true },\n 'Cormorant Garamond': { category: 'serif', bold: true },\n 'EB Garamond': { category: 'serif', bold: true },\n Fraunces: { category: 'serif', bold: true },\n 'Source Serif 4': { category: 'serif', bold: true },\n 'Crimson Pro': { category: 'serif', bold: true },\n 'IBM Plex Mono': { category: 'monospace', bold: true },\n 'JetBrains Mono': { category: 'monospace', bold: true },\n 'Space Mono': { category: 'monospace', bold: true },\n Pacifico: { category: 'handwriting', bold: false },\n Caveat: { category: 'handwriting', bold: true },\n};\n\nconst FONT_BY_LOWER = new Map(Object.keys(GOOGLE_FONTS).map((n) => [n.toLowerCase(), n]));\n\n/** The allow-listed family name (canonical case), or null. */\nexport function canonicalFont(name: unknown): string | null {\n if (typeof name !== 'string') return null;\n const key = name.replace(/[\"']/g, '').replace(/\\s+/g, ' ').trim().toLowerCase();\n return FONT_BY_LOWER.get(key) ?? null;\n}\n\n/** A CSS `font-family` value with a generic fallback: `'Playfair Display', Georgia, serif`. */\nexport function fontStack(name: string): string {\n const spec = GOOGLE_FONTS[name];\n const fallback =\n spec?.category === 'serif'\n ? 'Georgia, serif'\n : spec?.category === 'monospace'\n ? 'ui-monospace, monospace'\n : spec?.category === 'handwriting'\n ? 'cursive'\n : 'system-ui, sans-serif';\n return `'${name}', ${fallback}`;\n}\n\n/** One css2 URL for the families (allow-listed only, de-duplicated, sorted so the URL is stable). */\nexport function googleFontsHref(families: Iterable<string>): string | null {\n const names = [...new Set([...families].map(canonicalFont).filter((n): n is string => Boolean(n)))].sort();\n if (!names.length) return null;\n const params = names.map((n) => `family=${n.replace(/ /g, '+')}${GOOGLE_FONTS[n].bold ? ':wght@400;700' : ''}`);\n return `https://fonts.googleapis.com/css2?${params.join('&')}&display=swap`;\n}\n\n// ---------------------------------------------------------------- colour + contrast\n\nconst HEX_RE = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i;\n\n/** `#abc` / `ABCDEF` -> `#aabbcc` (lower case), or null. */\nexport function normalizeHex(v: unknown): string | null {\n if (typeof v !== 'string') return null;\n const m = HEX_RE.exec(v.trim());\n if (!m) return null;\n const h = m[1].length === 3 ? m[1].replace(/./g, (c) => c + c) : m[1];\n return `#${h.toLowerCase()}`;\n}\n\nfunction rgb(hex: string): [number, number, number] {\n const n = parseInt(hex.slice(1), 16);\n return [(n >> 16) & 255, (n >> 8) & 255, n & 255];\n}\n\nfunction toHex([r, g, b]: [number, number, number]): string {\n return `#${[r, g, b]\n .map((c) =>\n Math.round(Math.min(255, Math.max(0, c)))\n .toString(16)\n .padStart(2, '0'),\n )\n .join('')}`;\n}\n\n/** WCAG relative luminance of a normalized hex colour. */\nexport function relativeLuminance(hex: string): number {\n const [r, g, b] = rgb(hex).map((c) => {\n const s = c / 255;\n return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;\n });\n return 0.2126 * r + 0.7152 * g + 0.0722 * b;\n}\n\n/** WCAG contrast ratio (1-21) between two normalized hex colours. */\nexport function contrastRatio(a: string, b: string): number {\n const la = relativeLuminance(a);\n const lb = relativeLuminance(b);\n return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);\n}\n\n/**\n * `text` when it already reaches `min` on `bg`; else `text` mixed step by step\n * toward black (light backgrounds) or white (dark ones) until it does. Keeps\n * the hue as long as possible; black / white is the last resort.\n */\nexport function ensureContrast(text: string, bg: string, min = AA_CONTRAST): string {\n if (contrastRatio(text, bg) >= min) return text;\n const towardBlack = contrastRatio('#000000', bg) >= contrastRatio('#ffffff', bg);\n const target: [number, number, number] = towardBlack ? [0, 0, 0] : [255, 255, 255];\n const [r, g, b] = rgb(text);\n for (let t = 0.05; t <= 1.0001; t += 0.05) {\n const mixed = toHex([r + (target[0] - r) * t, g + (target[1] - g) * t, b + (target[2] - b) * t]);\n if (contrastRatio(mixed, bg) >= min) return mixed;\n }\n return towardBlack ? '#000000' : '#ffffff';\n}\n\n/**\n * `color` when it reaches `min` on EVERY background (page and surface); else\n * mixed toward black or white (picked by the first background) until it does.\n * When no mix works, the extreme with the best worst-case contrast.\n */\nexport function ensureContrastOn(color: string, backgrounds: string[], min = AA_CONTRAST): string {\n const worst = (c: string) => Math.min(...backgrounds.map((bg) => contrastRatio(c, bg)));\n if (worst(color) >= min) return color;\n const first = backgrounds[0];\n const towardBlack = contrastRatio('#000000', first) >= contrastRatio('#ffffff', first);\n const target = towardBlack ? [0, 0, 0] : [255, 255, 255];\n const src = rgb(color);\n for (let t = 0.05; t <= 1.0001; t += 0.05) {\n const mixed = toHex(src.map((c, i) => c + (target[i] - c) * t) as [number, number, number]);\n if (worst(mixed) >= min) return mixed;\n }\n return worst('#000000') >= worst('#ffffff') ? '#000000' : '#ffffff';\n}\n\n/**\n * Button label colour on `primary`: black or white, whichever has more\n * contrast (one of them always reaches at least 4.58:1, so labels pass AA).\n */\nexport function onColor(bg: string): string {\n return contrastRatio('#ffffff', bg) >= contrastRatio('#000000', bg) ? '#ffffff' : '#000000';\n}\n\n// ---------------------------------------------------------------- validation\n\nexport type DirectionValidation =\n | {\n ok: true;\n direction: DesignDirection;\n /** What was fixed (e.g. text colour for contrast). */ adjusted: string[];\n }\n | { ok: false; errors: string[] };\n\nconst isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);\n\n/** Identical to the server's `cleanLine` (webbuilderDesignDirection.ts), so the card and the agent show the same name. */\nexport function cleanLine(v: unknown, max: number): string {\n if (typeof v !== 'string') return '';\n const t = v\n .slice(0, max * 4)\n .replace(/[\\u0000-\\u001f\\u007f]+/g, ' ')\n .replace(/[<>`{}#]/g, '')\n .replace(/\\s+/g, ' ')\n .trim();\n return t.length > max ? t.slice(0, max).trim() : t;\n}\n\nexport function slugify(v: string): string {\n return v\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 40);\n}\n\nconst oneOf = <T extends string>(list: readonly T[], v: unknown): T | null =>\n typeof v === 'string' && (list as readonly string[]).includes(v.trim().toLowerCase())\n ? (v.trim().toLowerCase() as T)\n : null;\n\n/**\n * Validate (and normalise) a direction from any source: the curated set, the\n * AI lane or stored settings. Text and muted colours that miss AA on the\n * background are adjusted (reported in `adjusted`); anything else invalid is\n * an error.\n */\nexport function validateDirection(raw: unknown): DirectionValidation {\n if (!isObj(raw)) return { ok: false, errors: ['direction must be an object'] };\n const errors: string[] = [];\n const adjusted: string[] = [];\n\n const name = cleanLine(raw.name, MAX_NAME_CHARS);\n if (!name) errors.push('name is required');\n const mood = cleanLine(raw.mood, MAX_MOOD_CHARS);\n if (!mood) errors.push('mood is required');\n const id = slugify(typeof raw.id === 'string' && raw.id.trim() ? raw.id : name) || 'direction';\n\n const palette: Partial<Record<PaletteRole, string>> = {};\n if (!isObj(raw.palette)) errors.push('palette must be an object');\n else {\n for (const role of PALETTE_ROLES) {\n const v = raw.palette[role];\n if (role === 'muted' && (v === undefined || v === null || v === '')) continue;\n const hex = normalizeHex(v);\n if (!hex) errors.push(`palette.${role} must be a hex colour`);\n else palette[role] = hex;\n }\n }\n\n const fonts = isObj(raw.fonts) ? raw.fonts : {};\n const heading = canonicalFont(fonts.heading);\n const body = canonicalFont(fonts.body);\n if (!heading) errors.push('fonts.heading must be one of the allowed Google Fonts');\n if (!body) errors.push('fonts.body must be one of the allowed Google Fonts');\n\n const radius = oneOf(RADIUS_STYLES, raw.radius);\n if (!radius) errors.push(`radius must be one of ${RADIUS_STYLES.join(', ')}`);\n const density = oneOf(DENSITY_STYLES, raw.density);\n if (!density) errors.push(`density must be one of ${DENSITY_STYLES.join(', ')}`);\n const imagery = oneOf(IMAGERY_STYLES, raw.imagery);\n if (!imagery) errors.push(`imagery must be one of ${IMAGERY_STYLES.join(', ')}`);\n\n if (errors.length) return { ok: false, errors };\n\n // Text and muted text sit on the page AND on cards: AA on both. Links use the text colour plus\n // an underline (primary is for button fills, labelled with `onColor`), so primary needs no check.\n const grounds = [palette.background!, palette.surface!];\n const text = ensureContrastOn(palette.text!, grounds);\n if (text !== palette.text) adjusted.push(`text ${palette.text} -> ${text} (contrast on background / surface)`);\n palette.text = text;\n if (palette.muted) {\n const muted = ensureContrastOn(palette.muted, grounds);\n if (muted !== palette.muted)\n adjusted.push(`muted ${palette.muted} -> ${muted} (contrast on background / surface)`);\n palette.muted = muted;\n }\n\n return {\n ok: true,\n adjusted,\n direction: {\n id,\n name,\n mood,\n palette: palette as DesignPalette,\n fonts: { heading: heading!, body: body! },\n radius: radius!,\n density: density!,\n imagery: imagery!,\n },\n };\n}\n\n/** The validated direction, or null. */\nexport function toDesignDirection(raw: unknown): DesignDirection | null {\n const r = validateDirection(raw);\n return r.ok ? r.direction : null;\n}\n\n/** `props.designDirection` for the build turn ({} when there is none). */\nexport function designDirectionTurnProps(d: DesignDirection | null | undefined): { designDirection?: DesignDirection } {\n const v = d ? toDesignDirection(d) : null;\n return v ? { designDirection: v } : {};\n}\n\nexport interface TurnDirectionPlan {\n /** Spread into the post props. `designDirection: null` = skipped on a new build (no settings fallback). */\n props: { designDirection?: DesignDirection | null };\n /** Write to the project settings after the turn is delivered (`null` clears); undefined = leave them. */\n save?: DesignDirection | null;\n}\n\n/**\n * What a connector turn sends and saves (the server falls back to settings on EDIT turns only):\n * - a new build that went through the picker (`designDirection` key present): the pick, saved; or an\n * explicit `null` when skipped / styles off, clearing an older pick in this channel's settings;\n * - an edit: the project's saved direction, so edits keep the same tokens;\n * - anything else: nothing.\n */\nexport function planTurnDirection(input: {\n isEdit: boolean;\n opts?: { designDirection?: DesignDirection | null } | null;\n saved?: DesignDirection | null;\n /** The channel was minted for this send (nothing saved to clear). */\n minted?: boolean;\n}): TurnDirectionPlan {\n const opts = input.opts;\n if (!input.isEdit && opts && 'designDirection' in opts) {\n const picked = opts.designDirection ? toDesignDirection(opts.designDirection) : null;\n if (picked) return { props: { designDirection: picked }, save: picked };\n return { props: { designDirection: null }, ...(!input.minted && input.saved ? { save: null } : {}) };\n }\n if (input.isEdit) return { props: designDirectionTurnProps(input.saved) };\n return { props: {} };\n}\n\n// ---------------------------------------------------------------- curated fallback set\n\nexport interface CuratedDirection extends DesignDirection {\n /** Brief keywords that make this direction a good fit. */\n keywords: string[];\n}\n\nexport const CURATED_DIRECTIONS: readonly CuratedDirection[] = [\n {\n id: 'quiet-minimal',\n name: 'Quiet Minimal',\n mood: 'Calm, precise and spacious - lots of white space and confident type.',\n palette: {\n background: '#ffffff',\n surface: '#f5f5f4',\n text: '#1c1917',\n muted: '#57534e',\n primary: '#1c1917',\n accent: '#a8a29e',\n },\n fonts: { heading: 'Manrope', body: 'Inter' },\n radius: 'sm',\n density: 'airy',\n imagery: 'minimal',\n keywords: [\n 'minimal',\n 'clean',\n 'simple',\n 'portfolio',\n 'architect',\n 'architecture',\n 'studio',\n 'photographer',\n 'photography',\n 'designer',\n 'resume',\n 'cv',\n ],\n },\n {\n id: 'golden-hour',\n name: 'Golden Hour',\n mood: 'Warm and welcoming, like late-afternoon light in a neighbourhood cafe.',\n palette: {\n background: '#fdf6ec',\n surface: '#f6e7d3',\n text: '#3b2a1e',\n muted: '#6b5444',\n primary: '#c2410c',\n accent: '#e9a23b',\n },\n fonts: { heading: 'Fraunces', body: 'Nunito Sans' },\n radius: 'lg',\n density: 'comfortable',\n imagery: 'photo',\n keywords: [\n 'bakery',\n 'cafe',\n 'coffee',\n 'restaurant',\n 'food',\n 'recipe',\n 'recipes',\n 'kitchen',\n 'family',\n 'home',\n 'wedding',\n 'bnb',\n 'catering',\n 'warm',\n ],\n },\n {\n id: 'loud-and-clear',\n name: 'Loud & Clear',\n mood: 'High-energy and bold - big type, hard edges, strong contrast.',\n palette: {\n background: '#0a0a0a',\n surface: '#1a1a1a',\n text: '#fafafa',\n muted: '#a3a3a3',\n primary: '#facc15',\n accent: '#ef4444',\n },\n fonts: { heading: 'Archivo Black', body: 'Archivo' },\n radius: 'none',\n density: 'compact',\n imagery: 'geometric',\n keywords: [\n 'fitness',\n 'gym',\n 'sport',\n 'sports',\n 'event',\n 'festival',\n 'music',\n 'band',\n 'launch',\n 'streetwear',\n 'bold',\n 'conference',\n 'marathon',\n ],\n },\n {\n id: 'broadsheet',\n name: 'Broadsheet',\n mood: 'Editorial and literate - classic serif headlines with a newspaper rhythm.',\n palette: {\n background: '#fbfaf7',\n surface: '#f0ede6',\n text: '#111111',\n muted: '#555048',\n primary: '#9f1239',\n accent: '#1e3a8a',\n },\n fonts: { heading: 'Playfair Display', body: 'Libre Franklin' },\n radius: 'none',\n density: 'comfortable',\n imagery: 'photo',\n keywords: [\n 'blog',\n 'magazine',\n 'news',\n 'journal',\n 'writer',\n 'writing',\n 'book',\n 'books',\n 'author',\n 'publication',\n 'newsletter',\n 'podcast',\n 'editorial',\n 'essay',\n ],\n },\n {\n id: 'candy-pop',\n name: 'Candy Pop',\n mood: 'Playful and friendly - round shapes, bright color and a wink of fun.',\n palette: {\n background: '#fff7fb',\n surface: '#ffe4f1',\n text: '#2e1065',\n muted: '#5b4a7a',\n primary: '#db2777',\n accent: '#22c55e',\n },\n fonts: { heading: 'Fredoka', body: 'Nunito' },\n radius: 'full',\n density: 'comfortable',\n imagery: 'illustration',\n keywords: [\n 'kids',\n 'children',\n 'child',\n 'game',\n 'games',\n 'toy',\n 'toys',\n 'party',\n 'pet',\n 'pets',\n 'school',\n 'fun',\n 'candy',\n 'ice',\n 'playful',\n 'daycare',\n ],\n },\n {\n id: 'noir-gold',\n name: 'Noir & Gold',\n mood: 'Luxurious and refined - deep darks, gold accents and elegant serifs.',\n palette: {\n background: '#0f0e0c',\n surface: '#1c1a16',\n text: '#f5f0e6',\n muted: '#b5ab98',\n primary: '#c9a227',\n accent: '#8c6d1f',\n },\n fonts: { heading: 'Cormorant Garamond', body: 'Montserrat' },\n radius: 'none',\n density: 'airy',\n imagery: 'photo',\n keywords: [\n 'luxury',\n 'jewelry',\n 'jewellery',\n 'fashion',\n 'hotel',\n 'wine',\n 'watch',\n 'watches',\n 'premium',\n 'boutique',\n 'estate',\n 'perfume',\n 'cocktail',\n 'elegant',\n ],\n },\n {\n id: 'terminal-grid',\n name: 'Terminal Grid',\n mood: 'Technical and sharp - dark UI, crisp grids and a hint of neon.',\n palette: {\n background: '#0b1020',\n surface: '#131a2e',\n text: '#e2e8f0',\n muted: '#94a3b8',\n primary: '#22d3ee',\n accent: '#a78bfa',\n },\n fonts: { heading: 'Space Grotesk', body: 'IBM Plex Sans' },\n radius: 'md',\n density: 'compact',\n imagery: 'gradient',\n keywords: [\n 'saas',\n 'ai',\n 'developer',\n 'developers',\n 'api',\n 'crypto',\n 'dashboard',\n 'tech',\n 'software',\n 'analytics',\n 'data',\n 'devtools',\n 'cloud',\n 'startup',\n ],\n },\n {\n id: 'field-and-fern',\n name: 'Field & Fern',\n mood: 'Organic and grounded - earthy greens, natural textures, unhurried.',\n palette: {\n background: '#f4f1ea',\n surface: '#e6e2d3',\n text: '#23301f',\n muted: '#4f5b48',\n primary: '#3f6212',\n accent: '#b45309',\n },\n fonts: { heading: 'DM Serif Display', body: 'Karla' },\n radius: 'lg',\n density: 'airy',\n imagery: 'texture',\n keywords: [\n 'garden',\n 'gardening',\n 'farm',\n 'organic',\n 'eco',\n 'plant',\n 'plants',\n 'nature',\n 'sustainable',\n 'outdoor',\n 'florist',\n 'flowers',\n 'hiking',\n 'camping',\n ],\n },\n {\n id: 'clear-blue',\n name: 'Clear Blue',\n mood: 'Trustworthy and professional - clean layout, confident blue, no noise.',\n palette: {\n background: '#ffffff',\n surface: '#f1f5f9',\n text: '#0f172a',\n muted: '#475569',\n primary: '#2563eb',\n accent: '#0ea5e9',\n },\n fonts: { heading: 'Plus Jakarta Sans', body: 'Inter' },\n radius: 'md',\n density: 'comfortable',\n imagery: 'photo',\n keywords: [\n 'consulting',\n 'consultant',\n 'finance',\n 'law',\n 'lawyer',\n 'legal',\n 'clinic',\n 'medical',\n 'dentist',\n 'insurance',\n 'bank',\n 'accounting',\n 'business',\n 'agency',\n 'corporate',\n ],\n },\n {\n id: 'sunset-diner',\n name: 'Sunset Diner',\n mood: 'Retro and characterful - chunky display type and sun-faded color.',\n palette: {\n background: '#fff4e0',\n surface: '#ffe3b3',\n text: '#3d1f0f',\n muted: '#6e4630',\n primary: '#c2410c',\n accent: '#0b7285',\n },\n fonts: { heading: 'Abril Fatface', body: 'Work Sans' },\n radius: 'md',\n density: 'comfortable',\n imagery: 'illustration',\n keywords: [\n 'diner',\n 'retro',\n 'vintage',\n 'barber',\n 'records',\n 'vinyl',\n 'brewery',\n 'beer',\n 'burger',\n 'pizza',\n 'taco',\n 'food truck',\n 'arcade',\n ],\n },\n {\n id: 'soft-sage',\n name: 'Soft Sage',\n mood: 'Calm and restorative - muted sage, gentle serif headings, room to breathe.',\n palette: {\n background: '#f6f8f5',\n surface: '#e7eee6',\n text: '#1f2d27',\n muted: '#4d5f56',\n primary: '#3f6b5c',\n accent: '#d4a373',\n },\n fonts: { heading: 'Lora', body: 'Mulish' },\n radius: 'lg',\n density: 'airy',\n imagery: 'photo',\n keywords: [\n 'wellness',\n 'yoga',\n 'spa',\n 'therapy',\n 'therapist',\n 'meditation',\n 'health',\n 'coach',\n 'coaching',\n 'skincare',\n 'massage',\n 'mindfulness',\n 'calm',\n ],\n },\n {\n id: 'neon-night',\n name: 'Neon Night',\n mood: 'Futuristic and electric - deep night tones lit by violet and pink glows.',\n palette: {\n background: '#09090f',\n surface: '#15152a',\n text: '#f4f4ff',\n muted: '#a1a1c2',\n primary: '#8b5cf6',\n accent: '#ec4899',\n },\n fonts: { heading: 'Sora', body: 'Outfit' },\n radius: 'lg',\n density: 'comfortable',\n imagery: 'gradient',\n keywords: [\n 'gaming',\n 'gamer',\n 'nightclub',\n 'club',\n 'esports',\n 'nft',\n 'web3',\n 'dj',\n 'synth',\n 'futuristic',\n 'nightlife',\n 'vr',\n ],\n },\n];\n\n/** Order used when the brief gives no hints: as different from each other as possible. */\nconst DEFAULT_ORDER = [\n 'quiet-minimal',\n 'golden-hour',\n 'terminal-grid',\n 'broadsheet',\n 'candy-pop',\n 'noir-gold',\n 'field-and-fern',\n 'loud-and-clear',\n 'clear-blue',\n 'soft-sage',\n 'neon-night',\n 'sunset-diner',\n];\n\nfunction keywordScore(d: CuratedDirection, brief: string): number {\n let score = 0;\n for (const k of d.keywords) {\n const re = new RegExp(`\\\\b${k.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}s?\\\\b`, 'i');\n if (re.test(brief)) score += 1;\n }\n return score;\n}\n\n/** Every curated direction, best fit for the brief first (ties keep the diverse default order). */\nexport function rankDirectionsForBrief(brief: string | null | undefined): CuratedDirection[] {\n const text = String(brief ?? '');\n const order = new Map(DEFAULT_ORDER.map((id, i) => [id, i]));\n return [...CURATED_DIRECTIONS]\n .map((d) => ({ d, score: keywordScore(d, text) }))\n .sort((a, b) => b.score - a.score || (order.get(a.d.id) ?? 99) - (order.get(b.d.id) ?? 99))\n .map((x) => x.d);\n}\n\n/** Strip the curated-only `keywords`. */\nexport function asDirection(d: DesignDirection): DesignDirection {\n const { id, name, mood, palette, fonts, radius, density, imagery } = d;\n return { id, name, mood, palette: { ...palette }, fonts: { ...fonts }, radius, density, imagery };\n}\n\n/**\n * Three distinct curated directions for the brief (keyword heuristic). `exclude`\n * (ids already shown) gives the \"Shuffle\" set; when too few are left, the\n * ranking starts over.\n */\nexport function pickDirectionsForBrief(\n brief: string | null | undefined,\n exclude: Iterable<string> = [],\n): DesignDirection[] {\n const ranked = rankDirectionsForBrief(brief);\n const skip = new Set(exclude);\n const fresh = ranked.filter((d) => !skip.has(d.id));\n const pool = fresh.length >= 3 ? fresh : [...fresh, ...ranked.filter((d) => skip.has(d.id))];\n return pool.slice(0, 3).map(asDirection);\n}\n\n// ---------------------------------------------------------------- AI lane (optional)\n\nexport const DIRECTIONS_SESSION_KEY = 'webbuilder-design-directions';\nexport const DIRECTIONS_TIMEOUT_MS = 12_000;\n\n/** One plain-chat session per build channel (reused across requests), not one per call. */\nexport function directionsSessionKey(channelId: string | null | undefined): string {\n const id = String(channelId ?? '')\n .trim()\n .replace(/[^A-Za-z0-9_-]/g, '')\n .slice(0, 80);\n return id ? `${DIRECTIONS_SESSION_KEY}-${id}` : DIRECTIONS_SESSION_KEY;\n}\n\n/** The strict-JSON prompt sent through the plain-chat lane. */\nexport function buildDirectionsPrompt(brief: string): string {\n return [\n 'You are an art director proposing visual style directions for a website BEFORE it is built.',\n 'Do NOT write code, do NOT build anything, do NOT ask questions, do NOT call any tool or connector.',\n 'Propose exactly 3 clearly DIFFERENT directions that fit the request below.',\n 'Reply with ONLY one JSON object, no prose and no code fence, in exactly this shape:',\n '{\"directions\":[{\"name\":\"2-3 words\",\"mood\":\"one sentence, max 140 characters\",' +\n '\"palette\":{\"background\":\"#rrggbb\",\"surface\":\"#rrggbb\",\"text\":\"#rrggbb\",\"muted\":\"#rrggbb\",\"primary\":\"#rrggbb\",\"accent\":\"#rrggbb\"},' +\n '\"fonts\":{\"heading\":\"<font>\",\"body\":\"<font>\"},\"radius\":\"<radius>\",\"density\":\"<density>\",\"imagery\":\"<imagery>\"}]}',\n `Fonts must be exact names from this list: ${Object.keys(GOOGLE_FONTS).join(', ')}.`,\n `radius: one of ${RADIUS_STYLES.join(', ')}. density: one of ${DENSITY_STYLES.join(', ')}. imagery: one of ${IMAGERY_STYLES.join(', ')}.`,\n 'The text and muted colours must have at least 4.5:1 contrast on both the background and the surface. Links use the text colour with an underline; primary is a button fill.',\n '',\n `Website request:\\n${String(brief ?? '')\n .trim()\n .slice(0, 2000)}`,\n ].join('\\n');\n}\n\n/** The validated directions in an AI reply (fenced or not, array or `{ directions }`); [] when none. */\nexport function parseDirectionsReply(reply: string | null | undefined): DesignDirection[] {\n let t = String(reply ?? '').trim();\n const fenced = /```(?:json)?\\s*\\n?([\\s\\S]*?)```/i.exec(t);\n if (fenced) t = fenced[1].trim();\n const start = t.search(/[[{]/);\n if (start < 0) return [];\n const end = Math.max(t.lastIndexOf('}'), t.lastIndexOf(']'));\n if (end <= start) return [];\n let data: unknown;\n try {\n data = JSON.parse(t.slice(start, end + 1));\n } catch {\n return [];\n }\n const list = Array.isArray(data) ? data : isObj(data) && Array.isArray(data.directions) ? data.directions : [];\n const out: DesignDirection[] = [];\n const seen = new Set<string>();\n for (const item of list.slice(0, 6)) {\n const d = toDesignDirection(item);\n if (!d || seen.has(d.name.toLowerCase())) continue;\n seen.add(d.name.toLowerCase());\n // A model-made id could collide with a curated one; keep ids unique.\n out.push({ ...d, id: `ai-${d.id}`.slice(0, 40) });\n }\n return out.slice(0, 3);\n}\n\nexport interface ResolvedDirections {\n directions: DesignDirection[];\n source: 'ai' | 'curated';\n}\n\n/**\n * The AI directions for the brief, topped up from the curated set; the curated\n * three on any failure, an empty reply or after `timeoutMs`. Never throws.\n */\nexport async function resolveDirections(\n brief: string,\n suggest: ((prompt: string, opts: { signal: AbortSignal }) => Promise<string>) | null | undefined,\n opts: { timeoutMs?: number; signal?: AbortSignal } = {},\n): Promise<ResolvedDirections> {\n const curated = (): ResolvedDirections => ({ directions: pickDirectionsForBrief(brief), source: 'curated' });\n if (!suggest) return curated();\n const ctrl = new AbortController();\n const onAbort = () => ctrl.abort();\n opts.signal?.addEventListener('abort', onAbort, { once: true });\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const timeout = new Promise<null>((resolve) => {\n timer = setTimeout(() => {\n ctrl.abort();\n resolve(null);\n }, opts.timeoutMs ?? DIRECTIONS_TIMEOUT_MS);\n });\n const reply = await Promise.race([\n suggest(buildDirectionsPrompt(brief), { signal: ctrl.signal }).catch(() => null),\n timeout,\n ]);\n const ai = reply ? parseDirectionsReply(reply) : [];\n if (!ai.length) return curated();\n const names = new Set(ai.map((d) => d.name.toLowerCase()));\n const fill = rankDirectionsForBrief(brief)\n .filter((d) => !names.has(d.name.toLowerCase()))\n .slice(0, 3 - ai.length)\n .map(asDirection);\n return { directions: [...ai, ...fill], source: 'ai' };\n } catch {\n return curated();\n } finally {\n if (timer) clearTimeout(timer);\n opts.signal?.removeEventListener('abort', onAbort);\n }\n}\n\n// ---------------------------------------------------------------- picker state\n\n/** The open style-direction picker for the next new build. */\nexport interface DirectionPickerState {\n brief: string;\n directions: DesignDirection[];\n source: 'ai' | 'curated';\n /** The AI lane is still working. */\n loading: boolean;\n /** The user hovered, focused or clicked the cards: never swap them under the cursor. */\n touched?: boolean;\n /** AI directions that arrived after the user touched the cards (\"Tailored styles ready\"). */\n tailored?: DesignDirection[];\n}\n\n/**\n * The AI lane answered: replace the curated cards only while the user hasn't\n * touched them; otherwise park the result behind the \"Tailored styles ready\" chip.\n */\nexport function withTailoredDirections(state: DirectionPickerState, result: ResolvedDirections): DirectionPickerState {\n const next: DirectionPickerState = { ...state, loading: false };\n if (result.source !== 'ai' || !result.directions.length) return next;\n if (state.touched) return { ...next, tailored: result.directions };\n return { ...next, directions: result.directions, source: 'ai', tailored: undefined };\n}\n\n/** \"Tailored styles ready\" clicked: show the parked AI directions. */\nexport function showTailoredDirections(state: DirectionPickerState): DirectionPickerState {\n if (!state.tailored?.length) return state;\n return { ...state, directions: state.tailored, source: 'ai', tailored: undefined };\n}\n\n// ---------------------------------------------------------------- when to offer\n\n/**\n * Directions are offered only before a NEW build: New app, a template remix or\n * \"New from this\" - never an edit of an open build, a plain chat turn, or a\n * turn that already carries a plan.\n */\nexport function isNewBuildTurn(\n opts:\n | {\n forceNew?: boolean;\n template?: unknown;\n editTarget?: unknown;\n referenceArtifact?: unknown;\n plan?: string;\n }\n | null\n | undefined,\n): boolean {\n if (!opts || opts.editTarget || opts.plan) return false;\n return Boolean(opts.forceNew || opts.template || opts.referenceArtifact);\n}\n\n/** Pixel radius used for the card preview (and documented to the agent). */\nexport const RADIUS_PX: Readonly<Record<RadiusStyle, number>> = { none: 0, sm: 6, md: 12, lg: 20, full: 9999 };\n"],"names":[],"mappings":"AAqBO,MAAM,gBAAgB,CAAC,YAAA,EAAc,WAAW,MAAQ,EAAA,OAAA,EAAS,WAAW,QAAQ;AAMpF,MAAM,gBAAgB,CAAC,MAAA,EAAQ,IAAM,EAAA,IAAA,EAAM,MAAM,MAAM;AAEvD,MAAM,cAAiB,GAAA,CAAC,SAAW,EAAA,aAAA,EAAe,MAAM;AAExD,MAAM,iBAAiB,CAAC,OAAA,EAAS,gBAAgB,UAAY,EAAA,WAAA,EAAa,WAAW,SAAS;AAiB9F,MAAM,cAAiB,GAAA;AACvB,MAAM,cAAiB,GAAA;AAEvB,MAAM,WAAc,GAAA;AAYpB,MAAM,YAAmD,GAAA;AAAA,EAC9D,KAAO,EAAA;AAAA,IACL,QAAU,EAAA,YAAA;AAAA,IACV,IAAM,EAAA;AAAA,GACR;AAAA,EACA,MAAQ,EAAA;AAAA,IACN,QAAU,EAAA,YAAA;AAAA,IACV,IAAM,EAAA;AAAA,GACR;AAAA,EACA,WAAa,EAAA;AAAA,IACX,QAAU,EAAA,YAAA;AAAA,IACV,IAAM,EAAA;AAAA,GACR;AAAA,EACA,IAAM,EAAA;AAAA,IACJ,QAAU,EAAA,YAAA;AAAA,IACV,IAAM,EAAA;AAAA,GACR;AAAA,EACA,UAAY,EAAA;AAAA,IACV,QAAU,EAAA,YAAA;AAAA,IACV,IAAM,EAAA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AAA,EAAO,OAAO,CAAA;AACpD,EAAI,IAAA,IAAA,KAAS,OAAQ,CAAA,IAAA,EAAe,QAAA,CAAA,IAAA,CAAK,QAAQ,OAAQ,CAAA,IAAI,CAAO,IAAA,EAAA,IAAI,CAAqC,mCAAA,CAAA,CAAA;AAC7G,EAAA,OAAA,CAAQ,IAAO,GAAA,IAAA;AACf,EAAA,IAAI,QAAQ,KAAO,EAAA;AACjB,IAAA,MAAM,KAAQ,GAAA,gBAAA,CAAiB,OAAQ,CAAA,KAAA,EAAO,OAAO,CAAA;AACrD,IAAI,IAAA,KAAA,KAAU,OAAQ,CAAA,KAAA,EAAgB,QAAA,CAAA,IAAA,CAAK,SAAS,OAAQ,CAAA,KAAK,CAAO,IAAA,EAAA,KAAK,CAAqC,mCAAA,CAAA,CAAA;AAClH,IAAA,OAAA,CAAQ,KAAQ,GAAA,KAAA;AAAA;AAElB,EAAO,OAAA;AAAA,IACL,EAAI,EAAA,IAAA;AAAA,IACJ,QAAA;AAAA,IACA,SAAW,EAAA;AAAA,MACT,EAAA;AAAA,MACA,IAAA;AAAA,MACA,IAAA;AAAA,MACA,OAAA;AAAA,MACA,KAAO,EAAA;AAAA,QACL,OAAA;AAAA,QACA;AAAA,OACF;AAAA,MACA,MAAA;AAAA,MACA,OAAA;AAAA,MACA;AAAA;AACF,GACF;AACF;AAGO,SAAS,kBAAkB,GAAsC,EAAA;AACtE,EAAM,MAAA,CAAA,GAAI,kBAAkB,GAAG,CAAA;AAC/B,EAAO,OAAA,CAAA,CAAE,EAAK,GAAA,CAAA,CAAE,SAAY,GAAA,IAAA;AAC9B"}
@@ -1 +1 @@
1
- {"version":3,"file":"versions.js","sources":["../../../../../src/features/webbuilder/web/history/versions.ts"],"sourcesContent":["/**\n * W17: version history, restore and bookmarks (spec Phase 3-4 §1).\n *\n * The connector actions WEBBUILDER_LIST_VERSIONS / RESTORE_VERSION /\n * BOOKMARK_VERSION may not exist on a hosted agent yet. Until they do, the\n * surface falls back to WEBBUILDER_RUN_COMMAND with the git scripts built\n * here. Everything is pure (no connector, no React) so it is unit-tested:\n * - every sha is validated strictly (hex, 7-40 chars) before it reaches a shell;\n * - bookmark names become a safe slug (`bookmark/<slug>` git tags);\n * - commit subjects are single-line and single-quoted.\n *\n * Restore is always FORWARD: the files of the old version become a new commit\n * \"Restore to <short>: <message>\". History is never rewritten.\n *\n * Dirty tree (decision): a restore never refuses a dirty tree and never loses\n * work. Uncommitted changes (hand edits still waiting for their debounced\n * commit) are first committed as \"Manual edits: saved before restore\", so they\n * stay one click away in the history. `.env*`, node_modules and build output\n * are never staged. Refusing would only push the user into a dead end, because\n * the surface itself produces those uncommitted edits.\n */\n\nexport const DEFAULT_VERSION_LIMIT = 50;\nexport const MAX_VERSION_LIMIT = 200;\n/** RUN_COMMAND stdout is capped (~12 KB) - the git-log fallback asks for fewer rows. */\nexport const FALLBACK_VERSION_LIMIT = 40;\n\nexport interface WebbuilderVersion {\n sha: string;\n shortSha: string;\n message: string;\n author?: string;\n /** ISO date. */\n date?: string;\n /** Bookmark slug (the `bookmark/<slug>` tag), when the version has one. */\n bookmark?: string;\n isHead: boolean;\n}\n\nexport interface VersionList {\n versions: WebbuilderVersion[];\n head: string | null;\n dirty: boolean;\n /** Output was cut off, or the clone is shallow: older versions may be missing. */\n partial?: boolean;\n /** The project has no git repository yet (native `isGitRepo: false`). */\n noRepo?: boolean;\n}\n\nconst SHA_RE = /^[0-9a-f]{7,40}$/;\n\n/** Strict sha check: lowercase hex, 7-40 characters. Anything else is refused. */\nexport function isValidSha(value: unknown): value is string {\n return typeof value === 'string' && SHA_RE.test(value);\n}\n\n/** Lower-cased, trimmed sha, or null when it is not a valid sha. */\nexport function normalizeSha(value: unknown): string | null {\n if (typeof value !== 'string') return null;\n const v = value.trim().toLowerCase();\n return isValidSha(v) ? v : null;\n}\n\nexport function clampLimit(limit: unknown, fallback = DEFAULT_VERSION_LIMIT): number {\n const n = typeof limit === 'number' && Number.isFinite(limit) ? Math.floor(limit) : fallback;\n return Math.min(MAX_VERSION_LIMIT, Math.max(1, n));\n}\n\n/** Safe bookmark slug: lowercase `a-z0-9-`, at most 40 chars. Null when nothing is left. */\nexport function bookmarkSlug(name: unknown): string | null {\n if (typeof name !== 'string') return null;\n const slug = name\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 40)\n .replace(/-+$/g, '');\n return slug || null;\n}\n\nexport function shellQuote(value: string): string {\n return `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n\n/** Single-line, printable subject (max 72 chars). */\nexport function oneLineSubject(text: string, max = 72): string {\n const flat = String(text || '')\n .replace(/[\\r\\n\\t]+/g, ' ')\n .replace(/[^\\x20-\\x7E -￿]/g, '')\n .replace(/\\s+/g, ' ')\n .trim();\n return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;\n}\n\n/** \"Restore to <short>: <message>\" - the forward restore's commit subject. */\nexport function restoreCommitMessage(sha: string, message: string): string {\n const short = sha.slice(0, 7);\n return oneLineSubject(`Restore to ${short}: ${oneLineSubject(message, 200) || 'earlier version'}`);\n}\n\nexport const NO_REPO = 'git rev-parse --is-inside-work-tree >/dev/null 2>&1 || { echo \"__GIT=norepo\"; exit 0; }';\nconst IDENTITY =\n 'ID=\"\"; git config user.email >/dev/null 2>&1 || ID=\"-c user.name=Yantra -c user.email=webbuilder@yantra.dev\"';\n/** Stage everything except secrets, dependencies and build output (same rules as the manual-edit commit). */\nconst SAFE_STAGE = [\n \"git add -A -- . ':!.env*' ':!**/.env*' ':!node_modules' ':!**/node_modules' ':!dist' ':!.output' >/dev/null 2>&1 || true\",\n \"git reset -q -- '.env*' '**/.env*' >/dev/null 2>&1 || true\",\n];\n\n/**\n * RUN_COMMAND script: HEAD, dirty flag and the last `limit` commits, one per line:\n * `__V<TAB>sha<TAB>isoDate<TAB>author<TAB>refs<TAB>subject`. Always exits 0.\n */\nexport function buildListVersionsCommand(limit: number = FALLBACK_VERSION_LIMIT): string {\n const n = clampLimit(limit, FALLBACK_VERSION_LIMIT);\n return [\n NO_REPO,\n 'echo \"__GIT=ok\"',\n 'echo \"__HEAD=$(git rev-parse HEAD 2>/dev/null)\"',\n \"if [ -n \\\"$(git status --porcelain -- . ':!.env*' ':!**/.env*' ':!node_modules' ':!**/node_modules' ':!dist' ':!.output' 2>/dev/null | head -n 1)\\\" ]; then echo \\\"__DIRTY=1\\\"; else echo \\\"__DIRTY=0\\\"; fi\",\n `git log -n ${n} --no-color --pretty=format:'__V%x09%H%x09%aI%x09%an%x09%D%x09%s' 2>/dev/null || true`,\n 'echo',\n 'echo \"__END=1\"',\n 'exit 0',\n ].join('\\n');\n}\n\nexport type ParsedVersionList = (VersionList & { ok: true }) | { ok: false; reason: 'norepo' | 'unreadable' };\n\n/** Bookmark slug from a `%D` refs list (\"HEAD -> main, tag: bookmark/launch\"). */\nexport function bookmarkFromRefs(refs: string): string | undefined {\n for (const part of refs.split(',')) {\n const m = /^\\s*tag:\\s*bookmark\\/([a-z0-9-]{1,40})\\s*$/.exec(part);\n if (m) return m[1];\n }\n return undefined;\n}\n\nexport function parseListVersionsOutput(stdout: string, opts?: { truncated?: boolean }): ParsedVersionList {\n const text = String(stdout || '');\n if (/^__GIT=norepo\\s*$/m.test(text)) return { ok: false, reason: 'norepo' };\n if (!/^__GIT=ok\\s*$/m.test(text)) return { ok: false, reason: 'unreadable' };\n const head = normalizeSha(/^__HEAD=(.*)$/m.exec(text)?.[1] ?? '');\n const dirty = /^__DIRTY=1\\s*$/m.test(text);\n const versions: WebbuilderVersion[] = [];\n for (const line of text.split('\\n')) {\n if (!line.startsWith('__V\\t')) continue;\n const [, rawSha, date, author, refs, ...rest] = line.split('\\t');\n const sha = normalizeSha(rawSha);\n if (!sha || sha.length !== 40) continue;\n const bookmark = bookmarkFromRefs(refs ?? '');\n versions.push({\n sha,\n shortSha: sha.slice(0, 7),\n message: rest.join('\\t').replace(/\\r$/, '').trim(),\n ...(author ? { author: author.trim() } : {}),\n ...(date && !Number.isNaN(Date.parse(date)) ? { date: date.trim() } : {}),\n ...(bookmark ? { bookmark } : {}),\n isHead: sha === head,\n });\n }\n const ended = /^__END=1\\s*$/m.test(text);\n return {\n ok: true,\n versions,\n head,\n dirty,\n ...(opts?.truncated || !ended ? { partial: true } : {}),\n };\n}\n\n/**\n * The action's fields. The transport already unwraps `{ data }`; a second\n * `data` layer (older transports) is tolerated.\n */\nexport function actionFields(data: Record<string, unknown> | null | undefined): Record<string, unknown> {\n const rec = data && typeof data === 'object' ? data : {};\n const inner = rec.data;\n if (inner && typeof inner === 'object' && !Array.isArray(inner)) return inner as Record<string, unknown>;\n return rec;\n}\n\n/**\n * The plain sentence of a connector error: `\"<sentence> [CODE]\\nLast output:…\"`\n * -> `\"<sentence>\"`. Falls back when there is nothing readable.\n */\nexport function plainConnectorError(error: unknown, fallback: string): string {\n const first = String(error ?? '')\n .split('\\n')[0]\n .replace(/\\s*\\[[A-Z][A-Z0-9_]*(?:;[^\\]]*)?\\]\\s*$/, '')\n .trim();\n if (!first || /^at\\s/.test(first)) return fallback;\n return first.length > 240 ? `${first.slice(0, 239)}…` : first;\n}\n\n/**\n * Tolerant reader for WEBBUILDER_LIST_VERSIONS `{ versions:[{ sha, shortSha,\n * message, author, date, bookmark?, bookmarks?, isHead }], head, dirty, branch,\n * shallow, isGitRepo, count }`; drops rows with a bad sha.\n */\nexport function normalizeListVersionsData(input: Record<string, unknown>): VersionList | null {\n const data = actionFields(input);\n if (data.isGitRepo === false) return { versions: [], head: null, dirty: false, noRepo: true };\n const raw = Array.isArray(data.versions) ? data.versions : null;\n if (!raw) return null;\n const head = normalizeSha(data.head);\n const versions: WebbuilderVersion[] = [];\n for (const item of raw) {\n if (!item || typeof item !== 'object') continue;\n const r = item as Record<string, unknown>;\n const sha = normalizeSha(r.sha);\n if (!sha) continue;\n const marks = Array.isArray(r.bookmarks) ? r.bookmarks : [];\n const rawMark = typeof r.bookmark === 'string' ? r.bookmark : marks.find((m) => typeof m === 'string');\n const bookmark = typeof rawMark === 'string' ? bookmarkSlug(rawMark.replace(/^bookmark\\//, '')) : null;\n const date = typeof r.date === 'string' && !Number.isNaN(Date.parse(r.date)) ? r.date : undefined;\n versions.push({\n sha,\n shortSha: normalizeSha(r.shortSha) ?? sha.slice(0, 7),\n message: typeof r.message === 'string' ? r.message.split('\\n')[0].trim() : '',\n ...(typeof r.author === 'string' && r.author ? { author: r.author } : {}),\n ...(date ? { date } : {}),\n ...(bookmark ? { bookmark } : {}),\n isHead: r.isHead === true || (head !== null && sha === head),\n });\n }\n return {\n versions,\n head: head ?? versions.find((v) => v.isHead)?.sha ?? null,\n dirty: data.dirty === true,\n ...(data.shallow === true ? { partial: true } : {}),\n };\n}\n\n/**\n * WEBBUILDER_RESTORE_VERSION `{ restored, sha, shortSha, newHead, noChange,\n * autoSaved, message }`. `noChange` = the project already matched that version.\n */\nexport function normalizeRestoreData(\n input: Record<string, unknown>,\n): { ok: true; newHead: string | null; autoSaved: string | null } | { ok: false; reason: 'none' | 'failed' } {\n const data = actionFields(input);\n if (data.restored === false) return { ok: false, reason: 'failed' };\n if (data.noChange === true) return { ok: false, reason: 'none' };\n return { ok: true, newHead: normalizeSha(data.newHead), autoSaved: normalizeSha(data.autoSaved) };\n}\n\n/**\n * WEBBUILDER_BOOKMARK_VERSION `{ bookmark, tag, sha, moved }` or, on remove,\n * `{ bookmark, tag, sha, removed }`. The slug, from `bookmark` or `tag`.\n */\nexport function bookmarkFromData(input: Record<string, unknown>): string | null {\n const data = actionFields(input);\n const raw = typeof data.bookmark === 'string' ? data.bookmark : typeof data.tag === 'string' ? data.tag : '';\n return bookmarkSlug(raw.replace(/^bookmark\\//, ''));\n}\n\n/**\n * RUN_COMMAND script for the forward restore. Prints\n * `__RESTORE=ok <newHead>` | `__RESTORE=none` (already identical) |\n * `__RESTORE=unknown` (no such commit) | `__GIT=norepo` | `__RESTORE=failed`.\n *\n * `git read-tree --reset -u <sha>` makes index + tracked files match the old\n * version exactly (files added later are removed too, unlike\n * `git checkout <sha> -- .`). Untracked/ignored files (.env, node_modules) are\n * left alone, and the dev server keeps running and hot-reloads.\n */\nexport function buildRestoreCommand(sha: string, message: string): string {\n const s = normalizeSha(sha);\n if (!s) throw new Error('invalid version id');\n const msg = shellQuote(restoreCommitMessage(s, message));\n return [\n NO_REPO,\n `git cat-file -e '${s}^{commit}' 2>/dev/null || { echo \"__RESTORE=unknown\"; exit 0; }`,\n IDENTITY,\n // Keep uncommitted hand edits: commit them first (never .env*), so nothing is lost.\n ...SAFE_STAGE,\n 'git diff --cached --quiet || git $ID commit -q -m \\'Manual edits: saved before restore\\' >/dev/null 2>&1 || { echo \"__RESTORE=failed\"; exit 0; }',\n `git read-tree --reset -u '${s}' >/dev/null 2>&1 || { echo \"__RESTORE=failed\"; exit 0; }`,\n ...SAFE_STAGE,\n 'if git diff --cached --quiet HEAD; then echo \"__RESTORE=none\"; exit 0; fi',\n `if git $ID commit -q -m ${msg} >/dev/null 2>&1; then echo \"__RESTORE=ok $(git rev-parse HEAD)\"; else git reset -q --hard HEAD >/dev/null 2>&1; echo \"__RESTORE=failed\"; fi`,\n 'exit 0',\n ].join('\\n');\n}\n\nexport type RestoreOutcome =\n | { ok: true; newHead: string | null }\n | { ok: false; reason: 'none' | 'unknown' | 'norepo' | 'failed' };\n\nexport function parseRestoreOutput(stdout: string): RestoreOutcome {\n const text = String(stdout || '');\n if (/^__GIT=norepo\\s*$/m.test(text)) return { ok: false, reason: 'norepo' };\n const m = /^__RESTORE=(ok|none|unknown|failed)(?:\\s+([0-9a-f]{40}))?\\s*$/m.exec(text);\n if (!m) return { ok: false, reason: 'failed' };\n if (m[1] === 'ok') return { ok: true, newHead: normalizeSha(m[2] ?? '') };\n return { ok: false, reason: m[1] as 'none' | 'unknown' | 'failed' };\n}\n\n/**\n * RUN_COMMAND script for a bookmark: one bookmark per version, so existing\n * `bookmark/*` tags on that commit are removed first. `slug` null = remove.\n * Prints `__BOOKMARK=ok` | `__BOOKMARK=unknown` | `__BOOKMARK=failed` | `__GIT=norepo`.\n */\nexport function buildBookmarkCommand(sha: string, slug: string | null): string {\n const s = normalizeSha(sha);\n if (!s) throw new Error('invalid version id');\n if (slug !== null && bookmarkSlug(slug) !== slug) throw new Error('invalid bookmark name');\n return [\n NO_REPO,\n `git cat-file -e '${s}^{commit}' 2>/dev/null || { echo \"__BOOKMARK=unknown\"; exit 0; }`,\n `for T in $(git tag --points-at '${s}' --list 'bookmark/*' 2>/dev/null); do git tag -d \"$T\" >/dev/null 2>&1; done`,\n slug === null\n ? 'echo \"__BOOKMARK=ok\"'\n : `if git tag -f 'bookmark/${slug}' '${s}' >/dev/null 2>&1; then echo \"__BOOKMARK=ok\"; else echo \"__BOOKMARK=failed\"; fi`,\n 'exit 0',\n ].join('\\n');\n}\n\nexport function parseBookmarkOutput(stdout: string): 'ok' | 'unknown' | 'failed' | 'norepo' {\n const text = String(stdout || '');\n if (/^__GIT=norepo\\s*$/m.test(text)) return 'norepo';\n const m = /^__BOOKMARK=(ok|unknown|failed)\\s*$/m.exec(text);\n return (m?.[1] as 'ok' | 'unknown' | 'failed' | undefined) ?? 'failed';\n}\n\n/**\n * True when a connector error means \"this agent doesn't have that action yet\"\n * (the connector's `Unknown webbuilder action: X`, or the CLI's not-found forms).\n */\nexport function isUnknownActionError(error: string | null | undefined, data?: Record<string, unknown>): boolean {\n const blob = `${error || ''} ${typeof data?.error === 'string' ? data.error : ''} ${typeof data?.code === 'string' ? data.code : ''}`;\n return /unknown (webbuilder )?action|action[^\\n]{0,80}\\bnot (found|supported|available)|no such action|unsupported action|invalid action/i.test(\n blob,\n );\n}\n\n// ---------------------------------------------------------------------------\n// Display helpers\n\nexport type VersionKind = 'ai' | 'manual' | 'restore' | 'backup' | 'other';\n\n/** The git identities the builder commits with (the connector's and the surface's own). */\nconst BUILDER_AUTHOR_RE = /^(?:yantra(?:[ -]?web ?builder)?|web ?builder|cdecli)$/i;\nconst BUILDER_MESSAGE_RE = /^(?:cdecli:|manual edits:|restore to [0-9a-f]{7,40}:|backup:|webbuilder:)/i;\n/** A restore point named after the site: \"Happy Paws - first build\". */\nconst SNAPSHOT_NAME_RE = /^.+?\\s+[-–—]\\s+(.+)$/;\nconst FIRST_BUILD_RE = /^(?:.+?\\s+[-–—]\\s+)?first build$/i;\n\nexport function isBuilderAuthor(author: string | undefined): boolean {\n return BUILDER_AUTHOR_RE.test((author || '').trim());\n}\n\n/** A commit the builder made (AI turns, hand edits, restores, backups), not one inherited with the starting code. */\nexport function isBuilderVersion(version: Pick<WebbuilderVersion, 'message' | 'author'>): boolean {\n const m = (version.message || '').trim();\n return isBuilderAuthor(version.author) || BUILDER_MESSAGE_RE.test(m) || FIRST_BUILD_RE.test(m);\n}\n\nfunction sentence(text: string): string {\n const t = text.trim();\n return t ? t[0].toUpperCase() + t.slice(1) : t;\n}\n\n/**\n * Friendly label for a commit subject: AI turns (\"cdecli: …\", \"webbuilder: …\", \"<site> - first build\"),\n * hand edits (\"Manual edits: …\"), restores and backups. `author` lets a builder snapshot name lose its site prefix.\n */\nexport function describeVersion(message: string, author?: string): { kind: VersionKind; label: string } {\n const m = (message || '').trim();\n let r = /^cdecli:\\s*(.*)$/i.exec(m);\n if (r) return { kind: 'ai', label: r[1].trim() || 'AI change' };\n r = /^Manual edits:\\s*(.*)$/i.exec(m);\n if (r) {\n const rest = r[1].trim();\n return { kind: 'manual', label: !rest || rest === 'canvas changes' ? 'Your edits' : `Your edits: ${rest}` };\n }\n r = /^Restore to ([0-9a-f]{7,40}):\\s*(.*)$/i.exec(m);\n if (r) {\n const inner = describeVersion(r[2]);\n // Restoring a restore (Undo right after one) names the original once, not \"Restored “Restored “…””\".\n return { kind: 'restore', label: inner.kind === 'restore' ? inner.label : `Restored “${inner.label}”` };\n }\n if (/^backup:/i.test(m)) return { kind: 'backup', label: 'Backup saved' };\n r = /^webbuilder:\\s*(.*)$/i.exec(m);\n if (r) return { kind: 'ai', label: sentence(r[1]) || 'AI change' };\n if (FIRST_BUILD_RE.test(m)) return { kind: 'ai', label: 'First build' };\n r = isBuilderAuthor(author) ? SNAPSHOT_NAME_RE.exec(m) : null;\n if (r) return { kind: 'ai', label: sentence(r[1]) };\n return { kind: 'other', label: m || '(no message)' };\n}\n\n/** What History lists: the build's own versions, and how many inherited template commits were left out. */\nexport interface HistoryView {\n versions: WebbuilderVersion[];\n templateCommits: number;\n}\n\nexport interface TimelineOptions {\n /** Backups that changed no file. */\n unchanged?: ReadonlySet<string>;\n /** An imported repo, whose older commits are the user's own. */\n keepEarlier?: boolean;\n}\n\n/** The versions the user sees and steps through (History, Undo, Revert), as a list of its own. */\nexport interface VersionTimeline extends VersionList {\n templateCommits: number;\n /** A longer list may hold older versions. */\n hasMore?: boolean;\n}\n\n/** `historyView` as a `VersionList`: HEAD follows a folded backup down to the version it stands for. */\nexport function versionTimeline(list: VersionList, opts: TimelineOptions = {}): VersionTimeline {\n const view = historyView(list, opts);\n const head = view.versions.find((v) => v.isHead)?.sha ?? list.head;\n return { ...list, versions: view.versions, head, templateCommits: view.templateCommits };\n}\n\n/**\n * Commits older than the first build are the template's own history (written for its maintainers), so\n * only their count is kept. A backup that changed no file is folded into the version below it.\n * `keepEarlier`: an imported repo, whose older commits are the user's own.\n */\nexport function historyView(\n list: Pick<VersionList, 'versions'> | null | undefined,\n opts: TimelineOptions = {},\n): HistoryView {\n const all = list?.versions ?? [];\n let own = all;\n if (!opts.keepEarlier) {\n const oldest = (match: (v: WebbuilderVersion) => boolean) => {\n for (let i = all.length - 1; i >= 0; i--) if (match(all[i])) return i;\n return -1;\n };\n const firstBuild = oldest((v) => FIRST_BUILD_RE.test((v.message || '').trim()));\n const start = firstBuild >= 0 ? firstBuild : oldest(isBuilderVersion);\n if (start >= 0) own = all.slice(0, start + 1);\n }\n const versions: WebbuilderVersion[] = [];\n let carryHead = false;\n own.forEach((v, i) => {\n const fold =\n i < own.length - 1 &&\n !v.bookmark &&\n opts.unchanged?.has(v.sha) &&\n describeVersion(v.message, v.author).kind === 'backup';\n if (fold) {\n carryHead ||= v.isHead;\n return;\n }\n versions.push(carryHead && !v.isHead ? { ...v, isHead: true } : v);\n carryHead = false;\n });\n return { versions, templateCommits: all.length - own.length };\n}\n\n/** RUN_COMMAND script: which of these commits changed no file since their parent (`__SAME=<sha>` each). */\nexport function buildUnchangedCommand(shas: ReadonlyArray<string>): string {\n const valid = shas.map(normalizeSha).filter((s): s is string => s !== null && s.length === 40);\n return [\n NO_REPO,\n ...valid.map((s) => `git diff --quiet '${s}~1' '${s}' -- >/dev/null 2>&1 && echo \"__SAME=${s}\"`),\n 'echo \"__END=1\"',\n 'exit 0',\n ].join('\\n');\n}\n\nexport function parseUnchangedOutput(stdout: string): Set<string> {\n const out = new Set<string>();\n for (const m of String(stdout || '').matchAll(/^__SAME=([0-9a-f]{40})\\s*$/gm)) out.add(m[1]);\n return out;\n}\n\n/** \"just now\", \"5 min ago\", \"3 h ago\", \"2 days ago\", else a short date. */\nexport function relativeTime(iso: string | undefined, now: number = Date.now()): string {\n if (!iso) return '';\n const t = Date.parse(iso);\n if (Number.isNaN(t)) return '';\n const s = Math.max(0, Math.round((now - t) / 1000));\n if (s < 45) return 'just now';\n const min = Math.round(s / 60);\n if (min < 60) return `${min} min ago`;\n const h = Math.round(min / 60);\n if (h < 24) return `${h} h ago`;\n const d = Math.round(h / 24);\n if (d === 1) return 'yesterday';\n if (d < 7) return `${d} days ago`;\n return new Date(t).toISOString().slice(0, 10);\n}\n\n/** Who made it, in plain words: the AI, you, or (only on a person's own commit) their name. */\nfunction versionAuthor(kind: VersionKind, author: string | undefined): string {\n const name = author?.trim() || '';\n if (kind === 'ai' || kind === 'backup') return 'AI';\n if (kind === 'manual' || kind === 'restore') return name && !isBuilderAuthor(name) ? name : 'You';\n return isBuilderAuthor(name) ? 'AI' : name;\n}\n\n/** A History row: the commit message as the title, then time and author; the sha only in the tooltip. */\nexport function versionRow(\n version: Pick<WebbuilderVersion, 'shortSha' | 'message' | 'author' | 'date'>,\n now: number = Date.now(),\n): { kind: VersionKind; title: string; meta: string[]; tooltip: string } {\n const { kind, label } = describeVersion(version.message, version.author);\n const when = relativeTime(version.date, now);\n const who = versionAuthor(kind, version.author);\n const exact = version.date ? new Date(Date.parse(version.date)).toLocaleString() : '';\n return {\n kind,\n title: label,\n meta: [when, who].filter(Boolean),\n tooltip: [`Version ${version.shortSha}`, exact].filter(Boolean).join(' · '),\n };\n}\n\n/** A bookmark slug as a readable name: \"launch-ready\" -> \"Launch ready\". */\nexport function bookmarkLabel(slug: string): string {\n const text = slug.replace(/-+/g, ' ').trim();\n return text ? text[0].toUpperCase() + text.slice(1) : slug;\n}\n\n/** Chat line after a restore. */\nexport function restoredChatLine(version: Pick<WebbuilderVersion, 'shortSha' | 'message'>): string {\n return `Restored to ${version.shortSha}: ${describeVersion(version.message).label}`;\n}\n\n/**\n * The `manualEdits`-style entry the next AI turn gets, so it knows the files\n * went back to an older version (and doesn't \"fix\" them forward again).\n */\nexport function restoreManualEdit(version: Pick<WebbuilderVersion, 'shortSha' | 'message'>): {\n file: string;\n summary: string;\n} {\n return {\n file: '(whole project)',\n summary: oneLineSubject(\n `The user restored every file to version ${version.shortSha} (\"${describeVersion(version.message).label}\"). Changes made after that version are gone on purpose; build on the restored code.`,\n 500,\n ),\n };\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AA8CA,MAAM,MAAS,GAAA,kBAAA;AAGR,SAAS,WAAW,KAAiC,EAAA;AAC1D,EAAA,OAAO,OAAO,KAAA,KAAU,QAAY,IAAA,MAAA,CAAO,KAAK,KAAK,CAAA;AACvD;AAGO,SAAS,aAAa,KAA+B,EAAA;AAC1D,EAAI,IAAA,OAAO,KAAU,KAAA,QAAA,EAAiB,OAAA,IAAA;AACtC,EAAA,MAAM,CAAI,GAAA,KAAA,CAAM,IAAK,EAAA,CAAE,WAAY,EAAA;AACnC,EAAO,OAAA,UAAA,CAAW,CAAC,CAAA,GAAI,CA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AA,KAAA,CAAM,IAAI,CAAA,CAAE,CAAC,CAAA,CAAE,MAAS,GAAA;AAAA,KAAA,EACvE,OAAO,CAAA,CAAE,MAAW,KAAA,QAAA,IAAY,EAAE,MAAS,GAAA;AAAA,MAC7C,QAAQ,CAAE,CAAA;AAAA,KACZ,GAAI,EAAC,CAAA,EACD,IAAO,GAAA;AAAA,MACT;AAAA,KACF,GAAI,EAAC,CAAA,EACD,QAAW,GAAA;AAAA,MACb;AAAA,KACF,GAAI,EAZQ,CAAA,EAAA;AAAA,MAaZ,QAAQ,CAAE,CAAA,MAAA,KAAW,IAAQ,IAAA,IAAA,KAAS,QAAQ,GAAQ,KAAA;AAAA,KACvD,CAAA,CAAA;AAAA;AAEH,EAAO,OAAA,cAAA,CAAA;AAAA,IACL,QAAA;AAAA,IACA,IAAA,EAAA,CAAM,EAAQ,GAAA,IAAA,IAAA,IAAA,GAAA,IAAA,GAAA,CAAA,EAAA,GAAA,QAAA,CAAS,IAAK,CAAA,CAAA,CAAA,KAAK,EAAE,MAAM,CAAA,KAA3B,IAA8B,GAAA,MAAA,GAAA,EAAA,CAAA,GAAA,KAAtC,IAA6C,GAAA,EAAA,GAAA,IAAA;AAAA,IACnD,KAAA,EAAO,KAAK,KAAU,KAAA;AAAA,GAClB,EAAA,IAAA,CAAK,YAAY,IAAO,GAAA;AAAA,IAC1B,OAAS,EAAA;AAAA,MACP,EAAC,CAAA;AAET"}
1
+ {"version":3,"file":"versions.js","sources":["../../../../../src/features/webbuilder/web/history/versions.ts"],"sourcesContent":["/**\n * W17: version history, restore and bookmarks (spec Phase 3-4 §1).\n *\n * The connector actions WEBBUILDER_LIST_VERSIONS / RESTORE_VERSION /\n * BOOKMARK_VERSION may not exist on a hosted agent yet. Until they do, the\n * surface falls back to WEBBUILDER_RUN_COMMAND with the git scripts built\n * here. Everything is pure (no connector, no React) so it is unit-tested:\n * - every sha is validated strictly (hex, 7-40 chars) before it reaches a shell;\n * - bookmark names become a safe slug (`bookmark/<slug>` git tags);\n * - commit subjects are single-line and single-quoted.\n *\n * Restore is always FORWARD: the files of the old version become a new commit\n * \"Restore to <short>: <message>\". History is never rewritten.\n *\n * Dirty tree (decision): a restore never refuses a dirty tree and never loses\n * work. Uncommitted changes (hand edits still waiting for their debounced\n * commit) are first committed as \"Manual edits: saved before restore\", so they\n * stay one click away in the history. `.env*`, node_modules and build output\n * are never staged. Refusing would only push the user into a dead end, because\n * the surface itself produces those uncommitted edits.\n */\n\nexport const DEFAULT_VERSION_LIMIT = 50;\nexport const MAX_VERSION_LIMIT = 200;\n/** RUN_COMMAND stdout is capped (~12 KB) - the git-log fallback asks for fewer rows. */\nexport const FALLBACK_VERSION_LIMIT = 40;\n\nexport interface WebbuilderVersion {\n sha: string;\n shortSha: string;\n message: string;\n author?: string;\n /** ISO date. */\n date?: string;\n /** Bookmark slug (the `bookmark/<slug>` tag), when the version has one. */\n bookmark?: string;\n isHead: boolean;\n}\n\nexport interface VersionList {\n versions: WebbuilderVersion[];\n head: string | null;\n dirty: boolean;\n /** Output was cut off, or the clone is shallow: older versions may be missing. */\n partial?: boolean;\n /** The project has no git repository yet (native `isGitRepo: false`). */\n noRepo?: boolean;\n}\n\nconst SHA_RE = /^[0-9a-f]{7,40}$/;\n\n/** Strict sha check: lowercase hex, 7-40 characters. Anything else is refused. */\nexport function isValidSha(value: unknown): value is string {\n return typeof value === 'string' && SHA_RE.test(value);\n}\n\n/** Lower-cased, trimmed sha, or null when it is not a valid sha. */\nexport function normalizeSha(value: unknown): string | null {\n if (typeof value !== 'string') return null;\n const v = value.trim().toLowerCase();\n return isValidSha(v) ? v : null;\n}\n\nexport function clampLimit(limit: unknown, fallback = DEFAULT_VERSION_LIMIT): number {\n const n = typeof limit === 'number' && Number.isFinite(limit) ? Math.floor(limit) : fallback;\n return Math.min(MAX_VERSION_LIMIT, Math.max(1, n));\n}\n\n/** Safe bookmark slug: lowercase `a-z0-9-`, at most 40 chars. Null when nothing is left. */\nexport function bookmarkSlug(name: unknown): string | null {\n if (typeof name !== 'string') return null;\n const slug = name\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 40)\n .replace(/-+$/g, '');\n return slug || null;\n}\n\nexport function shellQuote(value: string): string {\n return `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n\n/** Single-line, printable subject (max 72 chars). */\nexport function oneLineSubject(text: string, max = 72): string {\n const flat = String(text || '')\n .replace(/[\\r\\n\\t]+/g, ' ')\n .replace(/[^\\x20-\\x7E -￿]/g, '')\n .replace(/\\s+/g, ' ')\n .trim();\n return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;\n}\n\n/** \"Restore to <short>: <message>\" - the forward restore's commit subject. */\nexport function restoreCommitMessage(sha: string, message: string): string {\n const short = sha.slice(0, 7);\n return oneLineSubject(`Restore to ${short}: ${oneLineSubject(message, 200) || 'earlier version'}`);\n}\n\nexport const NO_REPO = 'git rev-parse --is-inside-work-tree >/dev/null 2>&1 || { echo \"__GIT=norepo\"; exit 0; }';\nconst IDENTITY =\n 'ID=\"\"; git config user.email >/dev/null 2>&1 || ID=\"-c user.name=Yantra -c user.email=webbuilder@yantra.dev\"';\n/** Stage everything except secrets, dependencies and build output (same rules as the manual-edit commit). */\nconst SAFE_STAGE = [\n \"git add -A -- . ':!.env*' ':!**/.env*' ':!node_modules' ':!**/node_modules' ':!dist' ':!.output' >/dev/null 2>&1 || true\",\n \"git reset -q -- '.env*' '**/.env*' >/dev/null 2>&1 || true\",\n];\n\n/**\n * RUN_COMMAND script: HEAD, dirty flag and the last `limit` commits, one per line:\n * `__V<TAB>sha<TAB>isoDate<TAB>author<TAB>refs<TAB>subject`. Always exits 0.\n */\nexport function buildListVersionsCommand(limit: number = FALLBACK_VERSION_LIMIT): string {\n const n = clampLimit(limit, FALLBACK_VERSION_LIMIT);\n return [\n NO_REPO,\n 'echo \"__GIT=ok\"',\n 'echo \"__HEAD=$(git rev-parse HEAD 2>/dev/null)\"',\n \"if [ -n \\\"$(git status --porcelain -- . ':!.env*' ':!**/.env*' ':!node_modules' ':!**/node_modules' ':!dist' ':!.output' 2>/dev/null | head -n 1)\\\" ]; then echo \\\"__DIRTY=1\\\"; else echo \\\"__DIRTY=0\\\"; fi\",\n `git log -n ${n} --no-color --pretty=format:'__V%x09%H%x09%aI%x09%an%x09%D%x09%s' 2>/dev/null || true`,\n 'echo',\n 'echo \"__END=1\"',\n 'exit 0',\n ].join('\\n');\n}\n\nexport type ParsedVersionList = (VersionList & { ok: true }) | { ok: false; reason: 'norepo' | 'unreadable' };\n\n/** Bookmark slug from a `%D` refs list (\"HEAD -> main, tag: bookmark/launch\"). */\nexport function bookmarkFromRefs(refs: string): string | undefined {\n for (const part of refs.split(',')) {\n const m = /^\\s*tag:\\s*bookmark\\/([a-z0-9-]{1,40})\\s*$/.exec(part);\n if (m) return m[1];\n }\n return undefined;\n}\n\nexport function parseListVersionsOutput(stdout: string, opts?: { truncated?: boolean }): ParsedVersionList {\n const text = String(stdout || '');\n if (/^__GIT=norepo\\s*$/m.test(text)) return { ok: false, reason: 'norepo' };\n if (!/^__GIT=ok\\s*$/m.test(text)) return { ok: false, reason: 'unreadable' };\n const head = normalizeSha(/^__HEAD=(.*)$/m.exec(text)?.[1] ?? '');\n const dirty = /^__DIRTY=1\\s*$/m.test(text);\n const versions: WebbuilderVersion[] = [];\n for (const line of text.split('\\n')) {\n if (!line.startsWith('__V\\t')) continue;\n const [, rawSha, date, author, refs, ...rest] = line.split('\\t');\n const sha = normalizeSha(rawSha);\n if (!sha || sha.length !== 40) continue;\n const bookmark = bookmarkFromRefs(refs ?? '');\n versions.push({\n sha,\n shortSha: sha.slice(0, 7),\n message: rest.join('\\t').replace(/\\r$/, '').trim(),\n ...(author ? { author: author.trim() } : {}),\n ...(date && !Number.isNaN(Date.parse(date)) ? { date: date.trim() } : {}),\n ...(bookmark ? { bookmark } : {}),\n isHead: sha === head,\n });\n }\n const ended = /^__END=1\\s*$/m.test(text);\n return {\n ok: true,\n versions,\n head,\n dirty,\n ...(opts?.truncated || !ended ? { partial: true } : {}),\n };\n}\n\n/**\n * The action's fields. The transport already unwraps `{ data }`; a second\n * `data` layer (older transports) is tolerated.\n */\nexport function actionFields(data: Record<string, unknown> | null | undefined): Record<string, unknown> {\n const rec = data && typeof data === 'object' ? data : {};\n const inner = rec.data;\n if (inner && typeof inner === 'object' && !Array.isArray(inner)) return inner as Record<string, unknown>;\n return rec;\n}\n\n/**\n * The plain sentence of a connector error: `\"<sentence> [CODE]\\nLast output:…\"`\n * -> `\"<sentence>\"`. Falls back when there is nothing readable.\n */\nexport function plainConnectorError(error: unknown, fallback: string): string {\n const first = String(error ?? '')\n .split('\\n')[0]\n .replace(/\\s*\\[[A-Z][A-Z0-9_]*(?:;[^\\]]*)?\\]\\s*$/, '')\n .trim();\n if (!first || /^at\\s/.test(first)) return fallback;\n return first.length > 240 ? `${first.slice(0, 239)}…` : first;\n}\n\n/**\n * Tolerant reader for WEBBUILDER_LIST_VERSIONS `{ versions:[{ sha, shortSha,\n * message, author, date, bookmark?, bookmarks?, isHead }], head, dirty, branch,\n * shallow, isGitRepo, count }`; drops rows with a bad sha.\n */\nexport function normalizeListVersionsData(input: Record<string, unknown>): VersionList | null {\n const data = actionFields(input);\n if (data.isGitRepo === false) return { versions: [], head: null, dirty: false, noRepo: true };\n const raw = Array.isArray(data.versions) ? data.versions : null;\n if (!raw) return null;\n const head = normalizeSha(data.head);\n const versions: WebbuilderVersion[] = [];\n for (const item of raw) {\n if (!item || typeof item !== 'object') continue;\n const r = item as Record<string, unknown>;\n const sha = normalizeSha(r.sha);\n if (!sha) continue;\n const marks = Array.isArray(r.bookmarks) ? r.bookmarks : [];\n const rawMark = typeof r.bookmark === 'string' ? r.bookmark : marks.find((m) => typeof m === 'string');\n const bookmark = typeof rawMark === 'string' ? bookmarkSlug(rawMark.replace(/^bookmark\\//, '')) : null;\n const date = typeof r.date === 'string' && !Number.isNaN(Date.parse(r.date)) ? r.date : undefined;\n versions.push({\n sha,\n shortSha: normalizeSha(r.shortSha) ?? sha.slice(0, 7),\n message: typeof r.message === 'string' ? r.message.split('\\n')[0].trim() : '',\n ...(typeof r.author === 'string' && r.author ? { author: r.author } : {}),\n ...(date ? { date } : {}),\n ...(bookmark ? { bookmark } : {}),\n isHead: r.isHead === true || (head !== null && sha === head),\n });\n }\n return {\n versions,\n head: head ?? versions.find((v) => v.isHead)?.sha ?? null,\n dirty: data.dirty === true,\n ...(data.shallow === true ? { partial: true } : {}),\n };\n}\n\n/**\n * WEBBUILDER_RESTORE_VERSION `{ restored, sha, shortSha, newHead, noChange,\n * autoSaved, message }`. `noChange` = the project already matched that version.\n */\nexport function normalizeRestoreData(\n input: Record<string, unknown>,\n): { ok: true; newHead: string | null; autoSaved: string | null } | { ok: false; reason: 'none' | 'failed' } {\n const data = actionFields(input);\n if (data.restored === false) return { ok: false, reason: 'failed' };\n if (data.noChange === true) return { ok: false, reason: 'none' };\n return { ok: true, newHead: normalizeSha(data.newHead), autoSaved: normalizeSha(data.autoSaved) };\n}\n\n/**\n * WEBBUILDER_BOOKMARK_VERSION `{ bookmark, tag, sha, moved }` or, on remove,\n * `{ bookmark, tag, sha, removed }`. The slug, from `bookmark` or `tag`.\n */\nexport function bookmarkFromData(input: Record<string, unknown>): string | null {\n const data = actionFields(input);\n const raw = typeof data.bookmark === 'string' ? data.bookmark : typeof data.tag === 'string' ? data.tag : '';\n return bookmarkSlug(raw.replace(/^bookmark\\//, ''));\n}\n\n/**\n * RUN_COMMAND script for the forward restore. Prints\n * `__RESTORE=ok <newHead>` | `__RESTORE=none` (already identical) |\n * `__RESTORE=unknown` (no such commit) | `__GIT=norepo` | `__RESTORE=failed`.\n *\n * `git read-tree --reset -u <sha>` makes index + tracked files match the old\n * version exactly (files added later are removed too, unlike\n * `git checkout <sha> -- .`). Untracked/ignored files (.env, node_modules) are\n * left alone, and the dev server keeps running and hot-reloads.\n */\nexport function buildRestoreCommand(sha: string, message: string): string {\n const s = normalizeSha(sha);\n if (!s) throw new Error('invalid version id');\n const msg = shellQuote(restoreCommitMessage(s, message));\n return [\n NO_REPO,\n `git cat-file -e '${s}^{commit}' 2>/dev/null || { echo \"__RESTORE=unknown\"; exit 0; }`,\n IDENTITY,\n // Keep uncommitted hand edits: commit them first (never .env*), so nothing is lost.\n ...SAFE_STAGE,\n 'git diff --cached --quiet || git $ID commit -q -m \\'Manual edits: saved before restore\\' >/dev/null 2>&1 || { echo \"__RESTORE=failed\"; exit 0; }',\n `git read-tree --reset -u '${s}' >/dev/null 2>&1 || { echo \"__RESTORE=failed\"; exit 0; }`,\n ...SAFE_STAGE,\n 'if git diff --cached --quiet HEAD; then echo \"__RESTORE=none\"; exit 0; fi',\n `if git $ID commit -q -m ${msg} >/dev/null 2>&1; then echo \"__RESTORE=ok $(git rev-parse HEAD)\"; else git reset -q --hard HEAD >/dev/null 2>&1; echo \"__RESTORE=failed\"; fi`,\n 'exit 0',\n ].join('\\n');\n}\n\nexport type RestoreOutcome =\n | { ok: true; newHead: string | null }\n | { ok: false; reason: 'none' | 'unknown' | 'norepo' | 'failed' };\n\nexport function parseRestoreOutput(stdout: string): RestoreOutcome {\n const text = String(stdout || '');\n if (/^__GIT=norepo\\s*$/m.test(text)) return { ok: false, reason: 'norepo' };\n const m = /^__RESTORE=(ok|none|unknown|failed)(?:\\s+([0-9a-f]{40}))?\\s*$/m.exec(text);\n if (!m) return { ok: false, reason: 'failed' };\n if (m[1] === 'ok') return { ok: true, newHead: normalizeSha(m[2] ?? '') };\n return { ok: false, reason: m[1] as 'none' | 'unknown' | 'failed' };\n}\n\n/**\n * RUN_COMMAND script for a bookmark: one bookmark per version, so existing\n * `bookmark/*` tags on that commit are removed first. `slug` null = remove.\n * Prints `__BOOKMARK=ok` | `__BOOKMARK=unknown` | `__BOOKMARK=failed` | `__GIT=norepo`.\n */\nexport function buildBookmarkCommand(sha: string, slug: string | null): string {\n const s = normalizeSha(sha);\n if (!s) throw new Error('invalid version id');\n if (slug !== null && bookmarkSlug(slug) !== slug) throw new Error('invalid bookmark name');\n return [\n NO_REPO,\n `git cat-file -e '${s}^{commit}' 2>/dev/null || { echo \"__BOOKMARK=unknown\"; exit 0; }`,\n `for T in $(git tag --points-at '${s}' --list 'bookmark/*' 2>/dev/null); do git tag -d \"$T\" >/dev/null 2>&1; done`,\n slug === null\n ? 'echo \"__BOOKMARK=ok\"'\n : `if git tag -f 'bookmark/${slug}' '${s}' >/dev/null 2>&1; then echo \"__BOOKMARK=ok\"; else echo \"__BOOKMARK=failed\"; fi`,\n 'exit 0',\n ].join('\\n');\n}\n\nexport function parseBookmarkOutput(stdout: string): 'ok' | 'unknown' | 'failed' | 'norepo' {\n const text = String(stdout || '');\n if (/^__GIT=norepo\\s*$/m.test(text)) return 'norepo';\n const m = /^__BOOKMARK=(ok|unknown|failed)\\s*$/m.exec(text);\n return (m?.[1] as 'ok' | 'unknown' | 'failed' | undefined) ?? 'failed';\n}\n\n/**\n * True when a connector error means \"this agent doesn't have that action yet\"\n * (the connector's `Unknown webbuilder action: X`, or the CLI's not-found forms).\n */\nexport function isUnknownActionError(error: string | null | undefined, data?: Record<string, unknown>): boolean {\n const blob = `${error || ''} ${typeof data?.error === 'string' ? data.error : ''} ${typeof data?.code === 'string' ? data.code : ''}`;\n return /unknown (webbuilder )?action|action[^\\n]{0,80}\\bnot (found|supported|available)|no such action|unsupported action|invalid action/i.test(\n blob,\n );\n}\n\n// ---------------------------------------------------------------------------\n// Display helpers\n\nexport type VersionKind = 'ai' | 'manual' | 'restore' | 'backup' | 'other';\n\n/** The git identities the builder commits with (the connector's and the surface's own). */\nconst BUILDER_AUTHOR_RE = /^(?:yantra(?:[ -]?web ?builder)?|web ?builder|cdecli)$/i;\nconst BUILDER_MESSAGE_RE = /^(?:cdecli:|manual edits:|restore to [0-9a-f]{7,40}:|backup:|webbuilder:)/i;\n/** A restore point named after the site: \"Happy Paws - first build\". */\nconst SNAPSHOT_NAME_RE = /^.+?\\s+[-–—]\\s+(.+)$/;\nconst TEMPLATE_REPO_RE = /\\bfrom YantraTemplates\\//;\nconst FIRST_BUILD_RE = /^(?:.+?\\s+[-–—]\\s+)?first build$/i;\n\nexport function isBuilderAuthor(author: string | undefined): boolean {\n return BUILDER_AUTHOR_RE.test((author || '').trim());\n}\n\n/** A commit the builder made (AI turns, hand edits, restores, backups), not one inherited with the starting code. */\nexport function isBuilderVersion(version: Pick<WebbuilderVersion, 'message' | 'author'>): boolean {\n const m = (version.message || '').trim();\n return isBuilderAuthor(version.author) || BUILDER_MESSAGE_RE.test(m) || FIRST_BUILD_RE.test(m);\n}\n\nfunction sentence(text: string): string {\n const t = text.trim();\n return t ? t[0].toUpperCase() + t.slice(1) : t;\n}\n\n/**\n * Friendly label for a commit subject: AI turns (\"cdecli: …\", \"webbuilder: …\", \"<site> - first build\"),\n * hand edits (\"Manual edits: …\"), restores and backups. `author` lets a builder snapshot name lose its site prefix.\n */\nexport function describeVersion(message: string, author?: string): { kind: VersionKind; label: string } {\n const m = (message || '').trim();\n let r = /^cdecli:\\s*(.*)$/i.exec(m);\n if (r) return { kind: 'ai', label: r[1].trim() || 'AI change' };\n r = /^Manual edits:\\s*(.*)$/i.exec(m);\n if (r) {\n const rest = r[1].trim();\n return { kind: 'manual', label: !rest || rest === 'canvas changes' ? 'Your edits' : `Your edits: ${rest}` };\n }\n r = /^Restore to ([0-9a-f]{7,40}):\\s*(.*)$/i.exec(m);\n if (r) {\n const inner = describeVersion(r[2]);\n // Restoring a restore (Undo right after one) names the original once, not \"Restored “Restored “…””\".\n return { kind: 'restore', label: inner.kind === 'restore' ? inner.label : `Restored “${inner.label}”` };\n }\n if (/^backup:/i.test(m)) return { kind: 'backup', label: 'Backup saved' };\n r = /^webbuilder:\\s*(.*)$/i.exec(m);\n if (r) return { kind: 'ai', label: sentence(r[1]) || 'AI change' };\n if (FIRST_BUILD_RE.test(m)) return { kind: 'ai', label: 'First build' };\n r = isBuilderAuthor(author) ? SNAPSHOT_NAME_RE.exec(m) : null;\n if (r) return { kind: 'ai', label: sentence(r[1]) };\n return { kind: 'other', label: m || '(no message)' };\n}\n\n/** What History lists: the build's own versions, and how many inherited template commits were left out. */\nexport interface HistoryView {\n versions: WebbuilderVersion[];\n templateCommits: number;\n}\n\nexport interface TimelineOptions {\n /** Backups that changed no file. */\n unchanged?: ReadonlySet<string>;\n /** An imported repo, whose older commits are the user's own. */\n keepEarlier?: boolean;\n}\n\n/** The versions the user sees and steps through (History, Undo, Revert), as a list of its own. */\nexport interface VersionTimeline extends VersionList {\n templateCommits: number;\n /** A longer list may hold older versions. */\n hasMore?: boolean;\n}\n\n/** `historyView` as a `VersionList`: HEAD follows a folded backup down to the version it stands for. */\nexport function versionTimeline(list: VersionList, opts: TimelineOptions = {}): VersionTimeline {\n const view = historyView(list, opts);\n const head = view.versions.find((v) => v.isHead)?.sha ?? list.head;\n return { ...list, versions: view.versions, head, templateCommits: view.templateCommits };\n}\n\n/**\n * Commits older than the first build are the template's own history (written for its maintainers), so\n * only their count is kept. A backup that changed no file is folded into the version below it.\n * `keepEarlier`: an imported repo, whose older commits are the user's own.\n */\nexport function historyView(\n list: Pick<VersionList, 'versions'> | null | undefined,\n opts: TimelineOptions = {},\n): HistoryView {\n const all = list?.versions ?? [];\n let own = all;\n if (!opts.keepEarlier) {\n const oldest = (match: (v: WebbuilderVersion) => boolean) => {\n for (let i = all.length - 1; i >= 0; i--) if (match(all[i])) return i;\n return -1;\n };\n const firstBuild = oldest((v) => FIRST_BUILD_RE.test((v.message || '').trim()));\n const start = firstBuild >= 0 ? firstBuild : oldest(isBuilderVersion);\n if (start >= 0) own = all.slice(0, start + 1);\n else {\n // Nothing built yet: a Yantra template's own merge commit and everything before it are the template's.\n const templateTip = all.findIndex((v) => TEMPLATE_REPO_RE.test(v.message || ''));\n if (templateTip >= 0) own = all.slice(0, templateTip);\n }\n }\n const versions: WebbuilderVersion[] = [];\n let carryHead = false;\n own.forEach((v, i) => {\n const fold =\n i < own.length - 1 &&\n !v.bookmark &&\n opts.unchanged?.has(v.sha) &&\n describeVersion(v.message, v.author).kind === 'backup';\n if (fold) {\n carryHead ||= v.isHead;\n return;\n }\n versions.push(carryHead && !v.isHead ? { ...v, isHead: true } : v);\n carryHead = false;\n });\n return { versions, templateCommits: all.length - own.length };\n}\n\n/** RUN_COMMAND script: which of these commits changed no file since their parent (`__SAME=<sha>` each). */\nexport function buildUnchangedCommand(shas: ReadonlyArray<string>): string {\n const valid = shas.map(normalizeSha).filter((s): s is string => s !== null && s.length === 40);\n return [\n NO_REPO,\n ...valid.map((s) => `git diff --quiet '${s}~1' '${s}' -- >/dev/null 2>&1 && echo \"__SAME=${s}\"`),\n 'echo \"__END=1\"',\n 'exit 0',\n ].join('\\n');\n}\n\nexport function parseUnchangedOutput(stdout: string): Set<string> {\n const out = new Set<string>();\n for (const m of String(stdout || '').matchAll(/^__SAME=([0-9a-f]{40})\\s*$/gm)) out.add(m[1]);\n return out;\n}\n\n/** \"just now\", \"5 min ago\", \"3 h ago\", \"2 days ago\", else a short date. */\nexport function relativeTime(iso: string | undefined, now: number = Date.now()): string {\n if (!iso) return '';\n const t = Date.parse(iso);\n if (Number.isNaN(t)) return '';\n const s = Math.max(0, Math.round((now - t) / 1000));\n if (s < 45) return 'just now';\n const min = Math.round(s / 60);\n if (min < 60) return `${min} min ago`;\n const h = Math.round(min / 60);\n if (h < 24) return `${h} h ago`;\n const d = Math.round(h / 24);\n if (d === 1) return 'yesterday';\n if (d < 7) return `${d} days ago`;\n return new Date(t).toISOString().slice(0, 10);\n}\n\n/** Who made it, in plain words: the AI, you, or (only on a person's own commit) their name. */\nfunction versionAuthor(kind: VersionKind, author: string | undefined): string {\n const name = author?.trim() || '';\n if (kind === 'ai' || kind === 'backup') return 'AI';\n if (kind === 'manual' || kind === 'restore') return name && !isBuilderAuthor(name) ? name : 'You';\n return isBuilderAuthor(name) ? 'AI' : name;\n}\n\n/** A History row: the commit message as the title, then time and author; the sha only in the tooltip. */\nexport function versionRow(\n version: Pick<WebbuilderVersion, 'shortSha' | 'message' | 'author' | 'date'>,\n now: number = Date.now(),\n): { kind: VersionKind; title: string; meta: string[]; tooltip: string } {\n const { kind, label } = describeVersion(version.message, version.author);\n const when = relativeTime(version.date, now);\n const who = versionAuthor(kind, version.author);\n const exact = version.date ? new Date(Date.parse(version.date)).toLocaleString() : '';\n return {\n kind,\n title: label,\n meta: [when, who].filter(Boolean),\n tooltip: [`Version ${version.shortSha}`, exact].filter(Boolean).join(' · '),\n };\n}\n\n/** A bookmark slug as a readable name: \"launch-ready\" -> \"Launch ready\". */\nexport function bookmarkLabel(slug: string): string {\n const text = slug.replace(/-+/g, ' ').trim();\n return text ? text[0].toUpperCase() + text.slice(1) : slug;\n}\n\n/** Chat line after a restore. */\nexport function restoredChatLine(version: Pick<WebbuilderVersion, 'shortSha' | 'message'>): string {\n return `Restored an earlier version: ${describeVersion(version.message).label}`;\n}\n\n/**\n * The `manualEdits`-style entry the next AI turn gets, so it knows the files\n * went back to an older version (and doesn't \"fix\" them forward again).\n */\nexport function restoreManualEdit(version: Pick<WebbuilderVersion, 'shortSha' | 'message'>): {\n file: string;\n summary: string;\n} {\n return {\n file: '(whole project)',\n summary: oneLineSubject(\n `The user restored every file to version ${version.shortSha} (\"${describeVersion(version.message).label}\"). Changes made after that version are gone on purpose; build on the restored code.`,\n 500,\n ),\n };\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AA8CA,MAAM,MAAS,GAAA,kBAAA;AAGR,SAAS,WAAW,KAAiC,EAAA;AAC1D,EAAA,OAAO,OAAO,KAAA,KAAU,QAAY,IAAA,MAAA,CAAO,KAAK,KAAK,CAAA;AACvD;AAGO,SAAS,aAAa,KAA+B,EAAA;AAC1D,EAAI,IAAA,OAAO,KAAU,KAAA,QAAA,EAAiB,OAAA,IAAA;AACtC,EAAA,MAAM,CAAI,GAAA,KAAA,CAAM,IAAK,EAAA,CAAE,WAAY,EAAA;AACnC,EAA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,KAAY,QAAW,GAAA,CAAA,CAAE,OAAQ,CAAA,KAAA,CAAM,IAAI,CAAA,CAAE,CAAC,CAAA,CAAE,MAAS,GAAA;AAAA,KAAA,EACvE,OAAO,CAAA,CAAE,MAAW,KAAA,QAAA,IAAY,EAAE,MAAS,GAAA;AAAA,MAC7C,QAAQ,CAAE,CAAA;AAAA,KACZ,GAAI,EAAC,CAAA,EACD,IAAO,GAAA;AAAA,MACT;AAAA,KACF,GAAI,EAAC,CAAA,EACD,QAAW,GAAA;AAAA,MACb;AAAA,KACF,GAAI,EAZQ,CAAA,EAAA;AAAA,MAaZ,QAAQ,CAAE,CAAA,MAAA,KAAW,IAAQ,IAAA,IAAA,KAAS,QAAQ,GAAQ,KAAA;AAAA,KACvD,CAAA,CAAA;AAAA;AAEH,EAAO,OAAA,cAAA,CAAA;AAAA,IACL,QAAA;AAAA,IACA,IAAA,EAAA,CAAM,EAAQ,GAAA,IAAA,IAAA,IAAA,GAAA,IAAA,GAAA,CAAA,EAAA,GAAA,QAAA,CAAS,IAAK,CAAA,CAAA,CAAA,KAAK,EAAE,MAAM,CAAA,KAA3B,IAA8B,GAAA,MAAA,GAAA,EAAA,CAAA,GAAA,KAAtC,IAA6C,GAAA,EAAA,GAAA,IAAA;AAAA,IACnD,KAAA,EAAO,KAAK,KAAU,KAAA;AAAA,GAClB,EAAA,IAAA,CAAK,YAAY,IAAO,GAAA;AAAA,IAC1B,OAAS,EAAA;AAAA,MACP,EAAC,CAAA;AAET"}
@@ -0,0 +1,27 @@
1
+ import {LIVE_GRAPHICS_ASK}from'../chat/referenceMode.js';function normalizeReferenceUrl(input) {
2
+ let raw = String(input != null ? input : "").trim();
3
+ if (!raw) return void 0;
4
+ if (!/^[a-z][a-z0-9+.-]*:/i.test(raw)) {
5
+ if (!/^[\w-]+(\.[\w-]+)+([/:?#].*)?$/.test(raw)) return void 0;
6
+ raw = `https://${raw}`;
7
+ }
8
+ if (!/^https:\/\//i.test(raw)) return void 0;
9
+ try {
10
+ const u = new URL(raw);
11
+ if (!u.hostname.includes(".") || u.username || u.password) return void 0;
12
+ return u.toString();
13
+ } catch (e) {
14
+ return void 0;
15
+ }
16
+ }
17
+ function websiteImportUrl(input) {
18
+ const url = normalizeReferenceUrl(input);
19
+ if (!url) return null;
20
+ const u = new URL(url);
21
+ u.hash = "";
22
+ return u.toString();
23
+ }
24
+ function websiteImportBrief(url, graphics = "pictures") {
25
+ const brief = `Copy my website ${url} here, page for page, so I can keep editing and publishing it here.`;
26
+ return graphics === "live" ? `${brief} ${LIVE_GRAPHICS_ASK}` : brief;
27
+ }export{normalizeReferenceUrl,websiteImportBrief,websiteImportUrl};//# sourceMappingURL=websiteImport.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"websiteImport.js","sources":["../../../../../src/features/webbuilder/web/import/websiteImport.ts"],"sourcesContent":["/**\n * \"Import your website\" (web 0.16): a new project that starts as a page-for-page copy of a live site the person\n * owns. It is an ordinary new-site chat turn worded the way the builder's agent copies a site (\"copy my site …\n * here\"), so the copy shows live in the build view like any other. Pure.\n */\nimport { LIVE_GRAPHICS_ASK, type CopyGraphics } from '../chat/referenceMode';\n\n/** \"cafe.com\", \"https://cafe.com/menu\" -> https address; undefined when it isn't one (web turnProps). */\nexport function normalizeReferenceUrl(input: string | null | undefined): string | undefined {\n let raw = String(input ?? '').trim();\n if (!raw) return undefined;\n if (!/^[a-z][a-z0-9+.-]*:/i.test(raw)) {\n if (!/^[\\w-]+(\\.[\\w-]+)+([/:?#].*)?$/.test(raw)) return undefined;\n raw = `https://${raw}`;\n }\n if (!/^https:\\/\\//i.test(raw)) return undefined;\n try {\n const u = new URL(raw);\n if (!u.hostname.includes('.') || u.username || u.password) return undefined;\n return u.toString();\n } catch {\n return undefined;\n }\n}\n\n/** The site's address as typed, https only, without its #hash; null when it isn't one. */\nexport function websiteImportUrl(input: string | null | undefined): string | null {\n const url = normalizeReferenceUrl(input);\n if (!url) return null;\n const u = new URL(url);\n u.hash = '';\n return u.toString();\n}\n\n/** The chat message that starts the copy (what the person sees as their own message). */\nexport function websiteImportBrief(url: string, graphics: CopyGraphics = 'pictures'): string {\n const brief = `Copy my website ${url} here, page for page, so I can keep editing and publishing it here.`;\n return graphics === 'live' ? `${brief} ${LIVE_GRAPHICS_ASK}` : brief;\n}\n"],"names":[],"mappings":"yDAQO,SAAS,sBAAsB,KAAsD,EAAA;AAC1F,EAAA,IAAI,GAAM,GAAA,MAAA,CAAO,KAAS,IAAA,IAAA,GAAA,KAAA,GAAA,EAAE,EAAE,IAAK,EAAA;AACnC,EAAI,IAAA,CAAC,KAAY,OAAA,MAAA;AACjB,EAAA,IAAI,CAAC,sBAAA,CAAuB,IAAK,CAAA,GAAG,CAAG,EAAA;AACrC,IAAA,IAAI,CAAC,gCAAA,CAAiC,IAAK,CAAA,GAAG,GAAU,OAAA,MAAA;AACxD,IAAA,GAAA,GAAM,WAAW,GAAG,CAAA,CAAA;AAAA;AAEtB,EAAA,IAAI,CAAC,cAAA,CAAe,IAAK,CAAA,GAAG,GAAU,OAAA,MAAA;AACtC,EAAI,IAAA;AACF,IAAM,MAAA,CAAA,GAAI,IAAI,GAAA,CAAI,GAAG,CAAA;AACrB,IAAI,IAAA,CAAC,CAAE,CAAA,QAAA,CAAS,QAAS,CAAA,GAAG,KAAK,CAAE,CAAA,QAAA,IAAY,CAAE,CAAA,QAAA,EAAiB,OAAA,KAAA,CAAA;AAClE,IAAA,OAAO,EAAE,QAAS,EAAA;AAAA,GACZ,CAAA,OAAA,CAAA,EAAA;AACN,IAAO,OAAA,MAAA;AAAA;AAEX;AAGO,SAAS,iBAAiB,KAAiD,EAAA;AAChF,EAAM,MAAA,GAAA,GAAM,sBAAsB,KAAK,CAAA;AACvC,EAAI,IAAA,CAAC,KAAY,OAAA,IAAA;AACjB,EAAM,MAAA,CAAA,GAAI,IAAI,GAAA,CAAI,GAAG,CAAA;AACrB,EAAA,CAAA,CAAE,IAAO,GAAA,EAAA;AACT,EAAA,OAAO,EAAE,QAAS,EAAA;AACpB;AAGgB,SAAA,kBAAA,CAAmB,GAAa,EAAA,QAAA,GAAyB,UAAoB,EAAA;AAC3F,EAAM,MAAA,KAAA,GAAQ,mBAAmB,GAAG,CAAA,mEAAA,CAAA;AACpC,EAAA,OAAO,aAAa,MAAS,GAAA,CAAA,EAAG,KAAK,CAAA,CAAA,EAAI,iBAAiB,CAAK,CAAA,GAAA,KAAA;AACjE"}
@@ -0,0 +1,31 @@
1
+ const PHASES = [{
2
+ kind: "database",
3
+ re: /\b(?:database|postgres(?:ql)?|schema|migrations?)\b/gi,
4
+ title: "Setting up your database"
5
+ }, {
6
+ kind: "auth",
7
+ re: /\b(?:auth(?:entication)?|logins|better auth|sign-in system)\b/gi,
8
+ title: "Setting up logins"
9
+ }];
10
+ const DETAIL = "The preview comes back as soon as it is connected - it can go blank for a moment meanwhile.";
11
+ function setupPhase(streaming) {
12
+ var _a;
13
+ const text = String(streaming != null ? streaming : "").trim();
14
+ if (!text) return null;
15
+ const last = (_a = text.split(/\n\s*\n/).filter((p) => p.trim()).slice(-1)[0]) != null ? _a : "";
16
+ let best = null;
17
+ for (const p of PHASES) {
18
+ for (const m of last.matchAll(p.re)) {
19
+ if (!best || m.index > best.at) best = {
20
+ kind: p.kind,
21
+ title: p.title,
22
+ at: m.index
23
+ };
24
+ }
25
+ }
26
+ return best ? {
27
+ kind: best.kind,
28
+ title: best.title,
29
+ detail: DETAIL
30
+ } : null;
31
+ }export{setupPhase};//# sourceMappingURL=setupPhase.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setupPhase.js","sources":["../../../../../src/features/webbuilder/web/preview/setupPhase.ts"],"sourcesContent":["/** (web c67928e8, 0.17) What the preview says while a turn wires up a database or logins (the dev server restarts, the page goes blank). Pure. */\n\nexport type SetupPhase = { kind: 'database' | 'auth'; title: string; detail: string };\n\nconst PHASES: Array<{ kind: SetupPhase['kind']; re: RegExp; title: string }> = [\n {\n kind: 'database',\n re: /\\b(?:database|postgres(?:ql)?|schema|migrations?)\\b/gi,\n title: 'Setting up your database',\n },\n { kind: 'auth', re: /\\b(?:auth(?:entication)?|logins|better auth|sign-in system)\\b/gi, title: 'Setting up logins' },\n];\n\nconst DETAIL = 'The preview comes back as soon as it is connected - it can go blank for a moment meanwhile.';\n\n/** The phase the AI's newest paragraph is in: the keyword named last wins (\"Database is set up. Now … auth\" is logins). */\nexport function setupPhase(streaming: string | null | undefined): SetupPhase | null {\n const text = String(streaming ?? '').trim();\n if (!text) return null;\n const last =\n text\n .split(/\\n\\s*\\n/)\n .filter((p) => p.trim())\n .slice(-1)[0] ?? '';\n let best: { kind: SetupPhase['kind']; title: string; at: number } | null = null;\n for (const p of PHASES) {\n for (const m of last.matchAll(p.re)) {\n if (!best || m.index > best.at) best = { kind: p.kind, title: p.title, at: m.index };\n }\n }\n return best ? { kind: best.kind, title: best.title, detail: DETAIL } : null;\n}\n"],"names":[],"mappings":"AAOA,MAAM,SAID,CAAC;AAAA,EACJ,IAAM,EAAA,UAAA;AAAA,EACN,EAAI,EAAA,uDAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAG,EAAA;AAAA,EACD,IAAM,EAAA,MAAA;AAAA,EACN,EAAI,EAAA,iEAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAC,CAAA;AACD,MAAM,MAAS,GAAA,6FAAA;AAGR,SAAS,WAAW,SAAyD,EAAA;AAvBpF,EAAA,IAAA,EAAA;AAwBE,EAAA,MAAM,IAAO,GAAA,MAAA,CAAO,SAAa,IAAA,IAAA,GAAA,SAAA,GAAA,EAAE,EAAE,IAAK,EAAA;AAC1C,EAAI,IAAA,CAAC,MAAa,OAAA,IAAA;AAClB,EAAA,MAAM,QAAO,EAAK,GAAA,IAAA,CAAA,KAAA,CAAM,SAAS,CAAA,CAAE,OAAO,CAAK,CAAA,KAAA,CAAA,CAAE,IAAK,EAAC,EAAE,KAAM,CAAA,EAAE,CAAE,CAAA,CAAC,MAAvD,IAA4D,GAAA,EAAA,GAAA,EAAA;AAC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