@easybits.cloud/html-tailwind-generator 0.2.115 → 0.2.117

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.
@@ -3,7 +3,7 @@ import {
3
3
  enrichImages,
4
4
  resolveModel,
5
5
  sanitizeSemanticColors
6
- } from "./chunk-RBZ3YLOZ.js";
6
+ } from "./chunk-VKIIKF4Q.js";
7
7
 
8
8
  // src/refine.ts
9
9
  import { streamText } from "ai";
@@ -168,4 +168,4 @@ export {
168
168
  extractSectionDescription,
169
169
  refineLanding
170
170
  };
171
- //# sourceMappingURL=chunk-CFMB3Q7N.js.map
171
+ //# sourceMappingURL=chunk-O3F4GY2V.js.map
@@ -9,7 +9,7 @@ import {
9
9
  resolveModel,
10
10
  sanitizeSemanticColors,
11
11
  streamGenerate
12
- } from "./chunk-RBZ3YLOZ.js";
12
+ } from "./chunk-VKIIKF4Q.js";
13
13
 
14
14
  // src/generateDocument.ts
15
15
  import { generateObject, streamText } from "ai";
@@ -505,4 +505,4 @@ export {
505
505
  generateDocument,
506
506
  generateDocumentParallel
507
507
  };
508
- //# sourceMappingURL=chunk-RGKK2HBC.js.map
508
+ //# sourceMappingURL=chunk-QF7UX3XK.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  dataUrlToImagePart,
3
3
  streamGenerate
4
- } from "./chunk-RBZ3YLOZ.js";
4
+ } from "./chunk-VKIIKF4Q.js";
5
5
 
6
6
  // src/generate.ts
7
7
  var SYSTEM_PROMPT = `You are a world-class web designer who creates AWARD-WINNING landing pages. Your designs win Awwwards, FWA, and CSS Design Awards. You think in terms of visual hierarchy, whitespace, and emotional impact.
@@ -106,6 +106,20 @@ Generate 7-9 sections. Always start with Hero and end with Footer.
106
106
  IMPORTANT: Make each section VISUALLY UNIQUE \u2014 different layouts, different background colors, different grid structures.
107
107
  Think like a premium design agency creating a $50K landing page.
108
108
  NO generic Bootstrap layouts. Use creative grids, bento layouts, overlapping elements, asymmetric columns.`;
109
+ function buildPromptSuffix(userPrompt) {
110
+ const countMatch = userPrompt.match(/(\d+)\s*(?:secciones?|sections?|bloques?|blocks?|partes?|pages?)/i) || userPrompt.match(/(?:genera|generar|crea|crear|haz|hazme|dame|quiero)\s*(\d+)/i);
111
+ const count = countMatch ? parseInt(countMatch[1] || countMatch[2] || "0") : 0;
112
+ const sectionInstruction = count > 0 ? `Generate EXACTLY ${count} sections (no more, no less). Always include Hero as first and Footer as last.` : `Generate 7-9 sections. Always start with Hero and end with Footer.`;
113
+ return `
114
+
115
+ OUTPUT FORMAT: NDJSON \u2014 one JSON object per line, NO wrapper array, NO markdown fences.
116
+ Each line: {"label": "Short Label", "html": "<section>...</section>"}
117
+
118
+ ${sectionInstruction}
119
+ IMPORTANT: Make each section VISUALLY UNIQUE \u2014 different layouts, different background colors, different grid structures.
120
+ Think like a premium design agency creating a $50K landing page.
121
+ NO generic Bootstrap layouts. Use creative grids, bento layouts, overlapping elements, asymmetric columns.`;
122
+ }
109
123
  var THEME_DESCRIPTIONS = {
110
124
  minimal: "Clean, light, professional \u2014 white surfaces, subtle grays, minimal decoration",
111
125
  calido: "Warm tones \u2014 amber/orange primary, cream surfaces, cozy and inviting feel",
@@ -161,12 +175,12 @@ Additional instructions: ${extraInstructions}` : "";
161
175
  type: "text",
162
176
  text: `Generate a landing page for: ${prompt}${extra}
163
177
 
164
- IMPORTANT: Use the reference image as a DIRECT visual guide. Replicate its layout structure, grid arrangement, spacing, visual hierarchy, and section organization as closely as possible. Match the number of columns, element positioning, and overall composition. Adapt the content to the prompt but keep the visual DNA of the reference.${PROMPT_SUFFIX}`
178
+ IMPORTANT: Use the reference image as a DIRECT visual guide. Replicate its layout structure, grid arrangement, spacing, visual hierarchy, and section organization as closely as possible. Match the number of columns, element positioning, and overall composition. Adapt the content to the prompt but keep the visual DNA of the reference.${buildPromptSuffix(prompt)}`
165
179
  });
166
180
  } else {
167
181
  content.push({
168
182
  type: "text",
169
- text: `Generate a landing page for: ${prompt}${extra}${PROMPT_SUFFIX}`
183
+ text: `Generate a landing page for: ${prompt}${extra}${buildPromptSuffix(prompt)}`
170
184
  });
171
185
  }
172
186
  return streamGenerate({
@@ -181,4 +195,4 @@ export {
181
195
  PROMPT_SUFFIX,
182
196
  generateLanding
183
197
  };
184
- //# sourceMappingURL=chunk-KBO6XLYA.js.map
198
+ //# sourceMappingURL=chunk-RUOBAHYV.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/generate.ts"],"sourcesContent":["import { streamGenerate, dataUrlToImagePart, extractJsonObjects } from \"./streamCore\";\nimport type { Section3 } from \"./types\";\n\nexport { extractJsonObjects };\n\nexport const SYSTEM_PROMPT = `You are a world-class web designer who creates AWARD-WINNING landing pages. Your designs win Awwwards, FWA, and CSS Design Awards. You think in terms of visual hierarchy, whitespace, and emotional impact.\n\nRULES:\n- Each section is a complete <section> tag with Tailwind CSS classes\n- Use Tailwind CDN classes ONLY (no custom CSS, no @apply, no @import, no @tailwind directives)\n- NO JavaScript, only HTML+Tailwind\n- Each section must be independent and self-contained\n- Responsive: mobile-first with sm/md/lg/xl breakpoints\n- All text content in Spanish unless the prompt specifies otherwise\n- Use real-looking content (not Lorem ipsum) — make it specific to the prompt\n\nRESPONSIVE — MANDATORY:\n- EVERY grid: grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 (NEVER grid-cols-3 alone)\n- EVERY flex row: flex flex-col md:flex-row (NEVER flex flex-row alone)\n- Text sizes: text-3xl md:text-5xl lg:text-7xl (NEVER text-7xl alone)\n- Images: w-full h-auto object-cover max-w-full\n- Padding: px-4 md:px-8 lg:px-16 (NEVER px-16 alone)\n- Hide decorative on mobile if breaks layout: hidden md:block\n\nIMAGES — CRITICAL:\n- EVERY image MUST use: <img data-image-query=\"english search query\" alt=\"description\" class=\"w-full h-auto object-cover rounded-xl\"/>\n- NEVER use <img> without data-image-query\n- NEVER include a src attribute — the system auto-replaces data-image-query with a real image URL\n- Queries must be generic stock-photo friendly (e.g. \"modern office\" not \"Juan's cybercafe\")\n- For avatar-like elements, use colored divs with initials instead of img tags (e.g. <div class=\"w-10 h-10 rounded-full bg-primary flex items-center justify-center text-on-primary font-bold\">JD</div>)\n\nIMAGE OVERLAYS — CRITICAL:\n- When using images as backgrounds or behind text, ALWAYS add a gradient overlay for text readability\n- Pattern: <div class=\"relative\"><img data-image-query=\"...\" alt=\"...\" class=\"absolute inset-0 w-full h-full object-cover\"/><div class=\"absolute inset-0 bg-gradient-to-r from-primary/80 to-transparent\"></div><div class=\"relative z-10\">...text...</div></div>\n- NEVER place text directly on images without an overlay\n- For hero sections with background images: use bg-gradient-to-t from-primary-dark/90 via-primary-dark/50 to-transparent\n- For testimonial/quote backgrounds: use bg-surface/90 backdrop-blur-sm on the card\n\nCOLOR SYSTEM — CRITICAL (READ CAREFULLY):\n- Use semantic color classes: bg-primary, text-primary, bg-primary-light, bg-primary-dark, text-on-primary, bg-surface, bg-surface-alt, text-on-surface, text-on-surface-muted, bg-secondary, text-secondary, bg-accent, text-accent\n- NEVER use hardcoded Tailwind color classes: NO bg-gray-*, bg-black, bg-white, bg-indigo-*, bg-blue-*, bg-purple-*, text-gray-*, text-black, text-white, etc.\n- The ONLY exception: border-gray-200 or border-gray-700 for subtle dividers.\n- ALL backgrounds MUST use: bg-primary, bg-primary-dark, bg-surface, bg-surface-alt\n- ALL text MUST use: text-on-surface, text-on-surface-muted, text-on-primary, text-accent. Use text-primary ONLY on bg-surface/bg-surface-alt (it's the same hue as bg-primary — invisible on primary backgrounds).\n- CONTRAST RULE: on bg-primary or bg-primary-dark → use ONLY text-on-primary. On bg-surface or bg-surface-alt → use text-on-surface, text-on-surface-muted, or text-primary. NEVER use text-primary on bg-primary — they are the SAME COLOR. NEVER put text-on-surface on bg-primary or text-on-primary on bg-surface. text-accent is decorative — use sparingly on bg-surface/bg-surface-alt only.\n- ANTI-PATTERN: NEVER put bg-primary on BOTH the section AND elements inside it. If section is bg-primary, inner cards/elements should be bg-surface. If section is bg-surface, cards can use bg-surface-alt or bg-primary.\n- For gradients: from-primary to-primary-dark, from-surface to-surface-alt\n- For hover: hover:bg-primary-dark, hover:bg-primary-light\n\nCOLOR VARIETY — MANDATORY:\n- ALTERNATE section backgrounds: bg-surface → bg-primary → bg-surface-alt → bg-primary-dark → bg-surface\n- Use bg-accent for at least ONE section (CTA or highlight section)\n- Use bg-secondary for at least ONE section (features or stats)\n- Cards on dark sections (bg-primary, bg-primary-dark) MUST be bg-surface (light cards on dark bg = visual pop)\n- Cards on light sections (bg-surface) can use bg-surface-alt or bg-primary-light\n- Use text-accent for decorative elements: labels, badges, icons, highlights, underlines\n- Use text-secondary for secondary information, tags, category labels\n- Gradients: mix colors creatively — from-primary to-accent for CTAs, from-secondary to-primary for headers\n- Buttons: primary CTA = bg-accent text-on-accent, secondary CTA = bg-secondary text-on-secondary or border-primary\n\nDESIGN PHILOSOPHY — what separates good from GREAT:\n- WHITESPACE is your best friend. Generous padding (py-24, py-32, px-8). Let elements breathe.\n- CONTRAST: mix dark sections with light ones. Alternate bg-primary and bg-surface sections.\n- TYPOGRAPHY: use extreme size differences for hierarchy (text-7xl headline next to text-sm label)\n- DEPTH: overlapping elements, negative margins (-mt-12), z-index layering, shadows\n- ASYMMETRY: avoid centering everything. Use grid-cols-5 with col-span-3 + col-span-2. Offset elements.\n- TEXTURE: use subtle patterns, gradients, border treatments, rounded-3xl mixed with sharp edges\n- Each section should have a COMPLETELY DIFFERENT layout from the others\n\nSECTION LAYOUT — CRITICAL:\n- Each <section> must be full-width (bg goes edge-to-edge). NO max-w on the section itself.\n- Constrain content inside with a wrapper div: <section class=\"bg-primary py-24\"><div class=\"max-w-7xl mx-auto px-4 md:px-8\">...content...</div></section>\n- EVERY section follows this pattern. The <section> handles bg color + vertical padding. The inner <div> handles horizontal padding + max-width.\n\nTESTIMONIALS SECTION:\n- Cards MUST use bg-surface or bg-surface-alt with text-on-surface\n- If section bg is bg-primary or bg-primary-dark, cards MUST be bg-surface (light cards on dark bg)\n- Quote text: text-on-surface, italic\n- Avatar: colored div with initials (bg-accent text-on-primary or bg-primary-light text-on-primary)\n- Name: text-on-surface font-semibold. Role/company: text-on-surface-muted\n- NEVER use same dark bg for both section AND cards\n\nHERO SECTION — your masterpiece:\n- Use a 2-column grid (lg:grid-cols-2) that fills the full height, NOT content floating in empty space\n- Left column: headline + description + CTAs, vertically centered with flex flex-col justify-center\n- Right column: large hero image (data-image-query) filling the column, or a bento-grid of image + stat cards\n- Bold oversized headline (text-4xl md:text-6xl lg:text-7xl font-black leading-tight)\n- Tag/label above headline (uppercase, tracking-wider, text-xs text-accent)\n- Short description paragraph (text-lg text-on-surface-muted, max-w-lg)\n- 2 CTAs: primary (large, px-8 py-4, with → arrow) + secondary (ghost/outlined)\n- Optional: social proof bar below CTAs (avatar stack + \"2,847+ users\" text)\n- Min height: min-h-[90vh] with items-center on the grid so content is vertically centered\n- CRITICAL: the grid must stretch to fill the section height. Use min-h-[90vh] on the grid container itself, not just the section\n- NEVER leave large empty areas — if using min-h-[90vh], content must be centered/distributed within it\n\nTAILWIND v3 NOTES:\n- Standard Tailwind v3 classes (shadow-sm, shadow-md, rounded-md, etc.)\n- Borders: border + border-gray-200 for visible borders`;\n\nexport const PROMPT_SUFFIX = `\n\nOUTPUT FORMAT: NDJSON — one JSON object per line, NO wrapper array, NO markdown fences.\nEach line: {\"label\": \"Short Label\", \"html\": \"<section>...</section>\"}\n\nGenerate 7-9 sections. Always start with Hero and end with Footer.\nIMPORTANT: Make each section VISUALLY UNIQUE — different layouts, different background colors, different grid structures.\nThink like a premium design agency creating a $50K landing page.\nNO generic Bootstrap layouts. Use creative grids, bento layouts, overlapping elements, asymmetric columns.`;\n\nexport interface GenerateOptions {\n anthropicApiKey?: string;\n openaiApiKey?: string;\n prompt: string;\n referenceImage?: string;\n extraInstructions?: string;\n systemPrompt?: string;\n model?: string;\n pexelsApiKey?: string;\n persistImage?: (tempUrl: string, query: string) => Promise<string>;\n onSection?: (section: Section3) => void;\n onImageUpdate?: (sectionId: string, html: string) => void;\n onDone?: (sections: Section3[]) => void;\n onError?: (error: Error) => void;\n /** Theme colors to inject into the AI prompt (deprecated — use themeName) */\n themeColors?: Record<string, string>;\n /** Theme name (e.g. \"minimal\", \"noche\", \"oceano\") — tells the AI the design mood */\n themeName?: string;\n /** Brand kit info for AI context */\n brandKit?: {\n fonts?: { heading?: string; body?: string };\n mood?: string;\n logoUrl?: string;\n };\n}\n\n/**\n * Generate a landing page with streaming AI + image enrichment.\n */\nconst THEME_DESCRIPTIONS: Record<string, string> = {\n minimal: \"Clean, light, professional — white surfaces, subtle grays, minimal decoration\",\n calido: \"Warm tones — amber/orange primary, cream surfaces, cozy and inviting feel\",\n oceano: \"Cool blue tones — deep ocean blues, clean white surfaces, professional and fresh\",\n noche: \"DARK theme — very dark surfaces, purple/violet accents, moody and modern. Surfaces are dark, text is light.\",\n bosque: \"Nature-inspired — deep green primary, warm earth tones, organic and grounded\",\n rosa: \"Soft pink/rose tones — delicate, feminine, elegant with light surfaces\",\n};\n\nfunction buildVisualContext(themeName?: string, brandKit?: GenerateOptions[\"brandKit\"]): string {\n if (!themeName && !brandKit) return \"\";\n\n const lines: string[] = [\"\\n\\n## Visual Context — MANDATORY\"];\n\n if (themeName && themeName !== \"custom\") {\n const desc = THEME_DESCRIPTIONS[themeName] || themeName;\n lines.push(`Active theme: \"${themeName}\" — ${desc}`);\n lines.push(\"The CSS variables for this theme are already loaded. Just use the semantic classes (bg-primary, text-on-surface, bg-accent, etc.) as described in the COLOR SYSTEM above. The theme handles the actual color values.\");\n }\n\n if (brandKit?.fonts) {\n const { heading, body } = brandKit.fonts;\n if (heading) lines.push(`- Heading font: use font-family: '${heading}' via inline style on h1-h6`);\n if (body) lines.push(`- Body font: use font-family: '${body}' via inline style on p, li, span`);\n }\n\n if (brandKit?.mood) {\n lines.push(`- Design mood: ${brandKit.mood} — adapt spacing, imagery style, and visual weight to match this mood`);\n }\n\n if (brandKit?.logoUrl) {\n lines.push(`- Brand logo: include <img src=\"${brandKit.logoUrl}\" alt=\"Logo\" class=\"h-8 w-auto\" /> in the navbar/hero area`);\n }\n\n return lines.join(\"\\n\");\n}\n\nexport async function generateLanding(options: GenerateOptions): Promise<Section3[]> {\n const {\n prompt,\n referenceImage,\n extraInstructions,\n systemPrompt = SYSTEM_PROMPT,\n themeColors: _themeColors,\n themeName,\n brandKit,\n ...rest\n } = options;\n\n const visualContext = buildVisualContext(themeName, brandKit);\n const extra = extraInstructions ? `\\nAdditional instructions: ${extraInstructions}` : \"\";\n const content: any[] = [];\n\n if (referenceImage) {\n const converted = dataUrlToImagePart(referenceImage);\n if (converted) {\n content.push({ type: \"image\", ...converted });\n } else {\n content.push({ type: \"image\", image: referenceImage });\n }\n content.push({\n type: \"text\",\n text: `Generate a landing page for: ${prompt}${extra}\\n\\nIMPORTANT: Use the reference image as a DIRECT visual guide. Replicate its layout structure, grid arrangement, spacing, visual hierarchy, and section organization as closely as possible. Match the number of columns, element positioning, and overall composition. Adapt the content to the prompt but keep the visual DNA of the reference.${PROMPT_SUFFIX}`,\n });\n } else {\n content.push({\n type: \"text\",\n text: `Generate a landing page for: ${prompt}${extra}${PROMPT_SUFFIX}`,\n });\n }\n\n return streamGenerate({\n ...rest,\n systemPrompt: systemPrompt + visualContext,\n userContent: content,\n });\n}\n"],"mappings":";;;;;;AAKO,IAAM,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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AAM,QAAQ,oBAAoB;AAAA,2BAA8B,iBAAiB,KAAK;AACtF,QAAM,UAAiB,CAAC;AAExB,MAAI,gBAAgB;AAClB,UAAM,YAAY,mBAAmB,cAAc;AACnD,QAAI,WAAW;AACb,cAAQ,KAAK,EAAE,MAAM,SAAS,GAAG,UAAU,CAAC;AAAA,IAC9C,OAAO;AACL,cAAQ,KAAK,EAAE,MAAM,SAAS,OAAO,eAAe,CAAC;AAAA,IACvD;AACA,YAAQ,KAAK;AAAA,MACX,MAAM;AAAA,MACN,MAAM,gCAAgC,MAAM,GAAG,KAAK;AAAA;AAAA,iVAAsV,aAAa;AAAA,IACzZ,CAAC;AAAA,EACH,OAAO;AACL,YAAQ,KAAK;AAAA,MACX,MAAM;AAAA,MACN,MAAM,gCAAgC,MAAM,GAAG,KAAK,GAAG,aAAa;AAAA,IACtE,CAAC;AAAA,EACH;AAEA,SAAO,eAAe;AAAA,IACpB,GAAG;AAAA,IACH,cAAc,eAAe;AAAA,IAC7B,aAAa;AAAA,EACf,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../src/generate.ts"],"sourcesContent":["import { streamGenerate, dataUrlToImagePart, extractJsonObjects } from \"./streamCore\";\nimport type { Section3 } from \"./types\";\n\nexport { extractJsonObjects };\n\nexport const SYSTEM_PROMPT = `You are a world-class web designer who creates AWARD-WINNING landing pages. Your designs win Awwwards, FWA, and CSS Design Awards. You think in terms of visual hierarchy, whitespace, and emotional impact.\n\nRULES:\n- Each section is a complete <section> tag with Tailwind CSS classes\n- Use Tailwind CDN classes ONLY (no custom CSS, no @apply, no @import, no @tailwind directives)\n- NO JavaScript, only HTML+Tailwind\n- Each section must be independent and self-contained\n- Responsive: mobile-first with sm/md/lg/xl breakpoints\n- All text content in Spanish unless the prompt specifies otherwise\n- Use real-looking content (not Lorem ipsum) — make it specific to the prompt\n\nRESPONSIVE — MANDATORY:\n- EVERY grid: grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 (NEVER grid-cols-3 alone)\n- EVERY flex row: flex flex-col md:flex-row (NEVER flex flex-row alone)\n- Text sizes: text-3xl md:text-5xl lg:text-7xl (NEVER text-7xl alone)\n- Images: w-full h-auto object-cover max-w-full\n- Padding: px-4 md:px-8 lg:px-16 (NEVER px-16 alone)\n- Hide decorative on mobile if breaks layout: hidden md:block\n\nIMAGES — CRITICAL:\n- EVERY image MUST use: <img data-image-query=\"english search query\" alt=\"description\" class=\"w-full h-auto object-cover rounded-xl\"/>\n- NEVER use <img> without data-image-query\n- NEVER include a src attribute — the system auto-replaces data-image-query with a real image URL\n- Queries must be generic stock-photo friendly (e.g. \"modern office\" not \"Juan's cybercafe\")\n- For avatar-like elements, use colored divs with initials instead of img tags (e.g. <div class=\"w-10 h-10 rounded-full bg-primary flex items-center justify-center text-on-primary font-bold\">JD</div>)\n\nIMAGE OVERLAYS — CRITICAL:\n- When using images as backgrounds or behind text, ALWAYS add a gradient overlay for text readability\n- Pattern: <div class=\"relative\"><img data-image-query=\"...\" alt=\"...\" class=\"absolute inset-0 w-full h-full object-cover\"/><div class=\"absolute inset-0 bg-gradient-to-r from-primary/80 to-transparent\"></div><div class=\"relative z-10\">...text...</div></div>\n- NEVER place text directly on images without an overlay\n- For hero sections with background images: use bg-gradient-to-t from-primary-dark/90 via-primary-dark/50 to-transparent\n- For testimonial/quote backgrounds: use bg-surface/90 backdrop-blur-sm on the card\n\nCOLOR SYSTEM — CRITICAL (READ CAREFULLY):\n- Use semantic color classes: bg-primary, text-primary, bg-primary-light, bg-primary-dark, text-on-primary, bg-surface, bg-surface-alt, text-on-surface, text-on-surface-muted, bg-secondary, text-secondary, bg-accent, text-accent\n- NEVER use hardcoded Tailwind color classes: NO bg-gray-*, bg-black, bg-white, bg-indigo-*, bg-blue-*, bg-purple-*, text-gray-*, text-black, text-white, etc.\n- The ONLY exception: border-gray-200 or border-gray-700 for subtle dividers.\n- ALL backgrounds MUST use: bg-primary, bg-primary-dark, bg-surface, bg-surface-alt\n- ALL text MUST use: text-on-surface, text-on-surface-muted, text-on-primary, text-accent. Use text-primary ONLY on bg-surface/bg-surface-alt (it's the same hue as bg-primary — invisible on primary backgrounds).\n- CONTRAST RULE: on bg-primary or bg-primary-dark → use ONLY text-on-primary. On bg-surface or bg-surface-alt → use text-on-surface, text-on-surface-muted, or text-primary. NEVER use text-primary on bg-primary — they are the SAME COLOR. NEVER put text-on-surface on bg-primary or text-on-primary on bg-surface. text-accent is decorative — use sparingly on bg-surface/bg-surface-alt only.\n- ANTI-PATTERN: NEVER put bg-primary on BOTH the section AND elements inside it. If section is bg-primary, inner cards/elements should be bg-surface. If section is bg-surface, cards can use bg-surface-alt or bg-primary.\n- For gradients: from-primary to-primary-dark, from-surface to-surface-alt\n- For hover: hover:bg-primary-dark, hover:bg-primary-light\n\nCOLOR VARIETY — MANDATORY:\n- ALTERNATE section backgrounds: bg-surface → bg-primary → bg-surface-alt → bg-primary-dark → bg-surface\n- Use bg-accent for at least ONE section (CTA or highlight section)\n- Use bg-secondary for at least ONE section (features or stats)\n- Cards on dark sections (bg-primary, bg-primary-dark) MUST be bg-surface (light cards on dark bg = visual pop)\n- Cards on light sections (bg-surface) can use bg-surface-alt or bg-primary-light\n- Use text-accent for decorative elements: labels, badges, icons, highlights, underlines\n- Use text-secondary for secondary information, tags, category labels\n- Gradients: mix colors creatively — from-primary to-accent for CTAs, from-secondary to-primary for headers\n- Buttons: primary CTA = bg-accent text-on-accent, secondary CTA = bg-secondary text-on-secondary or border-primary\n\nDESIGN PHILOSOPHY — what separates good from GREAT:\n- WHITESPACE is your best friend. Generous padding (py-24, py-32, px-8). Let elements breathe.\n- CONTRAST: mix dark sections with light ones. Alternate bg-primary and bg-surface sections.\n- TYPOGRAPHY: use extreme size differences for hierarchy (text-7xl headline next to text-sm label)\n- DEPTH: overlapping elements, negative margins (-mt-12), z-index layering, shadows\n- ASYMMETRY: avoid centering everything. Use grid-cols-5 with col-span-3 + col-span-2. Offset elements.\n- TEXTURE: use subtle patterns, gradients, border treatments, rounded-3xl mixed with sharp edges\n- Each section should have a COMPLETELY DIFFERENT layout from the others\n\nSECTION LAYOUT — CRITICAL:\n- Each <section> must be full-width (bg goes edge-to-edge). NO max-w on the section itself.\n- Constrain content inside with a wrapper div: <section class=\"bg-primary py-24\"><div class=\"max-w-7xl mx-auto px-4 md:px-8\">...content...</div></section>\n- EVERY section follows this pattern. The <section> handles bg color + vertical padding. The inner <div> handles horizontal padding + max-width.\n\nTESTIMONIALS SECTION:\n- Cards MUST use bg-surface or bg-surface-alt with text-on-surface\n- If section bg is bg-primary or bg-primary-dark, cards MUST be bg-surface (light cards on dark bg)\n- Quote text: text-on-surface, italic\n- Avatar: colored div with initials (bg-accent text-on-primary or bg-primary-light text-on-primary)\n- Name: text-on-surface font-semibold. Role/company: text-on-surface-muted\n- NEVER use same dark bg for both section AND cards\n\nHERO SECTION — your masterpiece:\n- Use a 2-column grid (lg:grid-cols-2) that fills the full height, NOT content floating in empty space\n- Left column: headline + description + CTAs, vertically centered with flex flex-col justify-center\n- Right column: large hero image (data-image-query) filling the column, or a bento-grid of image + stat cards\n- Bold oversized headline (text-4xl md:text-6xl lg:text-7xl font-black leading-tight)\n- Tag/label above headline (uppercase, tracking-wider, text-xs text-accent)\n- Short description paragraph (text-lg text-on-surface-muted, max-w-lg)\n- 2 CTAs: primary (large, px-8 py-4, with → arrow) + secondary (ghost/outlined)\n- Optional: social proof bar below CTAs (avatar stack + \"2,847+ users\" text)\n- Min height: min-h-[90vh] with items-center on the grid so content is vertically centered\n- CRITICAL: the grid must stretch to fill the section height. Use min-h-[90vh] on the grid container itself, not just the section\n- NEVER leave large empty areas — if using min-h-[90vh], content must be centered/distributed within it\n\nTAILWIND v3 NOTES:\n- Standard Tailwind v3 classes (shadow-sm, shadow-md, rounded-md, etc.)\n- Borders: border + border-gray-200 for visible borders`;\n\n/** @deprecated Use buildPromptSuffix(prompt) internally. Kept for backward compat. */\nexport const PROMPT_SUFFIX = `\n\nOUTPUT FORMAT: NDJSON — one JSON object per line, NO wrapper array, NO markdown fences.\nEach line: {\"label\": \"Short Label\", \"html\": \"<section>...</section>\"}\n\nGenerate 7-9 sections. Always start with Hero and end with Footer.\nIMPORTANT: Make each section VISUALLY UNIQUE — different layouts, different background colors, different grid structures.\nThink like a premium design agency creating a $50K landing page.\nNO generic Bootstrap layouts. Use creative grids, bento layouts, overlapping elements, asymmetric columns.`;\n\nfunction buildPromptSuffix(userPrompt: string): string {\n // Extract section count from user prompt (e.g. \"3 secciones\", \"2 sections\", \"dame 4\")\n const countMatch = userPrompt.match(/(\\d+)\\s*(?:secciones?|sections?|bloques?|blocks?|partes?|pages?)/i)\n || userPrompt.match(/(?:genera|generar|crea|crear|haz|hazme|dame|quiero)\\s*(\\d+)/i);\n const count = countMatch ? parseInt(countMatch[1] || countMatch[2] || \"0\") : 0;\n const sectionInstruction = count > 0\n ? `Generate EXACTLY ${count} sections (no more, no less). Always include Hero as first and Footer as last.`\n : `Generate 7-9 sections. Always start with Hero and end with Footer.`;\n\n return `\n\nOUTPUT FORMAT: NDJSON — one JSON object per line, NO wrapper array, NO markdown fences.\nEach line: {\"label\": \"Short Label\", \"html\": \"<section>...</section>\"}\n\n${sectionInstruction}\nIMPORTANT: Make each section VISUALLY UNIQUE — different layouts, different background colors, different grid structures.\nThink like a premium design agency creating a $50K landing page.\nNO generic Bootstrap layouts. Use creative grids, bento layouts, overlapping elements, asymmetric columns.`;\n}\n\nexport interface GenerateOptions {\n anthropicApiKey?: string;\n openaiApiKey?: string;\n prompt: string;\n referenceImage?: string;\n extraInstructions?: string;\n systemPrompt?: string;\n model?: string;\n pexelsApiKey?: string;\n persistImage?: (tempUrl: string, query: string) => Promise<string>;\n onSection?: (section: Section3) => void;\n onImageUpdate?: (sectionId: string, html: string) => void;\n onDone?: (sections: Section3[]) => void;\n onError?: (error: Error) => void;\n /** Theme colors to inject into the AI prompt (deprecated — use themeName) */\n themeColors?: Record<string, string>;\n /** Theme name (e.g. \"minimal\", \"noche\", \"oceano\") — tells the AI the design mood */\n themeName?: string;\n /** Brand kit info for AI context */\n brandKit?: {\n fonts?: { heading?: string; body?: string };\n mood?: string;\n logoUrl?: string;\n };\n}\n\n/**\n * Generate a landing page with streaming AI + image enrichment.\n */\nconst THEME_DESCRIPTIONS: Record<string, string> = {\n minimal: \"Clean, light, professional — white surfaces, subtle grays, minimal decoration\",\n calido: \"Warm tones — amber/orange primary, cream surfaces, cozy and inviting feel\",\n oceano: \"Cool blue tones — deep ocean blues, clean white surfaces, professional and fresh\",\n noche: \"DARK theme — very dark surfaces, purple/violet accents, moody and modern. Surfaces are dark, text is light.\",\n bosque: \"Nature-inspired — deep green primary, warm earth tones, organic and grounded\",\n rosa: \"Soft pink/rose tones — delicate, feminine, elegant with light surfaces\",\n};\n\nfunction buildVisualContext(themeName?: string, brandKit?: GenerateOptions[\"brandKit\"]): string {\n if (!themeName && !brandKit) return \"\";\n\n const lines: string[] = [\"\\n\\n## Visual Context — MANDATORY\"];\n\n if (themeName && themeName !== \"custom\") {\n const desc = THEME_DESCRIPTIONS[themeName] || themeName;\n lines.push(`Active theme: \"${themeName}\" — ${desc}`);\n lines.push(\"The CSS variables for this theme are already loaded. Just use the semantic classes (bg-primary, text-on-surface, bg-accent, etc.) as described in the COLOR SYSTEM above. The theme handles the actual color values.\");\n }\n\n if (brandKit?.fonts) {\n const { heading, body } = brandKit.fonts;\n if (heading) lines.push(`- Heading font: use font-family: '${heading}' via inline style on h1-h6`);\n if (body) lines.push(`- Body font: use font-family: '${body}' via inline style on p, li, span`);\n }\n\n if (brandKit?.mood) {\n lines.push(`- Design mood: ${brandKit.mood} — adapt spacing, imagery style, and visual weight to match this mood`);\n }\n\n if (brandKit?.logoUrl) {\n lines.push(`- Brand logo: include <img src=\"${brandKit.logoUrl}\" alt=\"Logo\" class=\"h-8 w-auto\" /> in the navbar/hero area`);\n }\n\n return lines.join(\"\\n\");\n}\n\nexport async function generateLanding(options: GenerateOptions): Promise<Section3[]> {\n const {\n prompt,\n referenceImage,\n extraInstructions,\n systemPrompt = SYSTEM_PROMPT,\n themeColors: _themeColors,\n themeName,\n brandKit,\n ...rest\n } = options;\n\n const visualContext = buildVisualContext(themeName, brandKit);\n const extra = extraInstructions ? `\\nAdditional instructions: ${extraInstructions}` : \"\";\n const content: any[] = [];\n\n if (referenceImage) {\n const converted = dataUrlToImagePart(referenceImage);\n if (converted) {\n content.push({ type: \"image\", ...converted });\n } else {\n content.push({ type: \"image\", image: referenceImage });\n }\n content.push({\n type: \"text\",\n text: `Generate a landing page for: ${prompt}${extra}\\n\\nIMPORTANT: Use the reference image as a DIRECT visual guide. Replicate its layout structure, grid arrangement, spacing, visual hierarchy, and section organization as closely as possible. Match the number of columns, element positioning, and overall composition. Adapt the content to the prompt but keep the visual DNA of the reference.${buildPromptSuffix(prompt)}`,\n });\n } else {\n content.push({\n type: \"text\",\n text: `Generate a landing page for: ${prompt}${extra}${buildPromptSuffix(prompt)}`,\n });\n }\n\n return streamGenerate({\n ...rest,\n systemPrompt: systemPrompt + visualContext,\n userContent: content,\n });\n}\n"],"mappings":";;;;;;AAKO,IAAM,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA+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,IACA;AAAA,IACA;AAAA,IACA,eAAe;AAAA,IACf,aAAa;AAAA,IACb;AAAA,IACA;AAAA,IACA,GAAG;AAAA,EACL,IAAI;AAEJ,QAAM,gBAAgB,mBAAmB,WAAW,QAAQ;AAC5D,QAAM,QAAQ,oBAAoB;AAAA,2BAA8B,iBAAiB,KAAK;AACtF,QAAM,UAAiB,CAAC;AAExB,MAAI,gBAAgB;AAClB,UAAM,YAAY,mBAAmB,cAAc;AACnD,QAAI,WAAW;AACb,cAAQ,KAAK,EAAE,MAAM,SAAS,GAAG,UAAU,CAAC;AAAA,IAC9C,OAAO;AACL,cAAQ,KAAK,EAAE,MAAM,SAAS,OAAO,eAAe,CAAC;AAAA,IACvD;AACA,YAAQ,KAAK;AAAA,MACX,MAAM;AAAA,MACN,MAAM,gCAAgC,MAAM,GAAG,KAAK;AAAA;AAAA,iVAAsV,kBAAkB,MAAM,CAAC;AAAA,IACra,CAAC;AAAA,EACH,OAAO;AACL,YAAQ,KAAK;AAAA,MACX,MAAM;AAAA,MACN,MAAM,gCAAgC,MAAM,GAAG,KAAK,GAAG,kBAAkB,MAAM,CAAC;AAAA,IAClF,CAAC;AAAA,EACH;AAEA,SAAO,eAAe;AAAA,IACpB,GAAG;AAAA,IACH,cAAc,eAAe;AAAA,IAC7B,aAAa;AAAA,EACf,CAAC;AACH;","names":[]}
@@ -206,7 +206,39 @@ function categorize(color) {
206
206
  if (new RegExp(`^(?:${ACCENT_COLORS})$`).test(color)) return "accent";
207
207
  return "primary";
208
208
  }
209
- function buildReplacements() {
209
+ var NEUTRALS = "slate|gray|zinc|neutral|stone";
210
+ var neutralReplacements = [
211
+ // bg-white → bg-surface
212
+ [/\bbg-white\b/g, "bg-surface"],
213
+ // bg-black → bg-primary-dark
214
+ [/\bbg-black\b/g, "bg-primary-dark"],
215
+ // text-white → text-on-primary
216
+ [/\btext-white\b/g, "text-on-primary"],
217
+ // text-black → text-on-surface
218
+ [/\btext-black\b/g, "text-on-surface"],
219
+ // bg-gray-50/100 → bg-surface
220
+ [new RegExp(`\\bbg-(${NEUTRALS})-(50|100)\\b`, "g"), "bg-surface"],
221
+ // bg-gray-200/300 → bg-surface-alt
222
+ [new RegExp(`\\bbg-(${NEUTRALS})-(200|300)\\b`, "g"), "bg-surface-alt"],
223
+ // bg-gray-400-600 → bg-primary
224
+ [new RegExp(`\\bbg-(${NEUTRALS})-(400|500|600)\\b`, "g"), "bg-primary"],
225
+ // bg-gray-700-950 → bg-primary-dark
226
+ [new RegExp(`\\bbg-(${NEUTRALS})-(700|800|900|950)\\b`, "g"), "bg-primary-dark"],
227
+ // text-gray-300/400 → text-on-surface-muted
228
+ [new RegExp(`\\btext-(${NEUTRALS})-(300|400)\\b`, "g"), "text-on-surface-muted"],
229
+ // text-gray-500/600 → text-on-surface-muted
230
+ [new RegExp(`\\btext-(${NEUTRALS})-(500|600)\\b`, "g"), "text-on-surface-muted"],
231
+ // text-gray-700/800/900 → text-on-surface
232
+ [new RegExp(`\\btext-(${NEUTRALS})-(700|800|900|950)\\b`, "g"), "text-on-surface"],
233
+ // text-gray-50/100/200 → text-on-primary
234
+ [new RegExp(`\\btext-(${NEUTRALS})-(50|100|200)\\b`, "g"), "text-on-primary"],
235
+ // hover:bg-gray → hover semantic
236
+ [new RegExp(`\\bhover:bg-(${NEUTRALS})-(50|100|200|300)\\b`, "g"), "hover:bg-surface-alt"],
237
+ [new RegExp(`\\bhover:bg-(${NEUTRALS})-(400|500|600|700|800|900|950)\\b`, "g"), "hover:bg-primary-dark"],
238
+ // hover:text neutrals
239
+ [new RegExp(`\\bhover:text-(${NEUTRALS})-\\d{2,3}\\b`, "g"), "hover:text-on-surface"]
240
+ ];
241
+ function buildChromaticReplacements() {
210
242
  const re = (prefix, shades) => new RegExp(`\\b${prefix}-(${COLORS})-(${shades})\\b`, "g");
211
243
  return [
212
244
  // Background
@@ -247,10 +279,13 @@ function buildReplacements() {
247
279
  [re("accent", "\\d{2,3}"), (_m, c) => `accent-${categorize(c)}`]
248
280
  ];
249
281
  }
250
- var replacements = buildReplacements();
282
+ var chromaticReplacements = buildChromaticReplacements();
251
283
  function sanitizeSemanticColors(html) {
252
284
  let result = html;
253
- for (const [pattern, replacer] of replacements) {
285
+ for (const [pattern, replacement] of neutralReplacements) {
286
+ result = result.replace(pattern, replacement);
287
+ }
288
+ for (const [pattern, replacer] of chromaticReplacements) {
254
289
  result = result.replace(pattern, replacer);
255
290
  }
256
291
  return result;
@@ -677,4 +712,4 @@ export {
677
712
  enrichSectionSvgCharts,
678
713
  streamGenerate
679
714
  };
680
- //# sourceMappingURL=chunk-RBZ3YLOZ.js.map
715
+ //# sourceMappingURL=chunk-VKIIKF4Q.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/images/pexels.ts","../src/images/dalleImages.ts","../src/images/enrichImages.ts","../src/images/svgGenerator.ts","../src/streamCore.ts","../src/sanitizeColors.ts"],"sourcesContent":["export interface PexelsResult {\n url: string;\n photographer: string;\n alt: string;\n}\n\nexport async function searchImage(query: string, apiKey?: string): Promise<PexelsResult | null> {\n const key = apiKey || process.env.PEXELS_API_KEY;\n if (!key) return null;\n try {\n const res = await fetch(\n `https://api.pexels.com/v1/search?query=${encodeURIComponent(query)}&per_page=5&orientation=landscape&locale=en-US`,\n { headers: { Authorization: key } }\n );\n if (!res.ok) {\n console.warn(`[pexels] ${res.status} for \"${query}\", trying unsplash fallback`);\n return searchUnsplash(query);\n }\n const data = await res.json();\n const photos = data.photos;\n if (!photos || photos.length === 0) {\n console.warn(`[pexels] 0 results for \"${query}\"`);\n return null;\n }\n const photo = photos[Math.floor(Math.random() * photos.length)];\n return {\n url: photo.src.large,\n photographer: photo.photographer,\n alt: photo.alt || query,\n };\n } catch {\n return searchUnsplash(query);\n }\n}\n\nasync function searchUnsplash(query: string): Promise<PexelsResult | null> {\n try {\n const res = await fetch(\n `https://unsplash.com/napi/search/photos?query=${encodeURIComponent(query)}&per_page=5&orientation=landscape`\n );\n if (!res.ok) return null;\n const data = await res.json();\n const results = data.results;\n if (!results || results.length === 0) return null;\n const photo = results[Math.floor(Math.random() * results.length)];\n return {\n url: photo.urls?.regular || photo.urls?.small,\n photographer: photo.user?.name || \"Unsplash\",\n alt: photo.alt_description || query,\n };\n } catch {\n return null;\n }\n}\n","/**\n * Generate an image using DALL-E 3 API.\n */\nexport async function generateImage(\n query: string,\n openaiApiKey: string\n): Promise<string> {\n const res = await fetch(\"https://api.openai.com/v1/images/generations\", {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${openaiApiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n model: \"dall-e-3\",\n prompt: query,\n n: 1,\n size: \"1792x1024\",\n }),\n });\n\n if (!res.ok) {\n const err = await res.text().catch(() => \"Unknown error\");\n throw new Error(`DALL-E API error ${res.status}: ${err}`);\n }\n\n const data = await res.json();\n return data.data[0].url;\n}\n","import { searchImage } from \"./pexels\";\nimport { generateImage } from \"./dalleImages\";\n\ninterface ImageMatch {\n query: string;\n searchStr: string;\n replaceStr: string;\n}\n\nexport interface EnrichImagesOptions {\n pexelsApiKey?: string;\n openaiApiKey?: string;\n /** Called with temp URL + query, returns permanent URL. Use to persist DALL-E images to S3/etc. */\n persistImage?: (tempUrl: string, query: string) => Promise<string>;\n}\n\nconst FAKE_DOMAINS = [\n \"images.unsplash.com\",\n \"unsplash.com\",\n \"via.placeholder.com\",\n \"placeholder.com\",\n \"placehold.co\",\n \"placehold.it\",\n \"placekitten.com\",\n \"picsum.photos\",\n \"loremflickr.com\",\n \"source.unsplash.com\",\n \"dummyimage.com\",\n \"fakeimg.pl\",\n \"example.com\",\n \"img.freepik.com\",\n \"cdn.pixabay.com\",\n];\n\n/**\n * Find all images in HTML that need Pexels enrichment.\n * Two strategies:\n * 1. data-image-query=\"...\" — AI followed instructions\n * 2. <img src=\"fake-url\" — detect fake domains, use alt/class/nearby text as query\n */\nexport function findImageSlots(html: string): ImageMatch[] {\n const matches: ImageMatch[] = [];\n const seen = new Set<string>();\n\n // 1. data-image-query=\"...\" or '...' — match the full <img> tag so we can replace src + data-image-query together\n const diqRegex = /<img\\s[^>]*data-image-query=[\"']([^\"']+)[\"'][^>]*>/gi;\n let m: RegExpExecArray | null;\n while ((m = diqRegex.exec(html)) !== null) {\n const fullTag = m[0];\n const query = m[1];\n if (seen.has(query)) continue;\n seen.add(query);\n // Build replacement tag: replace src (if any) and data-image-query with final src\n const cleanedTag = fullTag\n .replace(/\\ssrc=[\"'][^\"']*[\"']/, \"\")\n .replace(/\\sdata-image-query=[\"'][^\"']*[\"']/, \"\");\n // Insert src and data-enriched right after <img\n const replaceTag = cleanedTag.replace(\n /^<img/,\n `<img src=\"{url}\" data-enriched=\"true\"`\n );\n matches.push({\n query,\n searchStr: fullTag,\n replaceStr: replaceTag,\n });\n }\n\n // 2. <img with fake/non-existent src URLs\n const imgRegex = /<img\\s[^>]*src=\"(https?:\\/\\/[^\"]+)\"[^>]*>/gi;\n while ((m = imgRegex.exec(html)) !== null) {\n const fullTag = m[0];\n const srcUrl = m[1];\n\n if (fullTag.includes(\"data-enriched\")) continue;\n if (srcUrl.includes(\"pexels.com\")) continue;\n if (seen.has(srcUrl)) continue;\n\n // Check if domain is fake\n let isFake = false;\n try {\n const domain = new URL(srcUrl).hostname;\n isFake = FAKE_DOMAINS.some((d) => domain.includes(d));\n } catch {\n isFake = true;\n }\n if (!isFake) continue;\n\n // Extract query: try alt, then class context, then URL path words\n const altMatch = fullTag.match(/alt=\"([^\"]*?)\"/);\n let query = altMatch?.[1]?.trim() || \"\";\n\n if (!query) {\n // Try to extract meaningful words from the URL path\n try {\n const path = new URL(srcUrl).pathname;\n const words = path\n .replace(/[^a-zA-Z]/g, \" \")\n .split(/\\s+/)\n .filter((w) => w.length > 2)\n .slice(0, 4)\n .join(\" \");\n if (words.length > 3) query = words;\n } catch { /* ignore */ }\n }\n\n if (!query) query = \"professional website hero image\";\n\n seen.add(srcUrl);\n matches.push({\n query,\n searchStr: `src=\"${srcUrl}\"`,\n replaceStr: `src=\"{url}\" data-enriched=\"true\"`,\n });\n }\n\n return matches;\n}\n\n/**\n * Enrich all images in an HTML string.\n * Strategy: Pexels (free) → DALL-E fallback (if openaiApiKey) → placeholder.\n * All images resolved in parallel. If persistImage callback provided, temp DALL-E URLs are persisted.\n */\nexport async function enrichImages(html: string, pexelsApiKeyOrOpts?: string | EnrichImagesOptions, openaiApiKey?: string): Promise<string> {\n // Support both legacy (string, string) and new (options object) signatures\n let opts: EnrichImagesOptions;\n if (typeof pexelsApiKeyOrOpts === \"object\" && pexelsApiKeyOrOpts !== null) {\n opts = pexelsApiKeyOrOpts;\n } else {\n opts = { pexelsApiKey: pexelsApiKeyOrOpts, openaiApiKey };\n }\n\n const slots = findImageSlots(html);\n if (slots.length === 0) return html;\n\n // Resolve all images in parallel\n const resolved = await Promise.allSettled(\n slots.map(async (slot) => {\n let url: string | null = null;\n\n // 1. Pexels first (free)\n if (opts.pexelsApiKey) {\n const img = await searchImage(slot.query, opts.pexelsApiKey).catch(() => null);\n url = img?.url || null;\n }\n\n // 2. DALL-E fallback if Pexels found nothing\n if (!url && opts.openaiApiKey) {\n try {\n const tempUrl = await generateImage(slot.query, opts.openaiApiKey);\n url = opts.persistImage\n ? await opts.persistImage(tempUrl, slot.query)\n : tempUrl;\n } catch (e) {\n console.warn(`[dalle] failed for \"${slot.query}\":`, e);\n }\n }\n\n // 3. Placeholder fallback\n url ??= `https://placehold.co/800x500/1f2937/9ca3af?text=${encodeURIComponent(slot.query.slice(0, 30))}`;\n\n return { slot, url };\n })\n );\n\n let result = html;\n for (const r of resolved) {\n if (r.status === \"fulfilled\" && r.value) {\n const { slot, url } = r.value;\n const replacement = slot.replaceStr.replace(\"{url}\", url);\n result = result.replaceAll(slot.searchStr, replacement);\n }\n }\n\n // Catch any remaining <img> tags without src\n result = result.replace(/<img\\s(?![^>]*\\bsrc=)([^>]*?)>/gi, (_match, attrs) => {\n const altMatch = attrs.match(/alt=\"([^\"]*?)\"/);\n const query = altMatch?.[1] || \"professional image\";\n return `<img src=\"https://placehold.co/800x500/1f2937/9ca3af?text=${encodeURIComponent(query.slice(0, 30))}\" ${attrs}>`;\n });\n\n return result;\n}\n","import { createAnthropic } from \"@ai-sdk/anthropic\";\nimport { generateText } from \"ai\";\nimport { currentDateLine } from \"../streamCore\";\n\nconst SVG_SYSTEM_PROMPT = `You are a professional SVG designer. Generate clean, compact SVG graphics for documents.\n\nSTRICT SIZE RULES:\n- ALWAYS use viewBox=\"0 0 600 300\" (2:1 ratio) — no exceptions\n- ALWAYS set width=\"100%\" height=\"auto\" — NEVER use fixed pixel width/height\n- NO internal padding or margins — content fills the viewBox edge-to-edge (leave only 10-20px padding)\n- Keep SVGs under 2KB — simplicity is key\n\nSTYLE RULES:\n- Output ONLY the <svg>...</svg> tag — no markdown, no explanation\n- Flat design: solid fills, no drop shadows, minimal gradients (max 1-2)\n- Max 8-10 elements total — prefer fewer, larger shapes over many small ones\n- Color palette: use the provided theme colors, or defaults (#6366f1, #8b5cf6, #ec4899, #14b8a6, #f59e0b)\n- Text: font-family=\"system-ui, sans-serif\", font-size 12-16px, max 5 text labels\n- Self-contained: no external references, all styles inline\n\nCHART TYPES:\n- Bar charts (vertical/horizontal) — max 6 bars, rounded caps\n- Pie/donut charts — max 5 segments\n- Line charts — smooth paths, max 8 data points\n- Progress/gauge charts\n- Simple comparison charts\n- Stat cards with visual elements\n\nAVOID: complex illustrations, many small elements, decorative borders, nested groups deeper than 2 levels.`;\n\n\nexport async function generateSvg(\n prompt: string,\n anthropicApiKey?: string,\n options?: { width?: number; height?: number; themeColors?: string }\n): Promise<string> {\n const apiKey = anthropicApiKey || process.env.ANTHROPIC_API_KEY;\n const anthropic = createAnthropic({ apiKey: apiKey || undefined });\n\n const sizeHint = options?.width && options?.height\n ? ` Target dimensions: ${options.width}x${options.height}px.`\n : \"\";\n const colorHint = options?.themeColors\n ? ` Use these theme colors: ${options.themeColors}.`\n : \"\";\n\n const result = await generateText({\n model: anthropic(\"claude-haiku-4-5-20251001\"),\n system: SVG_SYSTEM_PROMPT + currentDateLine(),\n messages: [\n {\n role: \"user\",\n content: `Generate an SVG for: ${prompt}${sizeHint}${colorHint}`,\n },\n ],\n maxOutputTokens: 2000,\n });\n\n // Extract just the SVG tag\n const svgMatch = result.text.match(/<svg[\\s\\S]*<\\/svg>/i);\n if (!svgMatch) {\n throw new Error(\"SVG generation failed — no <svg> tag in response\");\n }\n\n return svgMatch[0];\n}\n","import { streamText } from \"ai\";\nimport { createAnthropic } from \"@ai-sdk/anthropic\";\nimport { nanoid } from \"nanoid\";\nimport { findImageSlots } from \"./images/enrichImages\";\nimport { searchImage } from \"./images/pexels\";\nimport { generateImage } from \"./images/dalleImages\";\nimport { generateSvg } from \"./images/svgGenerator\";\nimport type { Section3 } from \"./types\";\nimport { sanitizeSemanticColors } from \"./sanitizeColors\";\n\nexport function currentDateLine(): string {\n return `\\nToday's date is ${new Date().toISOString().split(\"T\")[0]}. Use this for any date references.\\n`;\n}\n\n/**\n * Resolve AI model from available keys.\n * If modelId is already a LanguageModel object, return it directly.\n * Prefers Anthropic, falls back to OpenAI.\n */\nfunction isOpenAiModel(id: string): boolean {\n return /^(gpt-|o[1-9]|dall-e|tts-|whisper|chatgpt-)/.test(id);\n}\n\nfunction isLanguageModel(value: unknown): value is import(\"ai\").LanguageModel {\n return typeof value === \"object\" && value !== null && \"modelId\" in value && \"provider\" in value;\n}\n\nexport async function resolveModel(opts: {\n openaiApiKey?: string;\n anthropicApiKey?: string;\n modelId?: string | import(\"ai\").LanguageModel;\n defaultOpenai: string;\n defaultAnthropic: string;\n}) {\n // If modelId is already a model object, return it directly\n if (opts.modelId && isLanguageModel(opts.modelId)) {\n return opts.modelId;\n }\n\n const modelId = opts.modelId as string | undefined;\n\n if (modelId && isOpenAiModel(modelId)) {\n const openaiKey = opts.openaiApiKey || process.env.OPENAI_API_KEY;\n if (openaiKey) {\n const { createOpenAI } = await import(\"@ai-sdk/openai\");\n return createOpenAI({ apiKey: openaiKey })(modelId);\n }\n // OpenAI model requested but no key — fall through to Anthropic default\n } else if (modelId) {\n const anthropicKey = opts.anthropicApiKey || process.env.ANTHROPIC_API_KEY;\n if (anthropicKey) {\n return createAnthropic({ apiKey: anthropicKey })(modelId);\n }\n }\n // No explicit modelId — prefer Anthropic, fallback to OpenAI\n const anthropicKey = opts.anthropicApiKey || process.env.ANTHROPIC_API_KEY;\n if (anthropicKey) {\n return createAnthropic({ apiKey: anthropicKey })(opts.defaultAnthropic);\n }\n const openaiKey = opts.openaiApiKey || process.env.OPENAI_API_KEY;\n if (openaiKey) {\n const { createOpenAI } = await import(\"@ai-sdk/openai\");\n return createOpenAI({ apiKey: openaiKey })(opts.defaultOpenai);\n }\n return createAnthropic()(opts.defaultAnthropic);\n}\n\n/**\n * Convert data URL to Uint8Array for AI SDK vision.\n */\nexport function dataUrlToImagePart(dataUrl: string): { image: Uint8Array; mimeType: string } | null {\n const match = dataUrl.match(/^data:([^;]+);base64,(.+)$/);\n if (!match) return null;\n return {\n image: new Uint8Array(Buffer.from(match[2], \"base64\")),\n mimeType: match[1],\n };\n}\n\n/**\n * Extract complete JSON objects from accumulated text using brace-depth tracking.\n */\nexport function extractJsonObjects(text: string): [any[], string] {\n const objects: any[] = [];\n let remaining = text;\n\n while (remaining.length > 0) {\n remaining = remaining.trimStart();\n if (!remaining.startsWith(\"{\")) {\n const nextBrace = remaining.indexOf(\"{\");\n if (nextBrace === -1) break;\n remaining = remaining.slice(nextBrace);\n continue;\n }\n\n let depth = 0;\n let inString = false;\n let escape = false;\n let end = -1;\n\n for (let i = 0; i < remaining.length; i++) {\n const ch = remaining[i];\n if (escape) { escape = false; continue; }\n if (ch === \"\\\\\") { escape = true; continue; }\n if (ch === '\"') { inString = !inString; continue; }\n if (inString) continue;\n if (ch === \"{\") depth++;\n if (ch === \"}\") { depth--; if (depth === 0) { end = i; break; } }\n }\n\n if (end === -1) break;\n\n const candidate = remaining.slice(0, end + 1);\n remaining = remaining.slice(end + 1);\n\n try {\n objects.push(JSON.parse(candidate));\n } catch {\n // malformed, skip\n }\n }\n\n return [objects, remaining];\n}\n\n/** Inline shimmer SVG used as src for loading image placeholders */\nconst LOADING_PLACEHOLDER_SRC = `data:image/svg+xml,${encodeURIComponent('<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"800\" height=\"500\" viewBox=\"0 0 800 500\"><rect fill=\"#f3f4f6\" width=\"800\" height=\"500\" rx=\"12\"/><g opacity=\".4\"><rect x=\"320\" y=\"200\" width=\"160\" height=\"4\" rx=\"2\" fill=\"#d1d5db\"><animate attributeName=\"opacity\" values=\".3;.8;.3\" dur=\"1.5s\" repeatCount=\"indefinite\"/></rect><rect x=\"280\" y=\"215\" width=\"240\" height=\"4\" rx=\"2\" fill=\"#d1d5db\"><animate attributeName=\"opacity\" values=\".3;.8;.3\" dur=\"1.5s\" begin=\".3s\" repeatCount=\"indefinite\"/></rect><rect x=\"340\" y=\"230\" width=\"120\" height=\"4\" rx=\"2\" fill=\"#d1d5db\"><animate attributeName=\"opacity\" values=\".3;.8;.3\" dur=\"1.5s\" begin=\".6s\" repeatCount=\"indefinite\"/></rect></g><g transform=\"translate(376,150)\" opacity=\".3\"><path d=\"M0 28V4a4 4 0 014-4h40a4 4 0 014 4v24a4 4 0 01-4 4H4a4 4 0 01-4-4z\" fill=\"#d1d5db\"/><circle cx=\"14\" cy=\"12\" r=\"4\" fill=\"#9ca3af\"/><path d=\"M4 28l10-10 6 6 8-8 16 16H4z\" fill=\"#9ca3af\" opacity=\".5\"/></g></svg>')}`;\n\n/** Inline SVG placeholder for loading charts */\nconst SVG_LOADING_PLACEHOLDER = `<div class=\"w-full h-48 bg-gray-50 rounded-lg flex items-center justify-center animate-pulse\"><svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"#9ca3af\" stroke-width=\"1.5\"><rect x=\"3\" y=\"12\" width=\"4\" height=\"9\" rx=\"1\"/><rect x=\"10\" y=\"7\" width=\"4\" height=\"14\" rx=\"1\"/><rect x=\"17\" y=\"3\" width=\"4\" height=\"18\" rx=\"1\"/></svg></div>`;\n\n/** Replace data-svg-chart divs with loading placeholders */\nexport function addSvgLoadingPlaceholders(html: string): string {\n return html.replace(\n /<div\\s([^>]*?)data-svg-chart=\"([^\"]+)\"([^>]*?)>[\\s\\S]*?<\\/div>/gi,\n (_match, before, chart, after) => {\n return `<div ${before}data-svg-chart=\"${chart}\"${after}>${SVG_LOADING_PLACEHOLDER}</div>`;\n }\n );\n}\n\n/** Replace data-image-query attrs with animated loading placeholders */\nexport function addLoadingPlaceholders(html: string): string {\n return html.replace(\n /(<img\\s[^>]*)data-image-query=\"([^\"]+)\"([^>]*?)(?:\\s*\\/?>)/gi,\n (_match, before, query, after) => {\n if (before.includes('src=') || after.includes('src=')) return _match;\n return `${before}src=\"${LOADING_PLACEHOLDER_SRC}\" data-image-query=\"${query}\" alt=\"${query}\"${after}>`;\n }\n );\n}\n\n/** Enrich a section's images (Pexels → DALL-E → placeholder fallback). Mutates section.html in place. */\nexport async function enrichSectionImages(\n section: Section3,\n opts: {\n pexelsApiKey?: string;\n openaiApiKey?: string;\n persistImage?: (tempUrl: string, query: string) => Promise<string>;\n onImageUpdate?: (sectionId: string, html: string) => void;\n }\n): Promise<void> {\n const slots = findImageSlots(section.html);\n if (slots.length === 0) return;\n const results = await Promise.allSettled(\n slots.map(async (slot) => {\n let url: string | null = null;\n if (opts.pexelsApiKey) {\n const img = await searchImage(slot.query, opts.pexelsApiKey).catch(() => null);\n url = img?.url || null;\n }\n if (!url && opts.openaiApiKey) {\n try {\n const tempUrl = await generateImage(slot.query, opts.openaiApiKey);\n url = opts.persistImage ? await opts.persistImage(tempUrl, slot.query) : tempUrl;\n } catch (e) {\n console.warn(`[dalle] failed for \"${slot.query}\":`, e);\n }\n }\n url ??= `https://placehold.co/800x500/1f2937/9ca3af?text=${encodeURIComponent(slot.query.slice(0, 30))}`;\n return { slot, url };\n })\n );\n let html = section.html;\n for (const r of results) {\n if (r.status === \"fulfilled\" && r.value) {\n const { slot, url } = r.value;\n const replacement = slot.replaceStr.replace(\"{url}\", url);\n html = html.replaceAll(slot.searchStr, replacement);\n }\n }\n if (html !== section.html) {\n section.html = html;\n opts.onImageUpdate?.(section.id, html);\n }\n}\n\n/** Enrich a section's SVG chart placeholders. Mutates section.html in place. */\nexport async function enrichSectionSvgCharts(\n section: Section3,\n opts: {\n anthropicApiKey?: string;\n onImageUpdate?: (sectionId: string, html: string) => void;\n }\n): Promise<void> {\n const svgRegex = /<div\\s[^>]*data-svg-chart=\"([^\"]+)\"[^>]*>[\\s\\S]*?<\\/div>/gi;\n const svgMatches: { fullMatch: string; prompt: string }[] = [];\n let svgM: RegExpExecArray | null;\n while ((svgM = svgRegex.exec(section.html)) !== null) {\n svgMatches.push({ fullMatch: svgM[0], prompt: svgM[1] });\n }\n if (svgMatches.length === 0) return;\n const anthropicKey = opts.anthropicApiKey || process.env.ANTHROPIC_API_KEY;\n const results = await Promise.allSettled(\n svgMatches.map(async ({ fullMatch, prompt }) => {\n try {\n const svg = await generateSvg(prompt, anthropicKey);\n return { fullMatch, svg };\n } catch (e) {\n console.warn(`[svg] failed for \"${prompt}\":`, e);\n return { fullMatch, svg: `<div class=\"w-full h-48 bg-gray-100 rounded-lg flex items-center justify-center text-gray-400 text-sm\">${prompt}</div>` };\n }\n })\n );\n let html = section.html;\n for (const r of results) {\n if (r.status === \"fulfilled\" && r.value) {\n html = html.replace(r.value.fullMatch, r.value.svg);\n }\n }\n if (html !== section.html) {\n section.html = html;\n opts.onImageUpdate?.(section.id, html);\n }\n}\n\nexport interface StreamGenerateOptions {\n /** Anthropic API key */\n anthropicApiKey?: string;\n /** OpenAI API key */\n openaiApiKey?: string;\n /** Model ID override or pre-built LanguageModel object */\n model?: string | import(\"ai\").LanguageModel;\n /** System prompt */\n systemPrompt: string;\n /** User message content (text or multimodal parts) */\n userContent: any[];\n /** Pexels API key for image enrichment */\n pexelsApiKey?: string;\n /** Persist DALL-E images to permanent storage */\n persistImage?: (tempUrl: string, query: string) => Promise<string>;\n /** Called when a new section is parsed */\n onSection?: (section: Section3) => void;\n /** Called when a section's images are enriched */\n onImageUpdate?: (sectionId: string, html: string) => void;\n /** Called with raw text buffer for real-time partial streaming */\n onRawChunk?: (buffer: string, completedCount: number) => void;\n /** Called when generation is complete */\n onDone?: (sections: Section3[]) => void;\n /** Called on error */\n onError?: (error: Error) => void;\n}\n\n/**\n * Core streaming generation: stream AI text → parse NDJSON → emit sections → enrich images.\n * Used by both generateLanding and generateDocument.\n */\nexport async function streamGenerate(options: StreamGenerateOptions): Promise<Section3[]> {\n const {\n anthropicApiKey,\n openaiApiKey: _openaiApiKey,\n model: modelId,\n systemPrompt,\n userContent,\n pexelsApiKey,\n persistImage,\n onSection,\n onImageUpdate,\n onRawChunk,\n onDone,\n onError,\n } = options;\n\n const openaiApiKey = _openaiApiKey || process.env.OPENAI_API_KEY;\n const model = await resolveModel({\n openaiApiKey,\n anthropicApiKey,\n modelId,\n defaultOpenai: \"gpt-4o\",\n defaultAnthropic: \"claude-sonnet-4-6\",\n });\n\n const result = streamText({\n model,\n system: systemPrompt + currentDateLine(),\n messages: [{ role: \"user\", content: userContent }],\n });\n\n const allSections: Section3[] = [];\n const imagePromises: Promise<void>[] = [];\n let sectionOrder = 0;\n let buffer = \"\";\n\n function enrichSvgCharts(sectionRef: Section3) {\n const svgRegex = /<div\\s[^>]*data-svg-chart=\"([^\"]+)\"[^>]*>[\\s\\S]*?<\\/div>/gi;\n const svgMatches: { fullMatch: string; prompt: string }[] = [];\n let svgM: RegExpExecArray | null;\n while ((svgM = svgRegex.exec(sectionRef.html)) !== null) {\n svgMatches.push({ fullMatch: svgM[0], prompt: svgM[1] });\n }\n if (svgMatches.length === 0) return;\n\n const anthropicKey = anthropicApiKey || process.env.ANTHROPIC_API_KEY;\n imagePromises.push(\n (async () => {\n const results = await Promise.allSettled(\n svgMatches.map(async ({ fullMatch, prompt }) => {\n try {\n const svg = await generateSvg(prompt, anthropicKey);\n return { fullMatch, svg };\n } catch (e) {\n console.warn(`[svg] failed for \"${prompt}\":`, e);\n return { fullMatch, svg: `<div class=\"w-full h-48 bg-gray-100 rounded-lg flex items-center justify-center text-gray-400 text-sm\">${prompt}</div>` };\n }\n })\n );\n let html = sectionRef.html;\n for (const r of results) {\n if (r.status === \"fulfilled\" && r.value) {\n html = html.replace(r.value.fullMatch, r.value.svg);\n }\n }\n if (html !== sectionRef.html) {\n sectionRef.html = html;\n onImageUpdate?.(sectionRef.id, html);\n }\n })()\n );\n }\n\n function enrichSection(sectionRef: Section3) {\n const slots = findImageSlots(sectionRef.html);\n if (slots.length === 0) return;\n const slotsSnapshot = slots.map((s) => ({ ...s }));\n imagePromises.push(\n (async () => {\n const results = await Promise.allSettled(\n slotsSnapshot.map(async (slot) => {\n let url: string | null = null;\n // 1. Pexels first (free, fast)\n if (pexelsApiKey) {\n const img = await searchImage(slot.query, pexelsApiKey).catch(() => null);\n url = img?.url || null;\n }\n // 2. DALL-E fallback\n if (!url && openaiApiKey) {\n try {\n const tempUrl = await generateImage(slot.query, openaiApiKey);\n url = persistImage ? await persistImage(tempUrl, slot.query) : tempUrl;\n } catch (e) {\n console.warn(`[dalle] failed for \"${slot.query}\":`, e);\n }\n }\n url ??= `https://placehold.co/800x500/1f2937/9ca3af?text=${encodeURIComponent(slot.query.slice(0, 30))}`;\n return { slot, url };\n })\n );\n let html = sectionRef.html;\n for (const r of results) {\n if (r.status === \"fulfilled\" && r.value) {\n const { slot, url } = r.value;\n const replacement = slot.replaceStr.replace(\"{url}\", url);\n html = html.replaceAll(slot.searchStr, replacement);\n }\n }\n if (html !== sectionRef.html) {\n sectionRef.html = html;\n onImageUpdate?.(sectionRef.id, html);\n }\n })()\n );\n }\n\n function processObject(obj: any) {\n if (!obj.html || !obj.label) return;\n const section: Section3 = {\n id: nanoid(8),\n order: sectionOrder++,\n html: sanitizeSemanticColors(addSvgLoadingPlaceholders(addLoadingPlaceholders(obj.html))),\n label: obj.label,\n };\n allSections.push(section);\n onSection?.(section);\n enrichSection(section);\n enrichSvgCharts(section);\n }\n\n try {\n let chunkCount = 0;\n for await (const chunk of result.textStream) {\n buffer += chunk;\n chunkCount++;\n\n const [objects, remaining] = extractJsonObjects(buffer);\n buffer = remaining;\n for (const obj of objects) {\n chunkCount = 0;\n processObject(obj);\n }\n\n if (onRawChunk && chunkCount % 5 === 0 && buffer.length > 20) {\n onRawChunk(buffer, allSections.length);\n }\n }\n\n // Parse remaining buffer\n if (buffer.trim()) {\n let cleaned = buffer.trim();\n if (cleaned.startsWith(\"```\")) {\n cleaned = cleaned.replace(/^```(?:json)?\\s*/, \"\").replace(/\\s*```$/, \"\");\n }\n const [lastObjects] = extractJsonObjects(cleaned);\n for (const obj of lastObjects) processObject(obj);\n }\n\n // Wait for image enrichment\n await Promise.allSettled(imagePromises);\n\n // Final fallback for images without src\n for (const section of allSections) {\n const before = section.html;\n section.html = section.html.replace(\n /<img\\s(?![^>]*\\bsrc=)([^>]*?)>/gi,\n (_match, attrs) => {\n const altMatch = attrs.match(/alt=\"([^\"]*?)\"/);\n const query = altMatch?.[1] || \"image\";\n return `<img src=\"https://placehold.co/800x500/1f2937/9ca3af?text=${encodeURIComponent(query.slice(0, 30))}\" ${attrs}>`;\n }\n );\n section.html = section.html.replace(\n /data-image-query=\"([^\"]+)\"/g,\n (_match, query) => {\n return `src=\"https://placehold.co/800x500/1f2937/9ca3af?text=${encodeURIComponent(query.slice(0, 30))}\" data-enriched=\"placeholder\"`;\n }\n );\n if (section.html !== before) {\n onImageUpdate?.(section.id, section.html);\n }\n }\n\n onDone?.(allSections);\n return allSections;\n } catch (err: any) {\n const error = err instanceof Error ? err : new Error(err?.message || \"Generation failed\");\n onError?.(error);\n throw error;\n }\n}\n","/**\n * Replace hardcoded Tailwind color classes with semantic color classes.\n * Gray/white/black/slate/zinc/neutral stay intact.\n *\n * Smart mode: if the HTML already contains semantic classes (bg-primary, bg-surface, etc.),\n * only do light cleanup. If no semantic classes found, do full replacement.\n *\n * Maps colors to primary/secondary/accent instead of everything to primary:\n * - Blues/indigos/violet → secondary\n * - Greens/teals/emerald/cyan → accent\n * - Everything else (red/orange/amber/yellow/pink/rose/purple/fuchsia/lime/sky) → primary\n */\n\nconst COLORS =\n \"red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose\";\n\nconst SECONDARY_COLORS = \"blue|indigo|violet\";\nconst ACCENT_COLORS = \"green|emerald|teal|cyan\";\n// Everything else → primary\n\nfunction categorize(color: string): \"primary\" | \"secondary\" | \"accent\" {\n if (new RegExp(`^(?:${SECONDARY_COLORS})$`).test(color)) return \"secondary\";\n if (new RegExp(`^(?:${ACCENT_COLORS})$`).test(color)) return \"accent\";\n return \"primary\";\n}\n\nfunction buildReplacements(): [RegExp, (match: string, color: string) => string][] {\n const re = (prefix: string, shades: string) =>\n new RegExp(`\\\\b${prefix}-(${COLORS})-(${shades})\\\\b`, \"g\");\n\n return [\n // Background\n [re(\"bg\", \"500|600|700\"), (_m, c) => `bg-${categorize(c)}`],\n [re(\"bg\", \"50|100\"), (_m, c) => `bg-${categorize(c)}-light`],\n [re(\"bg\", \"800|900|950\"), (_m, c) => `bg-${categorize(c)}-dark`],\n [re(\"bg\", \"200|300|400\"), (_m, c) => `bg-${categorize(c)}`],\n\n // Text\n [re(\"text\", \"500|600|700\"), (_m, c) => `text-${categorize(c)}`],\n [re(\"text\", \"800|900|950\"), (_m, c) => `text-${categorize(c)}-dark`],\n [re(\"text\", \"50|100|200|300\"), (_m, c) => `text-on-${categorize(c)}`],\n [re(\"text\", \"400\"), (_m, c) => `text-${categorize(c)}`],\n\n // Border\n [re(\"border\", \"\\\\d{2,3}\"), (_m, c) => `border-${categorize(c)}`],\n\n // Ring\n [re(\"ring\", \"\\\\d{2,3}\"), (_m, c) => `ring-${categorize(c)}`],\n\n // Gradients\n [re(\"from\", \"\\\\d{2,3}\"), (_m, c) => `from-${categorize(c)}`],\n [re(\"to\", \"\\\\d{2,3}\"), (_m, c) => `to-${categorize(c)}`],\n [re(\"via\", \"\\\\d{2,3}\"), (_m, c) => `via-${categorize(c)}`],\n\n // Hover/focus variants\n [new RegExp(`\\\\bhover:bg-(${COLORS})-(500|600|700|800|900|950)\\\\b`, \"g\"), (_m, c) => `hover:bg-${categorize(c)}-dark`],\n [new RegExp(`\\\\bhover:bg-(${COLORS})-(50|100|200|300|400)\\\\b`, \"g\"), (_m, c) => `hover:bg-${categorize(c)}-light`],\n [new RegExp(`\\\\bhover:text-(${COLORS})-\\\\d{2,3}\\\\b`, \"g\"), (_m, c) => `hover:text-${categorize(c)}`],\n [new RegExp(`\\\\bfocus:ring-(${COLORS})-\\\\d{2,3}\\\\b`, \"g\"), (_m, c) => `focus:ring-${categorize(c)}`],\n [new RegExp(`\\\\bfocus:border-(${COLORS})-\\\\d{2,3}\\\\b`, \"g\"), (_m, c) => `focus:border-${categorize(c)}`],\n\n // Divide\n [re(\"divide\", \"\\\\d{2,3}\"), (_m, c) => `divide-${categorize(c)}`],\n\n // Placeholder\n [re(\"placeholder\", \"\\\\d{2,3}\"), (_m, c) => `placeholder-${categorize(c)}`],\n\n // Outline\n [re(\"outline\", \"\\\\d{2,3}\"), (_m, c) => `outline-${categorize(c)}`],\n\n // Shadow colored\n [re(\"shadow\", \"\\\\d{2,3}\"), (_m, c) => `shadow-${categorize(c)}`],\n\n // Decoration\n [re(\"decoration\", \"\\\\d{2,3}\"), (_m, c) => `decoration-${categorize(c)}`],\n\n // Accent (form accent color)\n [re(\"accent\", \"\\\\d{2,3}\"), (_m, c) => `accent-${categorize(c)}`],\n ];\n}\n\nconst replacements = buildReplacements();\n\nexport function sanitizeSemanticColors(html: string): string {\n // Always replace hardcoded chromatic colors — even if some semantic classes exist.\n // The regexes only match hardcoded colors (bg-blue-500, text-red-700, etc.)\n // and leave semantic classes (bg-primary, text-on-surface, etc.) untouched.\n let result = html;\n for (const [pattern, replacer] of replacements) {\n result = result.replace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,MAC1C;AAAA,IACF;AAEA,aAAS,WAAW;AACpB,WAAO;AAAA,EACT,SAAS,KAAU;AACjB,UAAM,QAAQ,eAAe,QAAQ,MAAM,IAAI,MAAM,KAAK,WAAW,mBAAmB;AACxF,cAAU,KAAK;AACf,UAAM;AAAA,EACR;AACF;;;ADrcA,IAAM,oBAAoB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA2B1B,eAAsB,YACpB,QACA,iBACA,SACiB;AACjB,QAAM,SAAS,mBAAmB,QAAQ,IAAI;AAC9C,QAAM,YAAYC,iBAAgB,EAAE,QAAQ,UAAU,OAAU,CAAC;AAEjE,QAAM,WAAW,SAAS,SAAS,SAAS,SACxC,uBAAuB,QAAQ,KAAK,IAAI,QAAQ,MAAM,QACtD;AACJ,QAAM,YAAY,SAAS,cACvB,4BAA4B,QAAQ,WAAW,MAC/C;AAEJ,QAAM,SAAS,MAAM,aAAa;AAAA,IAChC,OAAO,UAAU,2BAA2B;AAAA,IAC5C,QAAQ,oBAAoB,gBAAgB;AAAA,IAC5C,UAAU;AAAA,MACR;AAAA,QACE,MAAM;AAAA,QACN,SAAS,wBAAwB,MAAM,GAAG,QAAQ,GAAG,SAAS;AAAA,MAChE;AAAA,IACF;AAAA,IACA,iBAAiB;AAAA,EACnB,CAAC;AAGD,QAAM,WAAW,OAAO,KAAK,MAAM,qBAAqB;AACxD,MAAI,CAAC,UAAU;AACb,UAAM,IAAI,MAAM,uDAAkD;AAAA,EACpE;AAEA,SAAO,SAAS,CAAC;AACnB;","names":["createAnthropic","openaiKey","anthropicKey","createAnthropic"]}
1
+ {"version":3,"sources":["../src/images/pexels.ts","../src/images/dalleImages.ts","../src/images/enrichImages.ts","../src/images/svgGenerator.ts","../src/streamCore.ts","../src/sanitizeColors.ts"],"sourcesContent":["export interface PexelsResult {\n url: string;\n photographer: string;\n alt: string;\n}\n\nexport async function searchImage(query: string, apiKey?: string): Promise<PexelsResult | null> {\n const key = apiKey || process.env.PEXELS_API_KEY;\n if (!key) return null;\n try {\n const res = await fetch(\n `https://api.pexels.com/v1/search?query=${encodeURIComponent(query)}&per_page=5&orientation=landscape&locale=en-US`,\n { headers: { Authorization: key } }\n );\n if (!res.ok) {\n console.warn(`[pexels] ${res.status} for \"${query}\", trying unsplash fallback`);\n return searchUnsplash(query);\n }\n const data = await res.json();\n const photos = data.photos;\n if (!photos || photos.length === 0) {\n console.warn(`[pexels] 0 results for \"${query}\"`);\n return null;\n }\n const photo = photos[Math.floor(Math.random() * photos.length)];\n return {\n url: photo.src.large,\n photographer: photo.photographer,\n alt: photo.alt || query,\n };\n } catch {\n return searchUnsplash(query);\n }\n}\n\nasync function searchUnsplash(query: string): Promise<PexelsResult | null> {\n try {\n const res = await fetch(\n `https://unsplash.com/napi/search/photos?query=${encodeURIComponent(query)}&per_page=5&orientation=landscape`\n );\n if (!res.ok) return null;\n const data = await res.json();\n const results = data.results;\n if (!results || results.length === 0) return null;\n const photo = results[Math.floor(Math.random() * results.length)];\n return {\n url: photo.urls?.regular || photo.urls?.small,\n photographer: photo.user?.name || \"Unsplash\",\n alt: photo.alt_description || query,\n };\n } catch {\n return null;\n }\n}\n","/**\n * Generate an image using DALL-E 3 API.\n */\nexport async function generateImage(\n query: string,\n openaiApiKey: string\n): Promise<string> {\n const res = await fetch(\"https://api.openai.com/v1/images/generations\", {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${openaiApiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n model: \"dall-e-3\",\n prompt: query,\n n: 1,\n size: \"1792x1024\",\n }),\n });\n\n if (!res.ok) {\n const err = await res.text().catch(() => \"Unknown error\");\n throw new Error(`DALL-E API error ${res.status}: ${err}`);\n }\n\n const data = await res.json();\n return data.data[0].url;\n}\n","import { searchImage } from \"./pexels\";\nimport { generateImage } from \"./dalleImages\";\n\ninterface ImageMatch {\n query: string;\n searchStr: string;\n replaceStr: string;\n}\n\nexport interface EnrichImagesOptions {\n pexelsApiKey?: string;\n openaiApiKey?: string;\n /** Called with temp URL + query, returns permanent URL. Use to persist DALL-E images to S3/etc. */\n persistImage?: (tempUrl: string, query: string) => Promise<string>;\n}\n\nconst FAKE_DOMAINS = [\n \"images.unsplash.com\",\n \"unsplash.com\",\n \"via.placeholder.com\",\n \"placeholder.com\",\n \"placehold.co\",\n \"placehold.it\",\n \"placekitten.com\",\n \"picsum.photos\",\n \"loremflickr.com\",\n \"source.unsplash.com\",\n \"dummyimage.com\",\n \"fakeimg.pl\",\n \"example.com\",\n \"img.freepik.com\",\n \"cdn.pixabay.com\",\n];\n\n/**\n * Find all images in HTML that need Pexels enrichment.\n * Two strategies:\n * 1. data-image-query=\"...\" — AI followed instructions\n * 2. <img src=\"fake-url\" — detect fake domains, use alt/class/nearby text as query\n */\nexport function findImageSlots(html: string): ImageMatch[] {\n const matches: ImageMatch[] = [];\n const seen = new Set<string>();\n\n // 1. data-image-query=\"...\" or '...' — match the full <img> tag so we can replace src + data-image-query together\n const diqRegex = /<img\\s[^>]*data-image-query=[\"']([^\"']+)[\"'][^>]*>/gi;\n let m: RegExpExecArray | null;\n while ((m = diqRegex.exec(html)) !== null) {\n const fullTag = m[0];\n const query = m[1];\n if (seen.has(query)) continue;\n seen.add(query);\n // Build replacement tag: replace src (if any) and data-image-query with final src\n const cleanedTag = fullTag\n .replace(/\\ssrc=[\"'][^\"']*[\"']/, \"\")\n .replace(/\\sdata-image-query=[\"'][^\"']*[\"']/, \"\");\n // Insert src and data-enriched right after <img\n const replaceTag = cleanedTag.replace(\n /^<img/,\n `<img src=\"{url}\" data-enriched=\"true\"`\n );\n matches.push({\n query,\n searchStr: fullTag,\n replaceStr: replaceTag,\n });\n }\n\n // 2. <img with fake/non-existent src URLs\n const imgRegex = /<img\\s[^>]*src=\"(https?:\\/\\/[^\"]+)\"[^>]*>/gi;\n while ((m = imgRegex.exec(html)) !== null) {\n const fullTag = m[0];\n const srcUrl = m[1];\n\n if (fullTag.includes(\"data-enriched\")) continue;\n if (srcUrl.includes(\"pexels.com\")) continue;\n if (seen.has(srcUrl)) continue;\n\n // Check if domain is fake\n let isFake = false;\n try {\n const domain = new URL(srcUrl).hostname;\n isFake = FAKE_DOMAINS.some((d) => domain.includes(d));\n } catch {\n isFake = true;\n }\n if (!isFake) continue;\n\n // Extract query: try alt, then class context, then URL path words\n const altMatch = fullTag.match(/alt=\"([^\"]*?)\"/);\n let query = altMatch?.[1]?.trim() || \"\";\n\n if (!query) {\n // Try to extract meaningful words from the URL path\n try {\n const path = new URL(srcUrl).pathname;\n const words = path\n .replace(/[^a-zA-Z]/g, \" \")\n .split(/\\s+/)\n .filter((w) => w.length > 2)\n .slice(0, 4)\n .join(\" \");\n if (words.length > 3) query = words;\n } catch { /* ignore */ }\n }\n\n if (!query) query = \"professional website hero image\";\n\n seen.add(srcUrl);\n matches.push({\n query,\n searchStr: `src=\"${srcUrl}\"`,\n replaceStr: `src=\"{url}\" data-enriched=\"true\"`,\n });\n }\n\n return matches;\n}\n\n/**\n * Enrich all images in an HTML string.\n * Strategy: Pexels (free) → DALL-E fallback (if openaiApiKey) → placeholder.\n * All images resolved in parallel. If persistImage callback provided, temp DALL-E URLs are persisted.\n */\nexport async function enrichImages(html: string, pexelsApiKeyOrOpts?: string | EnrichImagesOptions, openaiApiKey?: string): Promise<string> {\n // Support both legacy (string, string) and new (options object) signatures\n let opts: EnrichImagesOptions;\n if (typeof pexelsApiKeyOrOpts === \"object\" && pexelsApiKeyOrOpts !== null) {\n opts = pexelsApiKeyOrOpts;\n } else {\n opts = { pexelsApiKey: pexelsApiKeyOrOpts, openaiApiKey };\n }\n\n const slots = findImageSlots(html);\n if (slots.length === 0) return html;\n\n // Resolve all images in parallel\n const resolved = await Promise.allSettled(\n slots.map(async (slot) => {\n let url: string | null = null;\n\n // 1. Pexels first (free)\n if (opts.pexelsApiKey) {\n const img = await searchImage(slot.query, opts.pexelsApiKey).catch(() => null);\n url = img?.url || null;\n }\n\n // 2. DALL-E fallback if Pexels found nothing\n if (!url && opts.openaiApiKey) {\n try {\n const tempUrl = await generateImage(slot.query, opts.openaiApiKey);\n url = opts.persistImage\n ? await opts.persistImage(tempUrl, slot.query)\n : tempUrl;\n } catch (e) {\n console.warn(`[dalle] failed for \"${slot.query}\":`, e);\n }\n }\n\n // 3. Placeholder fallback\n url ??= `https://placehold.co/800x500/1f2937/9ca3af?text=${encodeURIComponent(slot.query.slice(0, 30))}`;\n\n return { slot, url };\n })\n );\n\n let result = html;\n for (const r of resolved) {\n if (r.status === \"fulfilled\" && r.value) {\n const { slot, url } = r.value;\n const replacement = slot.replaceStr.replace(\"{url}\", url);\n result = result.replaceAll(slot.searchStr, replacement);\n }\n }\n\n // Catch any remaining <img> tags without src\n result = result.replace(/<img\\s(?![^>]*\\bsrc=)([^>]*?)>/gi, (_match, attrs) => {\n const altMatch = attrs.match(/alt=\"([^\"]*?)\"/);\n const query = altMatch?.[1] || \"professional image\";\n return `<img src=\"https://placehold.co/800x500/1f2937/9ca3af?text=${encodeURIComponent(query.slice(0, 30))}\" ${attrs}>`;\n });\n\n return result;\n}\n","import { createAnthropic } from \"@ai-sdk/anthropic\";\nimport { generateText } from \"ai\";\nimport { currentDateLine } from \"../streamCore\";\n\nconst SVG_SYSTEM_PROMPT = `You are a professional SVG designer. Generate clean, compact SVG graphics for documents.\n\nSTRICT SIZE RULES:\n- ALWAYS use viewBox=\"0 0 600 300\" (2:1 ratio) — no exceptions\n- ALWAYS set width=\"100%\" height=\"auto\" — NEVER use fixed pixel width/height\n- NO internal padding or margins — content fills the viewBox edge-to-edge (leave only 10-20px padding)\n- Keep SVGs under 2KB — simplicity is key\n\nSTYLE RULES:\n- Output ONLY the <svg>...</svg> tag — no markdown, no explanation\n- Flat design: solid fills, no drop shadows, minimal gradients (max 1-2)\n- Max 8-10 elements total — prefer fewer, larger shapes over many small ones\n- Color palette: use the provided theme colors, or defaults (#6366f1, #8b5cf6, #ec4899, #14b8a6, #f59e0b)\n- Text: font-family=\"system-ui, sans-serif\", font-size 12-16px, max 5 text labels\n- Self-contained: no external references, all styles inline\n\nCHART TYPES:\n- Bar charts (vertical/horizontal) — max 6 bars, rounded caps\n- Pie/donut charts — max 5 segments\n- Line charts — smooth paths, max 8 data points\n- Progress/gauge charts\n- Simple comparison charts\n- Stat cards with visual elements\n\nAVOID: complex illustrations, many small elements, decorative borders, nested groups deeper than 2 levels.`;\n\n\nexport async function generateSvg(\n prompt: string,\n anthropicApiKey?: string,\n options?: { width?: number; height?: number; themeColors?: string }\n): Promise<string> {\n const apiKey = anthropicApiKey || process.env.ANTHROPIC_API_KEY;\n const anthropic = createAnthropic({ apiKey: apiKey || undefined });\n\n const sizeHint = options?.width && options?.height\n ? ` Target dimensions: ${options.width}x${options.height}px.`\n : \"\";\n const colorHint = options?.themeColors\n ? ` Use these theme colors: ${options.themeColors}.`\n : \"\";\n\n const result = await generateText({\n model: anthropic(\"claude-haiku-4-5-20251001\"),\n system: SVG_SYSTEM_PROMPT + currentDateLine(),\n messages: [\n {\n role: \"user\",\n content: `Generate an SVG for: ${prompt}${sizeHint}${colorHint}`,\n },\n ],\n maxOutputTokens: 2000,\n });\n\n // Extract just the SVG tag\n const svgMatch = result.text.match(/<svg[\\s\\S]*<\\/svg>/i);\n if (!svgMatch) {\n throw new Error(\"SVG generation failed — no <svg> tag in response\");\n }\n\n return svgMatch[0];\n}\n","import { streamText } from \"ai\";\nimport { createAnthropic } from \"@ai-sdk/anthropic\";\nimport { nanoid } from \"nanoid\";\nimport { findImageSlots } from \"./images/enrichImages\";\nimport { searchImage } from \"./images/pexels\";\nimport { generateImage } from \"./images/dalleImages\";\nimport { generateSvg } from \"./images/svgGenerator\";\nimport type { Section3 } from \"./types\";\nimport { sanitizeSemanticColors } from \"./sanitizeColors\";\n\nexport function currentDateLine(): string {\n return `\\nToday's date is ${new Date().toISOString().split(\"T\")[0]}. Use this for any date references.\\n`;\n}\n\n/**\n * Resolve AI model from available keys.\n * If modelId is already a LanguageModel object, return it directly.\n * Prefers Anthropic, falls back to OpenAI.\n */\nfunction isOpenAiModel(id: string): boolean {\n return /^(gpt-|o[1-9]|dall-e|tts-|whisper|chatgpt-)/.test(id);\n}\n\nfunction isLanguageModel(value: unknown): value is import(\"ai\").LanguageModel {\n return typeof value === \"object\" && value !== null && \"modelId\" in value && \"provider\" in value;\n}\n\nexport async function resolveModel(opts: {\n openaiApiKey?: string;\n anthropicApiKey?: string;\n modelId?: string | import(\"ai\").LanguageModel;\n defaultOpenai: string;\n defaultAnthropic: string;\n}) {\n // If modelId is already a model object, return it directly\n if (opts.modelId && isLanguageModel(opts.modelId)) {\n return opts.modelId;\n }\n\n const modelId = opts.modelId as string | undefined;\n\n if (modelId && isOpenAiModel(modelId)) {\n const openaiKey = opts.openaiApiKey || process.env.OPENAI_API_KEY;\n if (openaiKey) {\n const { createOpenAI } = await import(\"@ai-sdk/openai\");\n return createOpenAI({ apiKey: openaiKey })(modelId);\n }\n // OpenAI model requested but no key — fall through to Anthropic default\n } else if (modelId) {\n const anthropicKey = opts.anthropicApiKey || process.env.ANTHROPIC_API_KEY;\n if (anthropicKey) {\n return createAnthropic({ apiKey: anthropicKey })(modelId);\n }\n }\n // No explicit modelId — prefer Anthropic, fallback to OpenAI\n const anthropicKey = opts.anthropicApiKey || process.env.ANTHROPIC_API_KEY;\n if (anthropicKey) {\n return createAnthropic({ apiKey: anthropicKey })(opts.defaultAnthropic);\n }\n const openaiKey = opts.openaiApiKey || process.env.OPENAI_API_KEY;\n if (openaiKey) {\n const { createOpenAI } = await import(\"@ai-sdk/openai\");\n return createOpenAI({ apiKey: openaiKey })(opts.defaultOpenai);\n }\n return createAnthropic()(opts.defaultAnthropic);\n}\n\n/**\n * Convert data URL to Uint8Array for AI SDK vision.\n */\nexport function dataUrlToImagePart(dataUrl: string): { image: Uint8Array; mimeType: string } | null {\n const match = dataUrl.match(/^data:([^;]+);base64,(.+)$/);\n if (!match) return null;\n return {\n image: new Uint8Array(Buffer.from(match[2], \"base64\")),\n mimeType: match[1],\n };\n}\n\n/**\n * Extract complete JSON objects from accumulated text using brace-depth tracking.\n */\nexport function extractJsonObjects(text: string): [any[], string] {\n const objects: any[] = [];\n let remaining = text;\n\n while (remaining.length > 0) {\n remaining = remaining.trimStart();\n if (!remaining.startsWith(\"{\")) {\n const nextBrace = remaining.indexOf(\"{\");\n if (nextBrace === -1) break;\n remaining = remaining.slice(nextBrace);\n continue;\n }\n\n let depth = 0;\n let inString = false;\n let escape = false;\n let end = -1;\n\n for (let i = 0; i < remaining.length; i++) {\n const ch = remaining[i];\n if (escape) { escape = false; continue; }\n if (ch === \"\\\\\") { escape = true; continue; }\n if (ch === '\"') { inString = !inString; continue; }\n if (inString) continue;\n if (ch === \"{\") depth++;\n if (ch === \"}\") { depth--; if (depth === 0) { end = i; break; } }\n }\n\n if (end === -1) break;\n\n const candidate = remaining.slice(0, end + 1);\n remaining = remaining.slice(end + 1);\n\n try {\n objects.push(JSON.parse(candidate));\n } catch {\n // malformed, skip\n }\n }\n\n return [objects, remaining];\n}\n\n/** Inline shimmer SVG used as src for loading image placeholders */\nconst LOADING_PLACEHOLDER_SRC = `data:image/svg+xml,${encodeURIComponent('<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"800\" height=\"500\" viewBox=\"0 0 800 500\"><rect fill=\"#f3f4f6\" width=\"800\" height=\"500\" rx=\"12\"/><g opacity=\".4\"><rect x=\"320\" y=\"200\" width=\"160\" height=\"4\" rx=\"2\" fill=\"#d1d5db\"><animate attributeName=\"opacity\" values=\".3;.8;.3\" dur=\"1.5s\" repeatCount=\"indefinite\"/></rect><rect x=\"280\" y=\"215\" width=\"240\" height=\"4\" rx=\"2\" fill=\"#d1d5db\"><animate attributeName=\"opacity\" values=\".3;.8;.3\" dur=\"1.5s\" begin=\".3s\" repeatCount=\"indefinite\"/></rect><rect x=\"340\" y=\"230\" width=\"120\" height=\"4\" rx=\"2\" fill=\"#d1d5db\"><animate attributeName=\"opacity\" values=\".3;.8;.3\" dur=\"1.5s\" begin=\".6s\" repeatCount=\"indefinite\"/></rect></g><g transform=\"translate(376,150)\" opacity=\".3\"><path d=\"M0 28V4a4 4 0 014-4h40a4 4 0 014 4v24a4 4 0 01-4 4H4a4 4 0 01-4-4z\" fill=\"#d1d5db\"/><circle cx=\"14\" cy=\"12\" r=\"4\" fill=\"#9ca3af\"/><path d=\"M4 28l10-10 6 6 8-8 16 16H4z\" fill=\"#9ca3af\" opacity=\".5\"/></g></svg>')}`;\n\n/** Inline SVG placeholder for loading charts */\nconst SVG_LOADING_PLACEHOLDER = `<div class=\"w-full h-48 bg-gray-50 rounded-lg flex items-center justify-center animate-pulse\"><svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"#9ca3af\" stroke-width=\"1.5\"><rect x=\"3\" y=\"12\" width=\"4\" height=\"9\" rx=\"1\"/><rect x=\"10\" y=\"7\" width=\"4\" height=\"14\" rx=\"1\"/><rect x=\"17\" y=\"3\" width=\"4\" height=\"18\" rx=\"1\"/></svg></div>`;\n\n/** Replace data-svg-chart divs with loading placeholders */\nexport function addSvgLoadingPlaceholders(html: string): string {\n return html.replace(\n /<div\\s([^>]*?)data-svg-chart=\"([^\"]+)\"([^>]*?)>[\\s\\S]*?<\\/div>/gi,\n (_match, before, chart, after) => {\n return `<div ${before}data-svg-chart=\"${chart}\"${after}>${SVG_LOADING_PLACEHOLDER}</div>`;\n }\n );\n}\n\n/** Replace data-image-query attrs with animated loading placeholders */\nexport function addLoadingPlaceholders(html: string): string {\n return html.replace(\n /(<img\\s[^>]*)data-image-query=\"([^\"]+)\"([^>]*?)(?:\\s*\\/?>)/gi,\n (_match, before, query, after) => {\n if (before.includes('src=') || after.includes('src=')) return _match;\n return `${before}src=\"${LOADING_PLACEHOLDER_SRC}\" data-image-query=\"${query}\" alt=\"${query}\"${after}>`;\n }\n );\n}\n\n/** Enrich a section's images (Pexels → DALL-E → placeholder fallback). Mutates section.html in place. */\nexport async function enrichSectionImages(\n section: Section3,\n opts: {\n pexelsApiKey?: string;\n openaiApiKey?: string;\n persistImage?: (tempUrl: string, query: string) => Promise<string>;\n onImageUpdate?: (sectionId: string, html: string) => void;\n }\n): Promise<void> {\n const slots = findImageSlots(section.html);\n if (slots.length === 0) return;\n const results = await Promise.allSettled(\n slots.map(async (slot) => {\n let url: string | null = null;\n if (opts.pexelsApiKey) {\n const img = await searchImage(slot.query, opts.pexelsApiKey).catch(() => null);\n url = img?.url || null;\n }\n if (!url && opts.openaiApiKey) {\n try {\n const tempUrl = await generateImage(slot.query, opts.openaiApiKey);\n url = opts.persistImage ? await opts.persistImage(tempUrl, slot.query) : tempUrl;\n } catch (e) {\n console.warn(`[dalle] failed for \"${slot.query}\":`, e);\n }\n }\n url ??= `https://placehold.co/800x500/1f2937/9ca3af?text=${encodeURIComponent(slot.query.slice(0, 30))}`;\n return { slot, url };\n })\n );\n let html = section.html;\n for (const r of results) {\n if (r.status === \"fulfilled\" && r.value) {\n const { slot, url } = r.value;\n const replacement = slot.replaceStr.replace(\"{url}\", url);\n html = html.replaceAll(slot.searchStr, replacement);\n }\n }\n if (html !== section.html) {\n section.html = html;\n opts.onImageUpdate?.(section.id, html);\n }\n}\n\n/** Enrich a section's SVG chart placeholders. Mutates section.html in place. */\nexport async function enrichSectionSvgCharts(\n section: Section3,\n opts: {\n anthropicApiKey?: string;\n onImageUpdate?: (sectionId: string, html: string) => void;\n }\n): Promise<void> {\n const svgRegex = /<div\\s[^>]*data-svg-chart=\"([^\"]+)\"[^>]*>[\\s\\S]*?<\\/div>/gi;\n const svgMatches: { fullMatch: string; prompt: string }[] = [];\n let svgM: RegExpExecArray | null;\n while ((svgM = svgRegex.exec(section.html)) !== null) {\n svgMatches.push({ fullMatch: svgM[0], prompt: svgM[1] });\n }\n if (svgMatches.length === 0) return;\n const anthropicKey = opts.anthropicApiKey || process.env.ANTHROPIC_API_KEY;\n const results = await Promise.allSettled(\n svgMatches.map(async ({ fullMatch, prompt }) => {\n try {\n const svg = await generateSvg(prompt, anthropicKey);\n return { fullMatch, svg };\n } catch (e) {\n console.warn(`[svg] failed for \"${prompt}\":`, e);\n return { fullMatch, svg: `<div class=\"w-full h-48 bg-gray-100 rounded-lg flex items-center justify-center text-gray-400 text-sm\">${prompt}</div>` };\n }\n })\n );\n let html = section.html;\n for (const r of results) {\n if (r.status === \"fulfilled\" && r.value) {\n html = html.replace(r.value.fullMatch, r.value.svg);\n }\n }\n if (html !== section.html) {\n section.html = html;\n opts.onImageUpdate?.(section.id, html);\n }\n}\n\nexport interface StreamGenerateOptions {\n /** Anthropic API key */\n anthropicApiKey?: string;\n /** OpenAI API key */\n openaiApiKey?: string;\n /** Model ID override or pre-built LanguageModel object */\n model?: string | import(\"ai\").LanguageModel;\n /** System prompt */\n systemPrompt: string;\n /** User message content (text or multimodal parts) */\n userContent: any[];\n /** Pexels API key for image enrichment */\n pexelsApiKey?: string;\n /** Persist DALL-E images to permanent storage */\n persistImage?: (tempUrl: string, query: string) => Promise<string>;\n /** Called when a new section is parsed */\n onSection?: (section: Section3) => void;\n /** Called when a section's images are enriched */\n onImageUpdate?: (sectionId: string, html: string) => void;\n /** Called with raw text buffer for real-time partial streaming */\n onRawChunk?: (buffer: string, completedCount: number) => void;\n /** Called when generation is complete */\n onDone?: (sections: Section3[]) => void;\n /** Called on error */\n onError?: (error: Error) => void;\n}\n\n/**\n * Core streaming generation: stream AI text → parse NDJSON → emit sections → enrich images.\n * Used by both generateLanding and generateDocument.\n */\nexport async function streamGenerate(options: StreamGenerateOptions): Promise<Section3[]> {\n const {\n anthropicApiKey,\n openaiApiKey: _openaiApiKey,\n model: modelId,\n systemPrompt,\n userContent,\n pexelsApiKey,\n persistImage,\n onSection,\n onImageUpdate,\n onRawChunk,\n onDone,\n onError,\n } = options;\n\n const openaiApiKey = _openaiApiKey || process.env.OPENAI_API_KEY;\n const model = await resolveModel({\n openaiApiKey,\n anthropicApiKey,\n modelId,\n defaultOpenai: \"gpt-4o\",\n defaultAnthropic: \"claude-sonnet-4-6\",\n });\n\n const result = streamText({\n model,\n system: systemPrompt + currentDateLine(),\n messages: [{ role: \"user\", content: userContent }],\n });\n\n const allSections: Section3[] = [];\n const imagePromises: Promise<void>[] = [];\n let sectionOrder = 0;\n let buffer = \"\";\n\n function enrichSvgCharts(sectionRef: Section3) {\n const svgRegex = /<div\\s[^>]*data-svg-chart=\"([^\"]+)\"[^>]*>[\\s\\S]*?<\\/div>/gi;\n const svgMatches: { fullMatch: string; prompt: string }[] = [];\n let svgM: RegExpExecArray | null;\n while ((svgM = svgRegex.exec(sectionRef.html)) !== null) {\n svgMatches.push({ fullMatch: svgM[0], prompt: svgM[1] });\n }\n if (svgMatches.length === 0) return;\n\n const anthropicKey = anthropicApiKey || process.env.ANTHROPIC_API_KEY;\n imagePromises.push(\n (async () => {\n const results = await Promise.allSettled(\n svgMatches.map(async ({ fullMatch, prompt }) => {\n try {\n const svg = await generateSvg(prompt, anthropicKey);\n return { fullMatch, svg };\n } catch (e) {\n console.warn(`[svg] failed for \"${prompt}\":`, e);\n return { fullMatch, svg: `<div class=\"w-full h-48 bg-gray-100 rounded-lg flex items-center justify-center text-gray-400 text-sm\">${prompt}</div>` };\n }\n })\n );\n let html = sectionRef.html;\n for (const r of results) {\n if (r.status === \"fulfilled\" && r.value) {\n html = html.replace(r.value.fullMatch, r.value.svg);\n }\n }\n if (html !== sectionRef.html) {\n sectionRef.html = html;\n onImageUpdate?.(sectionRef.id, html);\n }\n })()\n );\n }\n\n function enrichSection(sectionRef: Section3) {\n const slots = findImageSlots(sectionRef.html);\n if (slots.length === 0) return;\n const slotsSnapshot = slots.map((s) => ({ ...s }));\n imagePromises.push(\n (async () => {\n const results = await Promise.allSettled(\n slotsSnapshot.map(async (slot) => {\n let url: string | null = null;\n // 1. Pexels first (free, fast)\n if (pexelsApiKey) {\n const img = await searchImage(slot.query, pexelsApiKey).catch(() => null);\n url = img?.url || null;\n }\n // 2. DALL-E fallback\n if (!url && openaiApiKey) {\n try {\n const tempUrl = await generateImage(slot.query, openaiApiKey);\n url = persistImage ? await persistImage(tempUrl, slot.query) : tempUrl;\n } catch (e) {\n console.warn(`[dalle] failed for \"${slot.query}\":`, e);\n }\n }\n url ??= `https://placehold.co/800x500/1f2937/9ca3af?text=${encodeURIComponent(slot.query.slice(0, 30))}`;\n return { slot, url };\n })\n );\n let html = sectionRef.html;\n for (const r of results) {\n if (r.status === \"fulfilled\" && r.value) {\n const { slot, url } = r.value;\n const replacement = slot.replaceStr.replace(\"{url}\", url);\n html = html.replaceAll(slot.searchStr, replacement);\n }\n }\n if (html !== sectionRef.html) {\n sectionRef.html = html;\n onImageUpdate?.(sectionRef.id, html);\n }\n })()\n );\n }\n\n function processObject(obj: any) {\n if (!obj.html || !obj.label) return;\n const section: Section3 = {\n id: nanoid(8),\n order: sectionOrder++,\n html: sanitizeSemanticColors(addSvgLoadingPlaceholders(addLoadingPlaceholders(obj.html))),\n label: obj.label,\n };\n allSections.push(section);\n onSection?.(section);\n enrichSection(section);\n enrichSvgCharts(section);\n }\n\n try {\n let chunkCount = 0;\n for await (const chunk of result.textStream) {\n buffer += chunk;\n chunkCount++;\n\n const [objects, remaining] = extractJsonObjects(buffer);\n buffer = remaining;\n for (const obj of objects) {\n chunkCount = 0;\n processObject(obj);\n }\n\n if (onRawChunk && chunkCount % 5 === 0 && buffer.length > 20) {\n onRawChunk(buffer, allSections.length);\n }\n }\n\n // Parse remaining buffer\n if (buffer.trim()) {\n let cleaned = buffer.trim();\n if (cleaned.startsWith(\"```\")) {\n cleaned = cleaned.replace(/^```(?:json)?\\s*/, \"\").replace(/\\s*```$/, \"\");\n }\n const [lastObjects] = extractJsonObjects(cleaned);\n for (const obj of lastObjects) processObject(obj);\n }\n\n // Wait for image enrichment\n await Promise.allSettled(imagePromises);\n\n // Final fallback for images without src\n for (const section of allSections) {\n const before = section.html;\n section.html = section.html.replace(\n /<img\\s(?![^>]*\\bsrc=)([^>]*?)>/gi,\n (_match, attrs) => {\n const altMatch = attrs.match(/alt=\"([^\"]*?)\"/);\n const query = altMatch?.[1] || \"image\";\n return `<img src=\"https://placehold.co/800x500/1f2937/9ca3af?text=${encodeURIComponent(query.slice(0, 30))}\" ${attrs}>`;\n }\n );\n section.html = section.html.replace(\n /data-image-query=\"([^\"]+)\"/g,\n (_match, query) => {\n return `src=\"https://placehold.co/800x500/1f2937/9ca3af?text=${encodeURIComponent(query.slice(0, 30))}\" data-enriched=\"placeholder\"`;\n }\n );\n if (section.html !== before) {\n onImageUpdate?.(section.id, section.html);\n }\n }\n\n onDone?.(allSections);\n return allSections;\n } catch (err: any) {\n const error = err instanceof Error ? err : new Error(err?.message || \"Generation failed\");\n onError?.(error);\n throw error;\n }\n}\n","/**\n * Replace hardcoded Tailwind color classes with semantic color classes.\n *\n * Two layers:\n * 1. Neutral colors: bg-white → bg-surface, text-black → text-on-surface, bg-gray-* → semantic\n * 2. Chromatic colors: bg-blue-500 → bg-secondary, bg-green-500 → bg-accent, etc.\n *\n * Maps chromatic colors by family:\n * - Blues/indigos/violet → secondary\n * - Greens/teals/emerald/cyan → accent\n * - Everything else → primary\n */\n\nconst COLORS =\n \"red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose\";\n\nconst SECONDARY_COLORS = \"blue|indigo|violet\";\nconst ACCENT_COLORS = \"green|emerald|teal|cyan\";\n\nfunction categorize(color: string): \"primary\" | \"secondary\" | \"accent\" {\n if (new RegExp(`^(?:${SECONDARY_COLORS})$`).test(color)) return \"secondary\";\n if (new RegExp(`^(?:${ACCENT_COLORS})$`).test(color)) return \"accent\";\n return \"primary\";\n}\n\n// ── Neutral replacements (bg-white, text-black, bg-gray-*, text-gray-*, etc.) ──\nconst NEUTRALS = \"slate|gray|zinc|neutral|stone\";\n\nconst neutralReplacements: [RegExp, string][] = [\n // bg-white → bg-surface\n [/\\bbg-white\\b/g, \"bg-surface\"],\n // bg-black → bg-primary-dark\n [/\\bbg-black\\b/g, \"bg-primary-dark\"],\n // text-white → text-on-primary\n [/\\btext-white\\b/g, \"text-on-primary\"],\n // text-black → text-on-surface\n [/\\btext-black\\b/g, \"text-on-surface\"],\n\n // bg-gray-50/100 → bg-surface\n [new RegExp(`\\\\bbg-(${NEUTRALS})-(50|100)\\\\b`, \"g\"), \"bg-surface\"],\n // bg-gray-200/300 → bg-surface-alt\n [new RegExp(`\\\\bbg-(${NEUTRALS})-(200|300)\\\\b`, \"g\"), \"bg-surface-alt\"],\n // bg-gray-400-600 → bg-primary\n [new RegExp(`\\\\bbg-(${NEUTRALS})-(400|500|600)\\\\b`, \"g\"), \"bg-primary\"],\n // bg-gray-700-950 → bg-primary-dark\n [new RegExp(`\\\\bbg-(${NEUTRALS})-(700|800|900|950)\\\\b`, \"g\"), \"bg-primary-dark\"],\n\n // text-gray-300/400 → text-on-surface-muted\n [new RegExp(`\\\\btext-(${NEUTRALS})-(300|400)\\\\b`, \"g\"), \"text-on-surface-muted\"],\n // text-gray-500/600 → text-on-surface-muted\n [new RegExp(`\\\\btext-(${NEUTRALS})-(500|600)\\\\b`, \"g\"), \"text-on-surface-muted\"],\n // text-gray-700/800/900 → text-on-surface\n [new RegExp(`\\\\btext-(${NEUTRALS})-(700|800|900|950)\\\\b`, \"g\"), \"text-on-surface\"],\n // text-gray-50/100/200 → text-on-primary\n [new RegExp(`\\\\btext-(${NEUTRALS})-(50|100|200)\\\\b`, \"g\"), \"text-on-primary\"],\n\n // hover:bg-gray → hover semantic\n [new RegExp(`\\\\bhover:bg-(${NEUTRALS})-(50|100|200|300)\\\\b`, \"g\"), \"hover:bg-surface-alt\"],\n [new RegExp(`\\\\bhover:bg-(${NEUTRALS})-(400|500|600|700|800|900|950)\\\\b`, \"g\"), \"hover:bg-primary-dark\"],\n\n // hover:text neutrals\n [new RegExp(`\\\\bhover:text-(${NEUTRALS})-\\\\d{2,3}\\\\b`, \"g\"), \"hover:text-on-surface\"],\n];\n\n// ── Chromatic replacements ──\nfunction buildChromaticReplacements(): [RegExp, (match: string, color: string) => string][] {\n const re = (prefix: string, shades: string) =>\n new RegExp(`\\\\b${prefix}-(${COLORS})-(${shades})\\\\b`, \"g\");\n\n return [\n // Background\n [re(\"bg\", \"500|600|700\"), (_m, c) => `bg-${categorize(c)}`],\n [re(\"bg\", \"50|100\"), (_m, c) => `bg-${categorize(c)}-light`],\n [re(\"bg\", \"800|900|950\"), (_m, c) => `bg-${categorize(c)}-dark`],\n [re(\"bg\", \"200|300|400\"), (_m, c) => `bg-${categorize(c)}`],\n\n // Text\n [re(\"text\", \"500|600|700\"), (_m, c) => `text-${categorize(c)}`],\n [re(\"text\", \"800|900|950\"), (_m, c) => `text-${categorize(c)}-dark`],\n [re(\"text\", \"50|100|200|300\"), (_m, c) => `text-on-${categorize(c)}`],\n [re(\"text\", \"400\"), (_m, c) => `text-${categorize(c)}`],\n\n // Border\n [re(\"border\", \"\\\\d{2,3}\"), (_m, c) => `border-${categorize(c)}`],\n\n // Ring\n [re(\"ring\", \"\\\\d{2,3}\"), (_m, c) => `ring-${categorize(c)}`],\n\n // Gradients\n [re(\"from\", \"\\\\d{2,3}\"), (_m, c) => `from-${categorize(c)}`],\n [re(\"to\", \"\\\\d{2,3}\"), (_m, c) => `to-${categorize(c)}`],\n [re(\"via\", \"\\\\d{2,3}\"), (_m, c) => `via-${categorize(c)}`],\n\n // Hover/focus variants\n [new RegExp(`\\\\bhover:bg-(${COLORS})-(500|600|700|800|900|950)\\\\b`, \"g\"), (_m, c) => `hover:bg-${categorize(c)}-dark`],\n [new RegExp(`\\\\bhover:bg-(${COLORS})-(50|100|200|300|400)\\\\b`, \"g\"), (_m, c) => `hover:bg-${categorize(c)}-light`],\n [new RegExp(`\\\\bhover:text-(${COLORS})-\\\\d{2,3}\\\\b`, \"g\"), (_m, c) => `hover:text-${categorize(c)}`],\n [new RegExp(`\\\\bfocus:ring-(${COLORS})-\\\\d{2,3}\\\\b`, \"g\"), (_m, c) => `focus:ring-${categorize(c)}`],\n [new RegExp(`\\\\bfocus:border-(${COLORS})-\\\\d{2,3}\\\\b`, \"g\"), (_m, c) => `focus:border-${categorize(c)}`],\n\n // Divide\n [re(\"divide\", \"\\\\d{2,3}\"), (_m, c) => `divide-${categorize(c)}`],\n\n // Placeholder\n [re(\"placeholder\", \"\\\\d{2,3}\"), (_m, c) => `placeholder-${categorize(c)}`],\n\n // Outline\n [re(\"outline\", \"\\\\d{2,3}\"), (_m, c) => `outline-${categorize(c)}`],\n\n // Shadow colored\n [re(\"shadow\", \"\\\\d{2,3}\"), (_m, c) => `shadow-${categorize(c)}`],\n\n // Decoration\n [re(\"decoration\", \"\\\\d{2,3}\"), (_m, c) => `decoration-${categorize(c)}`],\n\n // Accent (form accent color)\n [re(\"accent\", \"\\\\d{2,3}\"), (_m, c) => `accent-${categorize(c)}`],\n ];\n}\n\nconst chromaticReplacements = buildChromaticReplacements();\n\nexport function sanitizeSemanticColors(html: string): string {\n let result = html;\n\n // 1. Replace neutral colors (bg-white, text-black, bg-gray-*, etc.)\n for (const [pattern, replacement] of neutralReplacements) {\n result = result.replace(pattern, replacement);\n }\n\n // 2. Replace chromatic colors (bg-blue-500, text-red-700, etc.)\n for (const [pattern, replacer] of chromaticReplacements) {\n result = result.replace(pattern, replacer as any);\n }\n\n return result;\n}\n"],"mappings":";AAMA,eAAsB,YAAY,OAAe,QAA+C;AAC9F,QAAM,MAAM,UAAU,QAAQ,IAAI;AAClC,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,MAAM,MAAM;AAAA,MAChB,0CAA0C,mBAAmB,KAAK,CAAC;AAAA,MACnE,EAAE,SAAS,EAAE,eAAe,IAAI,EAAE;AAAA,IACpC;AACA,QAAI,CAAC,IAAI,IAAI;AACX,cAAQ,KAAK,YAAY,IAAI,MAAM,SAAS,KAAK,6BAA6B;AAC9E,aAAO,eAAe,KAAK;AAAA,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AM,YAAYC,iBAAgB,EAAE,QAAQ,UAAU,OAAU,CAAC;AAEjE,QAAM,WAAW,SAAS,SAAS,SAAS,SACxC,uBAAuB,QAAQ,KAAK,IAAI,QAAQ,MAAM,QACtD;AACJ,QAAM,YAAY,SAAS,cACvB,4BAA4B,QAAQ,WAAW,MAC/C;AAEJ,QAAM,SAAS,MAAM,aAAa;AAAA,IAChC,OAAO,UAAU,2BAA2B;AAAA,IAC5C,QAAQ,oBAAoB,gBAAgB;AAAA,IAC5C,UAAU;AAAA,MACR;AAAA,QACE,MAAM;AAAA,QACN,SAAS,wBAAwB,MAAM,GAAG,QAAQ,GAAG,SAAS;AAAA,MAChE;AAAA,IACF;AAAA,IACA,iBAAiB;AAAA,EACnB,CAAC;AAGD,QAAM,WAAW,OAAO,KAAK,MAAM,qBAAqB;AACxD,MAAI,CAAC,UAAU;AACb,UAAM,IAAI,MAAM,uDAAkD;AAAA,EACpE;AAEA,SAAO,SAAS,CAAC;AACnB;","names":["createAnthropic","openaiKey","anthropicKey","createAnthropic"]}
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  currentDateLine,
3
3
  resolveModel
4
- } from "./chunk-RBZ3YLOZ.js";
4
+ } from "./chunk-VKIIKF4Q.js";
5
5
 
6
6
  // src/directions.ts
7
7
  import { generateObject, streamText } from "ai";
@@ -6,6 +6,7 @@ import { S as Section3 } from './types-BIpbpCJr.js';
6
6
  declare function extractJsonObjects(text: string): [any[], string];
7
7
 
8
8
  declare const SYSTEM_PROMPT = "You are a world-class web designer who creates AWARD-WINNING landing pages. Your designs win Awwwards, FWA, and CSS Design Awards. You think in terms of visual hierarchy, whitespace, and emotional impact.\n\nRULES:\n- Each section is a complete <section> tag with Tailwind CSS classes\n- Use Tailwind CDN classes ONLY (no custom CSS, no @apply, no @import, no @tailwind directives)\n- NO JavaScript, only HTML+Tailwind\n- Each section must be independent and self-contained\n- Responsive: mobile-first with sm/md/lg/xl breakpoints\n- All text content in Spanish unless the prompt specifies otherwise\n- Use real-looking content (not Lorem ipsum) \u2014 make it specific to the prompt\n\nRESPONSIVE \u2014 MANDATORY:\n- EVERY grid: grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 (NEVER grid-cols-3 alone)\n- EVERY flex row: flex flex-col md:flex-row (NEVER flex flex-row alone)\n- Text sizes: text-3xl md:text-5xl lg:text-7xl (NEVER text-7xl alone)\n- Images: w-full h-auto object-cover max-w-full\n- Padding: px-4 md:px-8 lg:px-16 (NEVER px-16 alone)\n- Hide decorative on mobile if breaks layout: hidden md:block\n\nIMAGES \u2014 CRITICAL:\n- EVERY image MUST use: <img data-image-query=\"english search query\" alt=\"description\" class=\"w-full h-auto object-cover rounded-xl\"/>\n- NEVER use <img> without data-image-query\n- NEVER include a src attribute \u2014 the system auto-replaces data-image-query with a real image URL\n- Queries must be generic stock-photo friendly (e.g. \"modern office\" not \"Juan's cybercafe\")\n- For avatar-like elements, use colored divs with initials instead of img tags (e.g. <div class=\"w-10 h-10 rounded-full bg-primary flex items-center justify-center text-on-primary font-bold\">JD</div>)\n\nIMAGE OVERLAYS \u2014 CRITICAL:\n- When using images as backgrounds or behind text, ALWAYS add a gradient overlay for text readability\n- Pattern: <div class=\"relative\"><img data-image-query=\"...\" alt=\"...\" class=\"absolute inset-0 w-full h-full object-cover\"/><div class=\"absolute inset-0 bg-gradient-to-r from-primary/80 to-transparent\"></div><div class=\"relative z-10\">...text...</div></div>\n- NEVER place text directly on images without an overlay\n- For hero sections with background images: use bg-gradient-to-t from-primary-dark/90 via-primary-dark/50 to-transparent\n- For testimonial/quote backgrounds: use bg-surface/90 backdrop-blur-sm on the card\n\nCOLOR SYSTEM \u2014 CRITICAL (READ CAREFULLY):\n- Use semantic color classes: bg-primary, text-primary, bg-primary-light, bg-primary-dark, text-on-primary, bg-surface, bg-surface-alt, text-on-surface, text-on-surface-muted, bg-secondary, text-secondary, bg-accent, text-accent\n- NEVER use hardcoded Tailwind color classes: NO bg-gray-*, bg-black, bg-white, bg-indigo-*, bg-blue-*, bg-purple-*, text-gray-*, text-black, text-white, etc.\n- The ONLY exception: border-gray-200 or border-gray-700 for subtle dividers.\n- ALL backgrounds MUST use: bg-primary, bg-primary-dark, bg-surface, bg-surface-alt\n- ALL text MUST use: text-on-surface, text-on-surface-muted, text-on-primary, text-accent. Use text-primary ONLY on bg-surface/bg-surface-alt (it's the same hue as bg-primary \u2014 invisible on primary backgrounds).\n- CONTRAST RULE: on bg-primary or bg-primary-dark \u2192 use ONLY text-on-primary. On bg-surface or bg-surface-alt \u2192 use text-on-surface, text-on-surface-muted, or text-primary. NEVER use text-primary on bg-primary \u2014 they are the SAME COLOR. NEVER put text-on-surface on bg-primary or text-on-primary on bg-surface. text-accent is decorative \u2014 use sparingly on bg-surface/bg-surface-alt only.\n- ANTI-PATTERN: NEVER put bg-primary on BOTH the section AND elements inside it. If section is bg-primary, inner cards/elements should be bg-surface. If section is bg-surface, cards can use bg-surface-alt or bg-primary.\n- For gradients: from-primary to-primary-dark, from-surface to-surface-alt\n- For hover: hover:bg-primary-dark, hover:bg-primary-light\n\nCOLOR VARIETY \u2014 MANDATORY:\n- ALTERNATE section backgrounds: bg-surface \u2192 bg-primary \u2192 bg-surface-alt \u2192 bg-primary-dark \u2192 bg-surface\n- Use bg-accent for at least ONE section (CTA or highlight section)\n- Use bg-secondary for at least ONE section (features or stats)\n- Cards on dark sections (bg-primary, bg-primary-dark) MUST be bg-surface (light cards on dark bg = visual pop)\n- Cards on light sections (bg-surface) can use bg-surface-alt or bg-primary-light\n- Use text-accent for decorative elements: labels, badges, icons, highlights, underlines\n- Use text-secondary for secondary information, tags, category labels\n- Gradients: mix colors creatively \u2014 from-primary to-accent for CTAs, from-secondary to-primary for headers\n- Buttons: primary CTA = bg-accent text-on-accent, secondary CTA = bg-secondary text-on-secondary or border-primary\n\nDESIGN PHILOSOPHY \u2014 what separates good from GREAT:\n- WHITESPACE is your best friend. Generous padding (py-24, py-32, px-8). Let elements breathe.\n- CONTRAST: mix dark sections with light ones. Alternate bg-primary and bg-surface sections.\n- TYPOGRAPHY: use extreme size differences for hierarchy (text-7xl headline next to text-sm label)\n- DEPTH: overlapping elements, negative margins (-mt-12), z-index layering, shadows\n- ASYMMETRY: avoid centering everything. Use grid-cols-5 with col-span-3 + col-span-2. Offset elements.\n- TEXTURE: use subtle patterns, gradients, border treatments, rounded-3xl mixed with sharp edges\n- Each section should have a COMPLETELY DIFFERENT layout from the others\n\nSECTION LAYOUT \u2014 CRITICAL:\n- Each <section> must be full-width (bg goes edge-to-edge). NO max-w on the section itself.\n- Constrain content inside with a wrapper div: <section class=\"bg-primary py-24\"><div class=\"max-w-7xl mx-auto px-4 md:px-8\">...content...</div></section>\n- EVERY section follows this pattern. The <section> handles bg color + vertical padding. The inner <div> handles horizontal padding + max-width.\n\nTESTIMONIALS SECTION:\n- Cards MUST use bg-surface or bg-surface-alt with text-on-surface\n- If section bg is bg-primary or bg-primary-dark, cards MUST be bg-surface (light cards on dark bg)\n- Quote text: text-on-surface, italic\n- Avatar: colored div with initials (bg-accent text-on-primary or bg-primary-light text-on-primary)\n- Name: text-on-surface font-semibold. Role/company: text-on-surface-muted\n- NEVER use same dark bg for both section AND cards\n\nHERO SECTION \u2014 your masterpiece:\n- Use a 2-column grid (lg:grid-cols-2) that fills the full height, NOT content floating in empty space\n- Left column: headline + description + CTAs, vertically centered with flex flex-col justify-center\n- Right column: large hero image (data-image-query) filling the column, or a bento-grid of image + stat cards\n- Bold oversized headline (text-4xl md:text-6xl lg:text-7xl font-black leading-tight)\n- Tag/label above headline (uppercase, tracking-wider, text-xs text-accent)\n- Short description paragraph (text-lg text-on-surface-muted, max-w-lg)\n- 2 CTAs: primary (large, px-8 py-4, with \u2192 arrow) + secondary (ghost/outlined)\n- Optional: social proof bar below CTAs (avatar stack + \"2,847+ users\" text)\n- Min height: min-h-[90vh] with items-center on the grid so content is vertically centered\n- CRITICAL: the grid must stretch to fill the section height. Use min-h-[90vh] on the grid container itself, not just the section\n- NEVER leave large empty areas \u2014 if using min-h-[90vh], content must be centered/distributed within it\n\nTAILWIND v3 NOTES:\n- Standard Tailwind v3 classes (shadow-sm, shadow-md, rounded-md, etc.)\n- Borders: border + border-gray-200 for visible borders";
9
+ /** @deprecated Use buildPromptSuffix(prompt) internally. Kept for backward compat. */
9
10
  declare const PROMPT_SUFFIX = "\n\nOUTPUT FORMAT: NDJSON \u2014 one JSON object per line, NO wrapper array, NO markdown fences.\nEach line: {\"label\": \"Short Label\", \"html\": \"<section>...</section>\"}\n\nGenerate 7-9 sections. Always start with Hero and end with Footer.\nIMPORTANT: Make each section VISUALLY UNIQUE \u2014 different layouts, different background colors, different grid structures.\nThink like a premium design agency creating a $50K landing page.\nNO generic Bootstrap layouts. Use creative grids, bento layouts, overlapping elements, asymmetric columns.";
10
11
  interface GenerateOptions {
11
12
  anthropicApiKey?: string;
package/dist/generate.js CHANGED
@@ -2,10 +2,10 @@ import {
2
2
  PROMPT_SUFFIX,
3
3
  SYSTEM_PROMPT,
4
4
  generateLanding
5
- } from "./chunk-KBO6XLYA.js";
5
+ } from "./chunk-RUOBAHYV.js";
6
6
  import {
7
7
  extractJsonObjects
8
- } from "./chunk-RBZ3YLOZ.js";
8
+ } from "./chunk-VKIIKF4Q.js";
9
9
  export {
10
10
  PROMPT_SUFFIX,
11
11
  SYSTEM_PROMPT,
@@ -3,8 +3,8 @@ import {
3
3
  DOCUMENT_SYSTEM_PROMPT,
4
4
  generateDocument,
5
5
  generateDocumentParallel
6
- } from "./chunk-RGKK2HBC.js";
7
- import "./chunk-RBZ3YLOZ.js";
6
+ } from "./chunk-QF7UX3XK.js";
7
+ import "./chunk-VKIIKF4Q.js";
8
8
  export {
9
9
  DOCUMENT_PROMPT_SUFFIX,
10
10
  DOCUMENT_SYSTEM_PROMPT,
package/dist/images.js CHANGED
@@ -5,7 +5,7 @@ import {
5
5
  generateImage,
6
6
  generateSvg,
7
7
  searchImage
8
- } from "./chunk-RBZ3YLOZ.js";
8
+ } from "./chunk-VKIIKF4Q.js";
9
9
  export {
10
10
  enrichImages,
11
11
  findImageSlots,
package/dist/index.js CHANGED
@@ -10,16 +10,16 @@ import {
10
10
  PROMPT_SUFFIX,
11
11
  SYSTEM_PROMPT,
12
12
  generateLanding
13
- } from "./chunk-KBO6XLYA.js";
13
+ } from "./chunk-RUOBAHYV.js";
14
14
  import {
15
15
  DOCUMENT_PROMPT_SUFFIX,
16
16
  DOCUMENT_SYSTEM_PROMPT,
17
17
  generateDocument
18
- } from "./chunk-RGKK2HBC.js";
18
+ } from "./chunk-QF7UX3XK.js";
19
19
  import {
20
20
  REFINE_SYSTEM,
21
21
  refineLanding
22
- } from "./chunk-CFMB3Q7N.js";
22
+ } from "./chunk-O3F4GY2V.js";
23
23
  import {
24
24
  deployToEasyBits,
25
25
  deployToS3
@@ -41,7 +41,7 @@ import {
41
41
  generateImage,
42
42
  generateSvg,
43
43
  searchImage
44
- } from "./chunk-RBZ3YLOZ.js";
44
+ } from "./chunk-VKIIKF4Q.js";
45
45
  export {
46
46
  Canvas,
47
47
  CodeEditor,
package/dist/refine.js CHANGED
@@ -2,8 +2,8 @@ import {
2
2
  REFINE_SYSTEM,
3
3
  extractSectionDescription,
4
4
  refineLanding
5
- } from "./chunk-CFMB3Q7N.js";
6
- import "./chunk-RBZ3YLOZ.js";
5
+ } from "./chunk-O3F4GY2V.js";
6
+ import "./chunk-VKIIKF4Q.js";
7
7
  export {
8
8
  REFINE_SYSTEM,
9
9
  extractSectionDescription,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@easybits.cloud/html-tailwind-generator",
3
- "version": "0.2.115",
3
+ "version": "0.2.117",
4
4
  "description": "AI-powered landing page generator with Tailwind CSS — canvas editor, streaming generation, and one-click deploy",
5
5
  "license": "PolyForm-Noncommercial-1.0.0",
6
6
  "type": "module",