@easybits.cloud/html-tailwind-generator 0.2.125 → 0.2.126

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.
@@ -16,12 +16,31 @@ import {
16
16
  import { generateObject, streamText } from "ai";
17
17
  import { z } from "zod";
18
18
  import { nanoid } from "nanoid";
19
- var DOCUMENT_SYSTEM_PROMPT = `You are a professional document designer who creates stunning letter-sized (8.5" \xD7 11") document pages using HTML + Tailwind CSS.
19
+ var PAGE_FORMAT_CONFIG = {
20
+ letter: {
21
+ container: "w-[8.5in] h-[11in]",
22
+ bodyText: "text-sm or text-base (10-11px)",
23
+ maxColumns: 2,
24
+ heightMode: "fixed at 11in",
25
+ description: 'letter-sized (8.5" \xD7 11") document pages'
26
+ },
27
+ web: {
28
+ container: "w-[1280px] min-h-[800px]",
29
+ bodyText: "text-base or text-lg (16-18px)",
30
+ maxColumns: 1,
31
+ heightMode: "flexible, no max height",
32
+ description: "web-optimized document sections"
33
+ }
34
+ };
35
+ function getDocumentSystemPrompt(format = "letter") {
36
+ const cfg = PAGE_FORMAT_CONFIG[format];
37
+ const isWeb = format === "web";
38
+ return `You are a professional document designer who creates stunning ${cfg.description} using HTML + Tailwind CSS.
20
39
 
21
40
  RULES:
22
- - Each page is a <section> element sized for letter paper
23
- - Page structure: <section class="w-[8.5in] h-[11in] relative overflow-hidden flex flex-col">
24
- - The section is EXACTLY 11in tall \u2014 content MUST fit, never exceed. Use flex flex-col so children can use flex-1.
41
+ - Each page is a <section> element${isWeb ? " optimized for web viewing" : " sized for letter paper"}
42
+ - Page structure: <section class="${cfg.container} relative overflow-hidden flex flex-col">
43
+ - ${isWeb ? "Each section has flexible height \u2014 content determines the height. Use min-h-[800px] but allow natural growth." : "The section is EXACTLY 11in tall \u2014 content MUST fit, never exceed. Use flex flex-col so children can use flex-1."}
25
44
  - The section itself has NO padding \u2014 backgrounds, gradients, and decorative elements go edge-to-edge
26
45
  - Use slot layout: shrink-0 for header/footer bands, flex-1 overflow-hidden for main content area
27
46
  - For text content, use an inner wrapper: <div class="flex-1 overflow-hidden px-[0.75in] py-[0.5in]">...content...</div>
@@ -32,28 +51,28 @@ RULES:
32
51
  - NO JavaScript, only HTML+Tailwind
33
52
  - All text content in Spanish unless the prompt specifies otherwise
34
53
  - Use real content from the source material, not Lorem ipsum
35
- - NOT responsive \u2014 fixed letter size, no breakpoints needed
54
+ - NOT responsive \u2014 fixed ${isWeb ? "width" : "letter size"}, no breakpoints needed
36
55
  - Sections can have ANY background \u2014 full-bleed color, gradients, or white. Not limited to white paper.
37
56
 
38
57
  STRICT PROHIBITIONS:
39
58
  1. **NO EMOJI** \u2014 Never use emoji characters (\u{1F680}\u274C\u2705\u{1F4CA} etc.). Instead use inline SVG icons or colored divs. For bullet decorators use small colored circles (<span class="w-2 h-2 rounded-full bg-primary inline-block"></span>) or simple SVG.
40
59
  2. **NO Chart.js / NO JavaScript** \u2014 Never reference Chart.js, canvas, or any JS library. For data visualization use pure CSS: progress bars (div with percentage width + bg-primary), horizontal bars, styled tables with colored cells. Never use <canvas> or <script>.
41
- 3. **NO buttons or CTAs** \u2014 This is a print document, not a web page. No "Contactar", "Ver m\xE1s", "Comprar" buttons. Use text with contact info instead.
60
+ 3. **NO buttons or CTAs** \u2014 This is a ${isWeb ? "document" : "print document"}, not a ${isWeb ? "landing page" : "web page"}. No "Contactar", "Ver m\xE1s", "Comprar" buttons. Use text with contact info instead.
42
61
  4. **CONTRAST IS MANDATORY** \u2014 Dark/colored backgrounds (bg-primary, bg-primary-dark, bg-secondary, dark gradients) MUST use text-white or text-on-primary. Light backgrounds (white, bg-surface, bg-surface-alt) MUST use text-gray-900 or text-on-surface. NEVER use dark text on dark backgrounds or light text on light backgrounds.
43
62
  5. **Max 2 font weights per page** \u2014 Pick 2 (e.g. font-semibold + font-normal, or font-bold + font-light). Don't mix 4-5 weights.
44
63
  6. **Generous whitespace** \u2014 Don't fill every centimeter. Leave breathing room. Use py-8, py-12, gap-6, gap-8 liberally. Less content per page = more professional.
45
64
 
46
65
  LAYOUT OVERFLOW PREVENTION \u2014 CRITICAL:
47
- - Max 2 columns side by side \u2014 each with w-1/2. NEVER use 3+ columns.
66
+ - Max ${cfg.maxColumns} column${cfg.maxColumns === 1 ? "" : "s"} side by side${cfg.maxColumns === 2 ? " \u2014 each with w-1/2" : ""}. NEVER use ${cfg.maxColumns + 1}+ columns.
48
67
  - Decorative sidebars: max w-16 (4rem). NEVER use w-[2.5in] or wider sidebars \u2014 they steal too much space.
49
68
  - Stats/metric grids: max 3 items per row (grid-cols-3). Use gap-4 or gap-6.
50
69
  - Tables: max 4 columns, use text-xs or text-sm for cell text, px-3 py-2 cell padding.
51
70
  - Images: always w-full or max-w-[50%] \u2014 never fixed pixel widths.
52
- - Text: never use text-6xl or larger except for cover page title. Body text: text-sm or text-base.
71
+ - Text: never use text-6xl or larger except for cover page title. Body text: ${cfg.bodyText}.
53
72
  - NEVER use absolute positioning that could overflow \u2014 prefer flex/grid layouts.
54
73
  - Decorative shapes with absolute positioning MUST stay fully inside the page. Use overflow-hidden on parent AND keep coordinates positive (no negative right/left values).
55
74
  - Large decorative text (text-[200px], text-[10rem] etc.) MUST have opacity-5 or lower AND overflow-hidden on its container. These giant texts frequently overflow \u2014 be extra careful.
56
- - NEVER place elements beyond the right edge \u2014 all content and decorations must fit within 8.5in width.
75
+ - NEVER place elements beyond the right edge \u2014 all content and decorations must fit within ${isWeb ? "1280px" : "8.5in"} width.
57
76
 
58
77
  DESIGN \u2014 ADAPT to the document type. Read the prompt carefully and match the visual style:
59
78
 
@@ -125,7 +144,7 @@ TAILWIND v3 NOTES:
125
144
  - Borders: border + border-gray-200 for visible borders
126
145
 
127
146
  EXAMPLE \u2014 Cover page (simple, no wide sidebars):
128
- <section class="w-[8.5in] h-[11in] relative overflow-hidden flex flex-col bg-white">
147
+ <section class="${cfg.container} relative overflow-hidden flex flex-col bg-white">
129
148
  <div class="absolute left-0 top-0 w-2 h-full bg-primary"></div>
130
149
  <div class="flex-1 overflow-hidden flex flex-col justify-center px-[1in]">
131
150
  <div class="text-sm font-normal text-primary mb-4">Marzo 2026 \xB7 Versi\xF3n 1.0</div>
@@ -136,9 +155,9 @@ EXAMPLE \u2014 Cover page (simple, no wide sidebars):
136
155
  </section>
137
156
 
138
157
  EXAMPLE \u2014 Marketing/brochure page (bold, visual):
139
- <section class="w-[8.5in] h-[11in] relative overflow-hidden flex flex-col bg-primary">
158
+ <section class="${cfg.container} relative overflow-hidden flex flex-col bg-primary">
140
159
  <div class="flex flex-1 overflow-hidden">
141
- <div class="w-1/2 flex flex-col justify-center px-[0.75in]">
160
+ <div class="${isWeb ? "flex-1" : "w-1/2"} flex flex-col justify-center px-[0.75in]">
142
161
  <span class="text-sm font-normal text-on-primary opacity-70 uppercase tracking-widest mb-3">Soluci\xF3n Premium</span>
143
162
  <h2 class="text-4xl font-bold text-on-primary leading-tight mb-6">Transforma tu negocio digital</h2>
144
163
  <p class="text-base font-normal text-on-primary opacity-80 mb-8">Herramientas inteligentes que simplifican la gesti\xF3n de tus activos digitales.</p>
@@ -147,14 +166,14 @@ EXAMPLE \u2014 Marketing/brochure page (bold, visual):
147
166
  <div><div class="text-3xl font-bold text-accent">2.4K</div><div class="text-xs text-on-primary opacity-70">Empresas</div></div>
148
167
  </div>
149
168
  </div>
150
- <div class="w-1/2 relative">
169
+ <div class="${isWeb ? "flex-1" : "w-1/2"} relative">
151
170
  <img data-image-query="modern office team collaboration technology" alt="Team working" class="absolute inset-0 w-full h-full object-cover" />
152
171
  </div>
153
172
  </div>
154
173
  </section>
155
174
 
156
175
  EXAMPLE \u2014 Catalog/product grid page:
157
- <section class="w-[8.5in] h-[11in] relative overflow-hidden flex flex-col bg-surface">
176
+ <section class="${cfg.container} relative overflow-hidden flex flex-col bg-surface">
158
177
  <div class="shrink-0 h-1 bg-primary w-full"></div>
159
178
  <div class="flex-1 overflow-hidden px-[0.75in] py-[0.5in]">
160
179
  <div class="flex justify-between items-baseline mb-6">
@@ -180,7 +199,7 @@ EXAMPLE \u2014 Catalog/product grid page:
180
199
  </section>
181
200
 
182
201
  EXAMPLE \u2014 Content page with table + progress bars:
183
- <section class="w-[8.5in] h-[11in] relative overflow-hidden flex flex-col bg-white">
202
+ <section class="${cfg.container} relative overflow-hidden flex flex-col bg-white">
184
203
  <div class="shrink-0 h-1.5 bg-primary w-full"></div>
185
204
  <div class="flex-1 overflow-hidden px-[0.75in] py-[0.5in]">
186
205
  <h2 class="text-2xl font-bold text-gray-900 mb-1">M\xE9tricas de Rendimiento</h2>
@@ -190,7 +209,7 @@ EXAMPLE \u2014 Content page with table + progress bars:
190
209
  <tbody>
191
210
  <tr class="bg-surface-alt"><td class="px-4 py-3 text-gray-900">Ingresos</td><td class="px-4 py-3 text-gray-900">$1.2M</td><td class="px-4 py-3 text-gray-900">$1.5M</td></tr>
192
211
  <tr><td class="px-4 py-3 text-gray-900">Clientes nuevos</td><td class="px-4 py-3 text-gray-900">340</td><td class="px-4 py-3 text-gray-900">300</td></tr>
193
- <tr class="bg-surface-alt"><td class="px-4 py-3 text-gray-900">Retenci\xF3n</td><td class="px-4 py-3 text-gray-900">92%</td><td class="px-4 py-3 text-gray-900">90%</td></tr>
212
+ <tr class="bg-surface-alt"><td class="px-4 py-3 text-gray-900">Retenci\xF3n</td><td class="px-4 py-3 text-gray-900">92%</td><td class="px-4 py-3 text-gray-900">${"90%"}</td></tr>
194
213
  </tbody>
195
214
  </table>
196
215
  <h3 class="text-lg font-bold text-gray-900 mb-4">Progreso por \xC1rea</h3>
@@ -201,15 +220,22 @@ EXAMPLE \u2014 Content page with table + progress bars:
201
220
  </div>
202
221
  </div>
203
222
  </section>`;
204
- var DOCUMENT_PROMPT_SUFFIX = `
223
+ }
224
+ var DOCUMENT_SYSTEM_PROMPT = getDocumentSystemPrompt("letter");
225
+ function getDocumentPromptSuffix(format = "letter") {
226
+ const cfg = PAGE_FORMAT_CONFIG[format];
227
+ const isWeb = format === "web";
228
+ return `
205
229
 
206
230
  OUTPUT FORMAT: NDJSON \u2014 one JSON object per line, NO wrapper array, NO markdown fences.
207
- Each line: {"label": "Page Title", "html": "<section class='w-[8.5in] h-[11in] relative overflow-hidden flex flex-col'>...</section>"}
231
+ Each line: {"label": "Page Title", "html": "<section class='${cfg.container} relative overflow-hidden flex flex-col'>...</section>"}
208
232
 
209
233
  Generate 3-8 pages depending on content length. First page = cover/title page.
210
- Each page must fit within letter size (8.5" \xD7 11"). Be conservative with spacing.
234
+ ${isWeb ? "Each section should have comfortable spacing for web reading." : 'Each page must fit within letter size (8.5" \xD7 11"). Be conservative with spacing.'}
211
235
  Make each page visually distinct \u2014 different layouts, different accent placements.
212
236
  IMPORTANT: Adapt your design style to match the type of document \u2014 not everything is a report. Brochures should feel bold and visual, catalogs should showcase products, invitations should feel elegant, etc.`;
237
+ }
238
+ var DOCUMENT_PROMPT_SUFFIX = getDocumentPromptSuffix("letter");
213
239
  async function generateDocument(options) {
214
240
  const {
215
241
  prompt,
@@ -325,6 +351,7 @@ async function generateDocumentParallel(options) {
325
351
  persistImage,
326
352
  pageCount,
327
353
  skipCover,
354
+ pageFormat = "letter",
328
355
  onOutline,
329
356
  onPageChunk,
330
357
  onPageComplete,
@@ -426,12 +453,12 @@ Small logo header: <img src="${logoUrl}" alt="Logo" class="h-8 object-contain" /
426
453
  ${directionInstruction}
427
454
 
428
455
  OUTPUT: A single JSON object on ONE line, no markdown fences:
429
- {"label": "${page.label}", "html": "<section class='w-[8.5in] h-[11in] relative overflow-hidden flex flex-col'>...</section>"}`
456
+ {"label": "${page.label}", "html": "<section class='${PAGE_FORMAT_CONFIG[pageFormat].container} relative overflow-hidden flex flex-col'>...</section>"}`
430
457
  });
431
458
  try {
432
459
  const result = streamText({
433
460
  model: pageModel,
434
- system: DOCUMENT_SYSTEM_PROMPT + currentDateLine(),
461
+ system: getDocumentSystemPrompt(pageFormat || "letter") + currentDateLine(),
435
462
  messages: [{ role: "user", content: userContent }]
436
463
  });
437
464
  let buffer = "";
@@ -521,9 +548,12 @@ OUTPUT: A single JSON object on ONE line, no markdown fences:
521
548
  }
522
549
 
523
550
  export {
551
+ PAGE_FORMAT_CONFIG,
552
+ getDocumentSystemPrompt,
524
553
  DOCUMENT_SYSTEM_PROMPT,
554
+ getDocumentPromptSuffix,
525
555
  DOCUMENT_PROMPT_SUFFIX,
526
556
  generateDocument,
527
557
  generateDocumentParallel
528
558
  };
529
- //# sourceMappingURL=chunk-6LK7JW6Q.js.map
559
+ //# sourceMappingURL=chunk-X5MEN76P.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/generateDocument.ts"],"sourcesContent":["import { generateObject, streamText } from \"ai\";\nimport { z } from \"zod\";\nimport { nanoid } from \"nanoid\";\nimport {\n streamGenerate,\n dataUrlToImagePart,\n resolveModel,\n currentDateLine,\n extractJsonObjects,\n addLoadingPlaceholders,\n addSvgLoadingPlaceholders,\n enrichSectionImages,\n enrichSectionSvgCharts,\n enrichSectionIconSlots,\n} from \"./streamCore\";\nimport { sanitizeSemanticColors } from \"./sanitizeColors\";\nimport type { Section3 } from \"./types\";\nimport type { DesignDirection } from \"./directions\";\n\nexport type PageFormat = \"letter\" | \"web\";\n\nexport const PAGE_FORMAT_CONFIG = {\n letter: {\n container: \"w-[8.5in] h-[11in]\",\n bodyText: \"text-sm or text-base (10-11px)\",\n maxColumns: 2,\n heightMode: \"fixed at 11in\",\n description: 'letter-sized (8.5\" × 11\") document pages',\n },\n web: {\n container: \"w-[1280px] min-h-[800px]\",\n bodyText: \"text-base or text-lg (16-18px)\",\n maxColumns: 1,\n heightMode: \"flexible, no max height\",\n description: \"web-optimized document sections\",\n },\n} as const;\n\nexport function getDocumentSystemPrompt(format: PageFormat = \"letter\"): string {\n const cfg = PAGE_FORMAT_CONFIG[format];\n const isWeb = format === \"web\";\n\n return `You are a professional document designer who creates stunning ${cfg.description} using HTML + Tailwind CSS.\n\nRULES:\n- Each page is a <section> element${isWeb ? \" optimized for web viewing\" : \" sized for letter paper\"}\n- Page structure: <section class=\"${cfg.container} relative overflow-hidden flex flex-col\">\n- ${isWeb ? \"Each section has flexible height — content determines the height. Use min-h-[800px] but allow natural growth.\" : \"The section is EXACTLY 11in tall — content MUST fit, never exceed. Use flex flex-col so children can use flex-1.\"}\n- The section itself has NO padding — backgrounds, gradients, and decorative elements go edge-to-edge\n- Use slot layout: shrink-0 for header/footer bands, flex-1 overflow-hidden for main content area\n- For text content, use an inner wrapper: <div class=\"flex-1 overflow-hidden px-[0.75in] py-[0.5in]\">...content...</div>\n- Footer elements (page numbers, decorative bars, contact info) MUST be direct children of <section> with shrink-0 and w-full — NEVER inside the padded content wrapper. This ensures footer backgrounds extend edge-to-edge\n- Cover pages and decorative sections can use full-bleed backgrounds (bg-primary, gradients, images that fill the entire page)\n- Content MUST NOT overflow page boundaries — be conservative with spacing\n- Use Tailwind CDN classes ONLY (no custom CSS, no @apply, no @import)\n- NO JavaScript, only HTML+Tailwind\n- All text content in Spanish unless the prompt specifies otherwise\n- Use real content from the source material, not Lorem ipsum\n- NOT responsive — fixed ${isWeb ? \"width\" : \"letter size\"}, no breakpoints needed\n- Sections can have ANY background — full-bleed color, gradients, or white. Not limited to white paper.\n\nSTRICT PROHIBITIONS:\n1. **NO EMOJI** — Never use emoji characters (🚀❌✅📊 etc.). Instead use inline SVG icons or colored divs. For bullet decorators use small colored circles (<span class=\"w-2 h-2 rounded-full bg-primary inline-block\"></span>) or simple SVG.\n2. **NO Chart.js / NO JavaScript** — Never reference Chart.js, canvas, or any JS library. For data visualization use pure CSS: progress bars (div with percentage width + bg-primary), horizontal bars, styled tables with colored cells. Never use <canvas> or <script>.\n3. **NO buttons or CTAs** — This is a ${isWeb ? \"document\" : \"print document\"}, not a ${isWeb ? \"landing page\" : \"web page\"}. No \"Contactar\", \"Ver más\", \"Comprar\" buttons. Use text with contact info instead.\n4. **CONTRAST IS MANDATORY** — Dark/colored backgrounds (bg-primary, bg-primary-dark, bg-secondary, dark gradients) MUST use text-white or text-on-primary. Light backgrounds (white, bg-surface, bg-surface-alt) MUST use text-gray-900 or text-on-surface. NEVER use dark text on dark backgrounds or light text on light backgrounds.\n5. **Max 2 font weights per page** — Pick 2 (e.g. font-semibold + font-normal, or font-bold + font-light). Don't mix 4-5 weights.\n6. **Generous whitespace** — Don't fill every centimeter. Leave breathing room. Use py-8, py-12, gap-6, gap-8 liberally. Less content per page = more professional.\n\nLAYOUT OVERFLOW PREVENTION — CRITICAL:\n- Max ${cfg.maxColumns} column${cfg.maxColumns === 1 ? \"\" : \"s\"} side by side${cfg.maxColumns === 2 ? \" — each with w-1/2\" : \"\"}. NEVER use ${cfg.maxColumns + 1}+ columns.\n- Decorative sidebars: max w-16 (4rem). NEVER use w-[2.5in] or wider sidebars — they steal too much space.\n- Stats/metric grids: max 3 items per row (grid-cols-3). Use gap-4 or gap-6.\n- Tables: max 4 columns, use text-xs or text-sm for cell text, px-3 py-2 cell padding.\n- Images: always w-full or max-w-[50%] — never fixed pixel widths.\n- Text: never use text-6xl or larger except for cover page title. Body text: ${cfg.bodyText}.\n- NEVER use absolute positioning that could overflow — prefer flex/grid layouts.\n- Decorative shapes with absolute positioning MUST stay fully inside the page. Use overflow-hidden on parent AND keep coordinates positive (no negative right/left values).\n- Large decorative text (text-[200px], text-[10rem] etc.) MUST have opacity-5 or lower AND overflow-hidden on its container. These giant texts frequently overflow — be extra careful.\n- NEVER place elements beyond the right edge — all content and decorations must fit within ${isWeb ? \"1280px\" : \"8.5in\"} width.\n\nDESIGN — ADAPT to the document type. Read the prompt carefully and match the visual style:\n\nGENERAL PRINCIPLES (apply to ALL documents):\n- First page is ALWAYS a stunning cover/title page with impactful design\n- Typography: strong hierarchy with just 2 weights, clear headings vs body\n- Each page visually distinct — different layouts, accent placements\n- Use the full page creatively — backgrounds, sidebars, geometric shapes\n- Professional and polished, never generic or template-looking\n- Icons: use simple inline SVG (12-20px) for visual accents. Keep SVGs minimal (single path, no complex illustrations)\n\nADAPT YOUR STYLE to what the user is creating:\n- Reports/Data: structured grids, tables with alternating rows (bg-surface-alt), progress bars, stat cards, clean data hierarchy\n- Brochures/Marketing: bold hero images, large headlines, feature grids, testimonial-style quotes, visual storytelling\n- Catalogs/Products: product cards with images, specs grids, price highlights, category headers with full-bleed color\n- Invitations/Events: centered dramatic typography, decorative borders, elegant spacing, date/location prominently styled\n- Proposals/Pitches: problem→solution flow, metric highlights, team/about sections, pricing tables\n- CVs/Resumes: clean sidebar layouts, skill bars, timeline for experience, contact info header\n- Creative/General: mix techniques — bento grids, full-bleed images, overlapping elements, bold color blocking\n\nVISUAL TECHNIQUES available to you:\n- Full-bleed colored pages (bg-primary, gradients)\n- Geometric accent shapes (CSS divs with clip-path or rotation)\n- Asymmetric layouts (grid with unequal columns)\n- Large stat numbers as visual anchors (text-5xl font-black)\n- Header/footer bands with contrasting color\n- Sidebar accents (thin, max w-16)\n- Image + text compositions\n- Bento-grid mixing content blocks of different sizes\n- Tables: alternating row colors, clean borders, generous cell padding (px-4 py-3)\n- For numerical data: CSS progress bars, styled tables with colored cells, large stat numbers — NEVER canvas/charts\n\nCSS PROGRESS BARS — use this pattern for data visualization:\n<div class=\"w-full bg-gray-200 rounded-full h-3\"><div class=\"bg-primary h-3 rounded-full\" style=\"width: 75%\"></div></div>\n\nCOLOR SYSTEM — use semantic classes:\n- bg-primary, text-primary, bg-primary-light, bg-primary-dark, text-on-primary\n- bg-surface, bg-surface-alt, text-on-surface, text-on-surface-muted\n- bg-secondary, text-secondary, bg-accent, text-accent\n- Cover pages should use bold full-bleed backgrounds (bg-primary, gradients from-primary to-primary-dark)\n- CONTRAST: bg-primary/bg-primary-dark/bg-secondary → text-white or text-on-primary. White/bg-surface → text-gray-900 or text-on-surface\n\nIMAGES — USE GENEROUSLY:\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 include a src attribute — the system auto-replaces data-image-query with a real image\n- For avatar-like elements, use colored divs with initials instead of img tags\n- Include at LEAST 3-5 images across the document — hero images, section illustrations, backgrounds, product photos\n- Each data-image-query should be a UNIQUE, specific search query in English (e.g. \"modern office workspace aerial view\", \"team brainstorming whiteboard\", \"abstract blue technology network\")\n- Use images to break up text-heavy pages and add visual interest\n\nICONS — use data-icon-query for professional icons:\n- <span data-icon-query=\"icon-name\" class=\"inline-block w-5 h-5 text-primary\"></span>\n- Use common Lucide icon names in English: star, check, arrow-right, heart, zap, shield, users, mail, phone, calendar, clock, map-pin, briefcase, trending-up, award, target, layers, globe, etc.\n- Use in: feature lists, stat cards, CTAs, list items, contact info, section headers\n- Sizes: w-4 h-4 (small), w-5 h-5 (default), w-8 h-8 (large). Color inherits from text-* class.\n- NEVER draw SVG paths manually — ALWAYS use data-icon-query instead\n- The system auto-replaces data-icon-query with real SVG icons from Iconify\n\nCHARTS & DATA VISUALIZATION (SVG):\n- For charts, diagrams, and decorative data graphics, use:\n <div data-svg-chart=\"bar chart showing Q1 revenue: Jan $45K, Feb $52K, Mar $61K\" class=\"w-full\"></div>\n- The system generates professional SVG charts with a specialized tool — NEVER draw SVGs yourself\n- Use descriptive prompts with data points: type of chart + what it shows + actual values\n- Examples: \"donut chart: 40% Marketing, 30% Sales, 20% R&D, 10% Admin\", \"line chart showing growth: Q1 $100K, Q2 $150K, Q3 $220K, Q4 $310K\"\n- For simple metrics, still prefer CSS progress bars (they render faster)\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\nEXAMPLE — Cover page (simple, no wide sidebars):\n<section class=\"${cfg.container} relative overflow-hidden flex flex-col bg-white\">\n <div class=\"absolute left-0 top-0 w-2 h-full bg-primary\"></div>\n <div class=\"flex-1 overflow-hidden flex flex-col justify-center px-[1in]\">\n <div class=\"text-sm font-normal text-primary mb-4\">Marzo 2026 · Versión 1.0</div>\n <h1 class=\"text-5xl font-bold text-gray-900 leading-tight\">Reporte<br/>Trimestral</h1>\n <div class=\"w-16 h-1 bg-primary mt-6 mb-4\"></div>\n <p class=\"text-lg font-normal text-gray-500\">Resultados y análisis del primer trimestre</p>\n </div>\n</section>\n\nEXAMPLE — Marketing/brochure page (bold, visual):\n<section class=\"${cfg.container} relative overflow-hidden flex flex-col bg-primary\">\n <div class=\"flex flex-1 overflow-hidden\">\n <div class=\"${isWeb ? \"flex-1\" : \"w-1/2\"} flex flex-col justify-center px-[0.75in]\">\n <span class=\"text-sm font-normal text-on-primary opacity-70 uppercase tracking-widest mb-3\">Solución Premium</span>\n <h2 class=\"text-4xl font-bold text-on-primary leading-tight mb-6\">Transforma tu negocio digital</h2>\n <p class=\"text-base font-normal text-on-primary opacity-80 mb-8\">Herramientas inteligentes que simplifican la gestión de tus activos digitales.</p>\n <div class=\"flex gap-6\">\n <div><div class=\"text-3xl font-bold text-accent\">98%</div><div class=\"text-xs text-on-primary opacity-70\">Satisfacción</div></div>\n <div><div class=\"text-3xl font-bold text-accent\">2.4K</div><div class=\"text-xs text-on-primary opacity-70\">Empresas</div></div>\n </div>\n </div>\n <div class=\"${isWeb ? \"flex-1\" : \"w-1/2\"} relative\">\n <img data-image-query=\"modern office team collaboration technology\" alt=\"Team working\" class=\"absolute inset-0 w-full h-full object-cover\" />\n </div>\n </div>\n</section>\n\nEXAMPLE — Catalog/product grid page:\n<section class=\"${cfg.container} relative overflow-hidden flex flex-col bg-surface\">\n <div class=\"shrink-0 h-1 bg-primary w-full\"></div>\n <div class=\"flex-1 overflow-hidden px-[0.75in] py-[0.5in]\">\n <div class=\"flex justify-between items-baseline mb-6\">\n <h2 class=\"text-2xl font-bold text-on-surface\">Colección Primavera</h2>\n <span class=\"text-xs font-normal text-on-surface-muted uppercase tracking-wider\">Página 3 de 8</span>\n </div>\n <div class=\"grid grid-cols-2 gap-6\">\n <div class=\"bg-surface-alt rounded-xl overflow-hidden\">\n <img data-image-query=\"minimalist product on white background\" alt=\"Product\" class=\"w-full h-48 object-cover\" />\n <div class=\"p-4\"><h3 class=\"font-bold text-on-surface text-sm\">Producto Alpha</h3><p class=\"text-xs text-on-surface-muted mt-1\">Diseño ergonómico premium</p><div class=\"text-lg font-bold text-primary mt-2\">$2,490</div></div>\n </div>\n <div class=\"bg-surface-alt rounded-xl overflow-hidden\">\n <img data-image-query=\"elegant product photography studio\" alt=\"Product\" class=\"w-full h-48 object-cover\" />\n <div class=\"p-4\"><h3 class=\"font-bold text-on-surface text-sm\">Producto Beta</h3><p class=\"text-xs text-on-surface-muted mt-1\">Tecnología de vanguardia</p><div class=\"text-lg font-bold text-primary mt-2\">$3,190</div></div>\n </div>\n </div>\n </div>\n <!-- Footer: direct child of section, shrink-0, full width -->\n <div class=\"shrink-0 w-full bg-surface-alt px-[0.75in] py-3 flex justify-between items-center\">\n <span class=\"text-xs text-on-surface-muted\">Colección Primavera 2026</span>\n <span class=\"text-xs text-on-surface-muted\">Página 3 de 8</span>\n </div>\n</section>\n\nEXAMPLE — Content page with table + progress bars:\n<section class=\"${cfg.container} relative overflow-hidden flex flex-col bg-white\">\n <div class=\"shrink-0 h-1.5 bg-primary w-full\"></div>\n <div class=\"flex-1 overflow-hidden px-[0.75in] py-[0.5in]\">\n <h2 class=\"text-2xl font-bold text-gray-900 mb-1\">Métricas de Rendimiento</h2>\n <p class=\"text-sm font-normal text-gray-500 mb-8\">Indicadores clave del periodo enero—marzo</p>\n <table class=\"w-full text-sm mb-10\">\n <thead><tr class=\"bg-primary text-white\"><th class=\"px-4 py-3 text-left font-semibold\">Indicador</th><th class=\"px-4 py-3 text-left font-semibold\">Valor</th><th class=\"px-4 py-3 text-left font-semibold\">Meta</th></tr></thead>\n <tbody>\n <tr class=\"bg-surface-alt\"><td class=\"px-4 py-3 text-gray-900\">Ingresos</td><td class=\"px-4 py-3 text-gray-900\">$1.2M</td><td class=\"px-4 py-3 text-gray-900\">$1.5M</td></tr>\n <tr><td class=\"px-4 py-3 text-gray-900\">Clientes nuevos</td><td class=\"px-4 py-3 text-gray-900\">340</td><td class=\"px-4 py-3 text-gray-900\">300</td></tr>\n <tr class=\"bg-surface-alt\"><td class=\"px-4 py-3 text-gray-900\">Retención</td><td class=\"px-4 py-3 text-gray-900\">92%</td><td class=\"px-4 py-3 text-gray-900\">${\"90%\"}</td></tr>\n </tbody>\n </table>\n <h3 class=\"text-lg font-bold text-gray-900 mb-4\">Progreso por Área</h3>\n <div class=\"space-y-4\">\n <div><div class=\"flex justify-between text-sm mb-1\"><span class=\"text-gray-900 font-semibold\">Ventas</span><span class=\"text-gray-500\">80%</span></div><div class=\"w-full bg-gray-200 rounded-full h-3\"><div class=\"bg-primary h-3 rounded-full\" style=\"width: 80%\"></div></div></div>\n <div><div class=\"flex justify-between text-sm mb-1\"><span class=\"text-gray-900 font-semibold\">Marketing</span><span class=\"text-gray-500\">65%</span></div><div class=\"w-full bg-gray-200 rounded-full h-3\"><div class=\"bg-secondary h-3 rounded-full\" style=\"width: 65%\"></div></div></div>\n <div><div class=\"flex justify-between text-sm mb-1\"><span class=\"text-gray-900 font-semibold\">Producto</span><span class=\"text-gray-500\">95%</span></div><div class=\"w-full bg-gray-200 rounded-full h-3\"><div class=\"bg-accent h-3 rounded-full\" style=\"width: 95%\"></div></div></div>\n </div>\n </div>\n</section>`;\n}\n\nexport const DOCUMENT_SYSTEM_PROMPT = getDocumentSystemPrompt(\"letter\");\n\nexport function getDocumentPromptSuffix(format: PageFormat = \"letter\"): string {\n const cfg = PAGE_FORMAT_CONFIG[format];\n const isWeb = format === \"web\";\n return `\n\nOUTPUT FORMAT: NDJSON — one JSON object per line, NO wrapper array, NO markdown fences.\nEach line: {\"label\": \"Page Title\", \"html\": \"<section class='${cfg.container} relative overflow-hidden flex flex-col'>...</section>\"}\n\nGenerate 3-8 pages depending on content length. First page = cover/title page.\n${isWeb ? \"Each section should have comfortable spacing for web reading.\" : \"Each page must fit within letter size (8.5\\\" × 11\\\"). Be conservative with spacing.\"}\nMake each page visually distinct — different layouts, different accent placements.\nIMPORTANT: Adapt your design style to match the type of document — not everything is a report. Brochures should feel bold and visual, catalogs should showcase products, invitations should feel elegant, etc.`;\n}\n\nexport const DOCUMENT_PROMPT_SUFFIX = getDocumentPromptSuffix(\"letter\");\n\nexport interface GenerateDocumentOptions {\n anthropicApiKey?: string;\n openaiApiKey?: string;\n prompt: string;\n logoUrl?: string;\n referenceImage?: string;\n extraInstructions?: string;\n model?: string | import(\"ai\").LanguageModel;\n pexelsApiKey?: string;\n /** Design direction — injects Google Fonts + hex colors into the prompt */\n direction?: DesignDirection;\n persistImage?: (tempUrl: string, query: string) => Promise<string>;\n onSection?: (section: Section3) => void;\n onImageUpdate?: (sectionId: string, html: string) => void;\n onRawChunk?: (buffer: string, completedCount: number) => void;\n onDone?: (sections: Section3[]) => void;\n onError?: (error: Error) => void;\n}\n\n/**\n * Generate a multi-page document with streaming AI + image enrichment.\n */\nexport async function generateDocument(options: GenerateDocumentOptions): Promise<Section3[]> {\n const {\n prompt,\n logoUrl,\n referenceImage,\n extraInstructions,\n direction,\n ...rest\n } = options;\n\n const extra = extraInstructions ? `\\nAdditional instructions: ${extraInstructions}` : \"\";\n\n // Build direction style instructions if provided\n let directionInstruction = \"\";\n if (direction) {\n const fontsUrl = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(direction.headingFont).replace(/%20/g, \"+\")}:wght@400;700;900&family=${encodeURIComponent(direction.bodyFont).replace(/%20/g, \"+\")}:wght@400;500;600&display=swap`;\n directionInstruction = `\nDESIGN DIRECTION: \"${direction.name}\" — ${direction.tagline}\nTYPOGRAPHY: Use these Google Fonts via <link href=\"${fontsUrl}\" rel=\"stylesheet\"> on the first page.\n- Headings: font-family: '${direction.headingFont}', sans-serif (via inline style)\n- Body: font-family: '${direction.bodyFont}', sans-serif (via inline style)\nCOLORS — use ONLY semantic Tailwind classes (the editor injects CSS variables that resolve these):\n- bg-primary, text-primary, bg-primary-light, bg-primary-dark, text-on-primary\n- bg-surface, bg-surface-alt, text-on-surface, text-on-surface-muted\n- bg-secondary, text-secondary, bg-accent, text-accent\n- NEVER use hardcoded hex colors like bg-[#xxx] or text-[#xxx] — always use semantic classes\n- The palette is: primary=${direction.colors.primary}, accent=${direction.colors.accent}, surface=${direction.colors.surface}\nMood: ${direction.mood}\nLayout approach: ${direction.layoutHint}\nIMPORTANT: Apply inline style=\"font-family: '${direction.headingFont}'\" on ALL heading elements and style=\"font-family: '${direction.bodyFont}'\" on ALL body text elements. Include the Google Fonts <link> tag inside the FIRST <section> only.`;\n }\n // Truncate prompt to prevent token overflow (max ~15K chars ≈ 5K tokens)\n const safePrompt = prompt.length > 15_000 ? prompt.substring(0, 15_000) + \"\\n[...content truncated...]\" : prompt;\n const logoInstruction = logoUrl\n ? `\\nLOGO: Include this logo on the cover page and as a small header on other pages:\\n<img src=\"${logoUrl}\" alt=\"Logo\" class=\"h-12 object-contain\" />\\nUse this exact <img> tag with this exact src URL — do NOT invent a different URL or modify it.`\n : \"\";\n\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: `Create a professional document inspired by this reference image for: ${safePrompt}${logoInstruction}${directionInstruction}${extra}${DOCUMENT_PROMPT_SUFFIX}`,\n });\n } else {\n content.push({\n type: \"text\",\n text: `Create a professional document for: ${safePrompt}${logoInstruction}${directionInstruction}${extra}${DOCUMENT_PROMPT_SUFFIX}`,\n });\n }\n\n return streamGenerate({\n ...rest,\n systemPrompt: DOCUMENT_SYSTEM_PROMPT,\n userContent: content,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Parallel Document Generation\n// ---------------------------------------------------------------------------\n\nconst DocumentOutlineSchema = z.object({\n pages: z.array(z.object({\n pageNumber: z.number(),\n label: z.string().describe(\"Page title for sidebar\"),\n type: z.enum([\"cover\", \"content\", \"data\", \"visual\", \"closing\"]),\n layoutHint: z.string().describe(\"Layout approach: split, full-bleed, grid, editorial, table-heavy, sidebar\"),\n contentBrief: z.string().describe(\"2-4 sentences describing exactly what goes on this page\"),\n keyElements: z.array(z.string()).describe(\"Specific elements: stats grid, table, hero image, timeline, etc.\"),\n backgroundStyle: z.enum([\"white\", \"primary\", \"gradient\", \"surface-alt\", \"image\"]),\n continuesFrom: z.string().optional().describe(\"How this page relates to the previous one\"),\n })),\n});\n\nexport type DocumentOutline = z.infer<typeof DocumentOutlineSchema>;\n\nexport interface GenerateDocumentParallelOptions {\n anthropicApiKey?: string;\n openaiApiKey?: string;\n prompt: string;\n logoUrl?: string;\n referenceImage?: string;\n /** Per-page reference images (e.g. rendered from PDF pages). Index matches page order. */\n referencePages?: string[];\n extraInstructions?: string;\n /** Model for page generation (quality model) */\n model?: string | import(\"ai\").LanguageModel;\n /** Model for outline generation (fast model) */\n outlineModel?: string | import(\"ai\").LanguageModel;\n pexelsApiKey?: string;\n direction?: DesignDirection;\n persistImage?: (tempUrl: string, query: string) => Promise<string>;\n pageCount?: number;\n skipCover?: boolean;\n pageFormat?: PageFormat;\n onOutline?: (outline: DocumentOutline) => void;\n onPageChunk?: (pageIndex: number, partialHtml: string) => void;\n onPageComplete?: (pageIndex: number, section: Section3) => void;\n onImageUpdate?: (sectionId: string, html: string) => void;\n onDone?: (sections: Section3[]) => void;\n onError?: (error: Error) => void;\n /** Called with accumulated token usage from outline + all pages */\n onUsage?: (usage: { inputTokens: number; outputTokens: number }) => void;\n}\n\nfunction buildDirectionInstruction(direction: DesignDirection): string {\n const fontsUrl = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(direction.headingFont).replace(/%20/g, \"+\")}:wght@400;700;900&family=${encodeURIComponent(direction.bodyFont).replace(/%20/g, \"+\")}:wght@400;500;600&display=swap`;\n return `\nDESIGN DIRECTION: \"${direction.name}\" — ${direction.tagline}\nTYPOGRAPHY: Use these Google Fonts via <link href=\"${fontsUrl}\" rel=\"stylesheet\"> on the first page.\n- Headings: font-family: '${direction.headingFont}', sans-serif (via inline style)\n- Body: font-family: '${direction.bodyFont}', sans-serif (via inline style)\nCOLORS — use ONLY semantic Tailwind classes (the editor injects CSS variables that resolve these):\n- bg-primary, text-primary, bg-primary-light, bg-primary-dark, text-on-primary\n- bg-surface, bg-surface-alt, text-on-surface, text-on-surface-muted\n- bg-secondary, text-secondary, bg-accent, text-accent\n- NEVER use hardcoded hex colors like bg-[#xxx] or text-[#xxx] — always use semantic classes\n- The palette is: primary=${direction.colors.primary}, accent=${direction.colors.accent}, surface=${direction.colors.surface}\nMood: ${direction.mood}\nLayout approach: ${direction.layoutHint}\nIMPORTANT: Apply inline style=\"font-family: '${direction.headingFont}'\" on ALL heading elements and style=\"font-family: '${direction.bodyFont}'\" on ALL body text elements. Include the Google Fonts <link> tag inside the FIRST <section> only.`;\n}\n\n/** Extract partial HTML from a raw JSON buffer (same pattern as onRawChunk) */\nfunction extractPartialHtml(buffer: string): string | null {\n const htmlMatch = buffer.match(/\"html\"\\s*:\\s*\"([\\s\\S]*)/);\n if (!htmlMatch) return null;\n let partial = htmlMatch[1]\n .replace(/\\\\n/g, '\\n').replace(/\\\\\"/g, '\"').replace(/\\\\\\\\/g, '\\\\');\n if (partial.endsWith('\\\\')) partial = partial.slice(0, -1);\n const lastQuote = partial.lastIndexOf('\"');\n if (lastQuote > 0) partial = partial.slice(0, lastQuote);\n if (/<section/i.test(partial) && !/<\\/section>/i.test(partial)) {\n partial += '</section>';\n }\n return partial.length > 20 ? partial : null;\n}\n\nexport async function generateDocumentParallel(options: GenerateDocumentParallelOptions): Promise<Section3[]> {\n const {\n anthropicApiKey,\n openaiApiKey: _openaiApiKey,\n prompt,\n logoUrl,\n referenceImage,\n referencePages,\n extraInstructions,\n model: pageModelId,\n outlineModel: outlineModelId,\n pexelsApiKey,\n direction,\n persistImage,\n pageCount,\n skipCover,\n pageFormat = \"letter\",\n onOutline,\n onPageChunk,\n onPageComplete,\n onImageUpdate,\n onDone,\n onError,\n onUsage,\n } = options;\n\n const openaiApiKey = _openaiApiKey || process.env.OPENAI_API_KEY;\n\n try {\n // --- Phase 1: Generate outline ---\n const outlineModel = await resolveModel({\n openaiApiKey,\n anthropicApiKey,\n modelId: outlineModelId,\n defaultOpenai: \"gpt-4.1-mini\",\n defaultAnthropic: \"claude-haiku-4-5-20251001\",\n });\n\n const safePrompt = prompt.length > 15_000 ? prompt.substring(0, 15_000) + \"\\n[...content truncated...]\" : prompt;\n const extra = extraInstructions ? `\\nAdditional instructions: ${extraInstructions}` : \"\";\n const pageCountHint = skipCover\n ? `Generate exactly ${Math.max(1, (pageCount || 5) - 1)} content pages (NO cover — it already exists).`\n : pageCount\n ? `Generate exactly ${pageCount} pages including a cover page.`\n : \"Generate 3-8 pages including a cover page.\";\n\n let totalInputTokens = 0;\n let totalOutputTokens = 0;\n\n const { object: rawOutline, usage: outlineUsage } = await generateObject({\n model: outlineModel,\n schema: DocumentOutlineSchema,\n prompt: `You are planning a professional document. Create a detailed page-by-page outline.\n\nDOCUMENT BRIEF: ${safePrompt}${extra}\n\nRULES:\n- ${pageCountHint}\n${skipCover ? \"- CRITICAL: Do NOT include a cover/title page. The cover already exists. Start with page type 'content', 'data', or 'visual'. NEVER use type 'cover'.\" : \"- First page is ALWAYS a stunning cover/title page.\"}\n- Distribute content EVENLY — no page should be overloaded\n- Each page must have a DISTINCT layout (mix split, full-bleed, grid, editorial, sidebar, table-heavy)\n- Narrative flows naturally: ${skipCover ? \"introduction → detail → data → closing\" : \"cover → introduction → detail → data → closing\"}\n- contentBrief must be detailed enough that a separate AI can generate the page independently\n- keyElements must list specific visual elements (not vague descriptions)\n- Vary backgroundStyle across pages — not all white\n- If source content is provided, assign specific portions to each page in the contentBrief\n${direction ? `- Design mood: ${direction.mood}, layout approach: ${direction.layoutHint}` : \"\"}`,\n });\n\n totalInputTokens += outlineUsage?.inputTokens || 0;\n totalOutputTokens += outlineUsage?.outputTokens || 0;\n\n // Filter out any cover pages if skipCover (AI sometimes ignores instructions)\n const outline: DocumentOutline = skipCover\n ? { pages: rawOutline.pages.filter(p => p.type !== \"cover\").map((p, i) => ({ ...p, pageNumber: i + 1 })) }\n : rawOutline;\n\n onOutline?.(outline);\n\n // --- Phase 2: Generate pages in parallel ---\n const directionInstruction = direction ? buildDirectionInstruction(direction) : \"\";\n const logoInstruction = logoUrl\n ? `\\nLOGO: Include this logo on the cover page and as a small header on other pages:\\n<img src=\"${logoUrl}\" alt=\"Logo\" class=\"h-12 object-contain\" />\\nUse this exact <img> tag with this exact src URL.`\n : \"\";\n\n const outlineJson = JSON.stringify(outline.pages, null, 2);\n\n const pageModel = await resolveModel({\n openaiApiKey,\n anthropicApiKey,\n modelId: pageModelId,\n defaultOpenai: \"gpt-4o\",\n defaultAnthropic: \"claude-sonnet-4-6\",\n });\n\n async function generateSinglePage(\n page: DocumentOutline[\"pages\"][number],\n retryCount = 0\n ): Promise<Section3> {\n const pageIdx = page.pageNumber - 1;\n const isCover = page.type === \"cover\";\n\n const userContent: any[] = [];\n\n // Per-page reference image from PDF (takes priority)\n const pageRef = referencePages?.[pageIdx];\n if (pageRef) {\n const converted = dataUrlToImagePart(pageRef);\n if (converted) {\n userContent.push({ type: \"image\", ...converted });\n } else {\n userContent.push({ type: \"image\", image: pageRef });\n }\n } else if (referenceImage && (isCover || page.type === \"visual\")) {\n // Fallback: single reference image for cover/visual pages\n const converted = dataUrlToImagePart(referenceImage);\n if (converted) {\n userContent.push({ type: \"image\", ...converted });\n } else {\n userContent.push({ type: \"image\", image: referenceImage });\n }\n }\n\n const hasRefImage = !!pageRef || !!(referenceImage && (isCover || page.type === \"visual\"));\n userContent.push({\n type: \"text\",\n text: `You are generating PAGE ${page.pageNumber} of ${outline.pages.length} for a professional document.\n${hasRefImage ? \"\\nREFERENCE IMAGE: The attached image shows the design to replicate. Match its layout, typography style, and visual structure as closely as possible while using the semantic color system and content from the brief.\" : \"\"}\n\nFULL DOCUMENT OUTLINE (for context — you are generating ONLY page ${page.pageNumber}):\n${outlineJson}\n\nYOUR PAGE ASSIGNMENT:\n- Label: ${page.label}\n- Type: ${page.type}\n- Layout: ${page.layoutHint}\n- Background: ${page.backgroundStyle}\n- Content: ${page.contentBrief}\n- Key elements: ${page.keyElements.join(\", \")}\n${page.continuesFrom ? `- Continues from: ${page.continuesFrom}` : \"\"}\n${isCover ? logoInstruction : logoUrl ? `\\nSmall logo header: <img src=\"${logoUrl}\" alt=\"Logo\" class=\"h-8 object-contain\" />` : \"\"}\n${directionInstruction}\n\nOUTPUT: A single JSON object on ONE line, no markdown fences:\n{\"label\": \"${page.label}\", \"html\": \"<section class='${PAGE_FORMAT_CONFIG[pageFormat].container} relative overflow-hidden flex flex-col'>...</section>\"}`,\n });\n\n try {\n const result = streamText({\n model: pageModel,\n system: getDocumentSystemPrompt(pageFormat || \"letter\") + currentDateLine(),\n messages: [{ role: \"user\", content: userContent }],\n });\n\n let buffer = \"\";\n let chunkCount = 0;\n for await (const chunk of result.textStream) {\n buffer += chunk;\n chunkCount++;\n if (chunkCount % 5 === 0) {\n const partial = extractPartialHtml(buffer);\n if (partial) onPageChunk?.(pageIdx, partial);\n }\n }\n\n // Accumulate token usage\n const pageUsage = await result.usage;\n totalInputTokens += pageUsage?.inputTokens || 0;\n totalOutputTokens += pageUsage?.outputTokens || 0;\n\n // Final partial before parse\n const finalPartial = extractPartialHtml(buffer);\n if (finalPartial) onPageChunk?.(pageIdx, finalPartial);\n\n // Parse the JSON object\n let cleaned = buffer.trim();\n if (cleaned.startsWith(\"```\")) {\n cleaned = cleaned.replace(/^```(?:json)?\\s*/, \"\").replace(/\\s*```$/, \"\");\n }\n const [objects] = extractJsonObjects(cleaned);\n const obj = objects[0];\n if (!obj?.html) throw new Error(`No valid HTML output for page ${page.pageNumber}`);\n\n const section: Section3 = {\n id: nanoid(8),\n order: pageIdx,\n html: sanitizeSemanticColors(addSvgLoadingPlaceholders(addLoadingPlaceholders(obj.html))),\n label: obj.label || page.label,\n };\n\n onPageComplete?.(pageIdx, section);\n return section;\n } catch (err) {\n if (retryCount < 1) {\n console.warn(`Page ${page.pageNumber} failed, retrying:`, (err as Error).message);\n return generateSinglePage(page, retryCount + 1);\n }\n // Return error placeholder\n const section: Section3 = {\n id: nanoid(8),\n order: pageIdx,\n html: `<section class=\"w-[8.5in] h-[11in] relative overflow-hidden flex flex-col bg-gray-50 items-center justify-center\"><div class=\"text-center text-gray-400\"><p class=\"text-lg font-semibold\">Error generando página</p><p class=\"text-sm mt-2\">${(err as Error).message?.slice(0, 100) || \"Error desconocido\"}</p></div></section>`,\n label: page.label,\n };\n onPageComplete?.(pageIdx, section);\n return section;\n }\n }\n\n const results = await Promise.allSettled(\n outline.pages.map((page) => generateSinglePage(page))\n );\n\n const sections: Section3[] = results\n .map((r) => r.status === \"fulfilled\" ? r.value : null)\n .filter((s): s is Section3 => s !== null)\n .sort((a, b) => a.order - b.order);\n\n // --- Phase 3: Image enrichment (sequential to respect Pexels rate limits) ---\n for (const section of sections) {\n await enrichSectionImages(section, {\n pexelsApiKey,\n openaiApiKey,\n persistImage,\n onImageUpdate,\n });\n await enrichSectionSvgCharts(section, {\n anthropicApiKey,\n onImageUpdate,\n });\n await enrichSectionIconSlots(section, { onImageUpdate });\n }\n\n // Final fallback for images without src\n for (const section of sections) {\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 if (section.html !== before) {\n onImageUpdate?.(section.id, section.html);\n }\n }\n\n onUsage?.({ inputTokens: totalInputTokens, outputTokens: totalOutputTokens });\n onDone?.(sections);\n return sections;\n } catch (err: any) {\n const error = err instanceof Error ? err : new Error(err?.message || \"Parallel generation failed\");\n onError?.(error);\n throw error;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB,kBAAkB;AAC3C,SAAS,SAAS;AAClB,SAAS,c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, {
16
- primary: string;
17
- accent: string;
18
- surface: string;
19
- text: string;
20
- surfaceAlt: string;
21
- }, {
22
- primary: string;
23
- accent: string;
24
- surface: string;
25
- text: string;
26
- surfaceAlt: string;
15
+ }, z.core.$strip>;
16
+ mood: z.ZodEnum<{
17
+ dark: "dark";
18
+ light: "light";
19
+ warm: "warm";
20
+ cool: "cool";
21
+ vibrant: "vibrant";
27
22
  }>;
28
- mood: z.ZodEnum<["dark", "light", "warm", "cool", "vibrant"]>;
29
23
  layoutHint: z.ZodString;
30
- }, "strip", z.ZodTypeAny, {
31
- colors: {
32
- primary: string;
33
- accent: string;
34
- surface: string;
35
- text: string;
36
- surfaceAlt: string;
37
- };
38
- mood: "dark" | "light" | "warm" | "cool" | "vibrant";
39
- name: string;
40
- tagline: string;
41
- headingFont: string;
42
- bodyFont: string;
43
- layoutHint: string;
44
- }, {
45
- colors: {
46
- primary: string;
47
- accent: string;
48
- surface: string;
49
- text: string;
50
- surfaceAlt: string;
51
- };
52
- mood: "dark" | "light" | "warm" | "cool" | "vibrant";
53
- name: string;
54
- tagline: string;
55
- headingFont: string;
56
- bodyFont: string;
57
- layoutHint: string;
58
- }>;
24
+ }, z.core.$strip>;
59
25
  type DesignDirection = z.infer<typeof DesignDirectionSchema>;
60
26
  interface DirectionsOptions {
61
27
  anthropicApiKey?: string;
@@ -3,8 +3,27 @@ import { z } from 'zod';
3
3
  import { S as Section3 } from './types-BIpbpCJr.js';
4
4
  import { DesignDirection } from './directions.js';
5
5
 
6
- declare const DOCUMENT_SYSTEM_PROMPT = "You are a professional document designer who creates stunning letter-sized (8.5\" \u00D7 11\") document pages using HTML + Tailwind CSS.\n\nRULES:\n- Each page is a <section> element sized for letter paper\n- Page structure: <section class=\"w-[8.5in] h-[11in] relative overflow-hidden flex flex-col\">\n- The section is EXACTLY 11in tall \u2014 content MUST fit, never exceed. Use flex flex-col so children can use flex-1.\n- The section itself has NO padding \u2014 backgrounds, gradients, and decorative elements go edge-to-edge\n- Use slot layout: shrink-0 for header/footer bands, flex-1 overflow-hidden for main content area\n- For text content, use an inner wrapper: <div class=\"flex-1 overflow-hidden px-[0.75in] py-[0.5in]\">...content...</div>\n- Footer elements (page numbers, decorative bars, contact info) MUST be direct children of <section> with shrink-0 and w-full \u2014 NEVER inside the padded content wrapper. This ensures footer backgrounds extend edge-to-edge\n- Cover pages and decorative sections can use full-bleed backgrounds (bg-primary, gradients, images that fill the entire page)\n- Content MUST NOT overflow page boundaries \u2014 be conservative with spacing\n- Use Tailwind CDN classes ONLY (no custom CSS, no @apply, no @import)\n- NO JavaScript, only HTML+Tailwind\n- All text content in Spanish unless the prompt specifies otherwise\n- Use real content from the source material, not Lorem ipsum\n- NOT responsive \u2014 fixed letter size, no breakpoints needed\n- Sections can have ANY background \u2014 full-bleed color, gradients, or white. Not limited to white paper.\n\nSTRICT PROHIBITIONS:\n1. **NO EMOJI** \u2014 Never use emoji characters (\uD83D\uDE80\u274C\u2705\uD83D\uDCCA etc.). Instead use inline SVG icons or colored divs. For bullet decorators use small colored circles (<span class=\"w-2 h-2 rounded-full bg-primary inline-block\"></span>) or simple SVG.\n2. **NO Chart.js / NO JavaScript** \u2014 Never reference Chart.js, canvas, or any JS library. For data visualization use pure CSS: progress bars (div with percentage width + bg-primary), horizontal bars, styled tables with colored cells. Never use <canvas> or <script>.\n3. **NO buttons or CTAs** \u2014 This is a print document, not a web page. No \"Contactar\", \"Ver m\u00E1s\", \"Comprar\" buttons. Use text with contact info instead.\n4. **CONTRAST IS MANDATORY** \u2014 Dark/colored backgrounds (bg-primary, bg-primary-dark, bg-secondary, dark gradients) MUST use text-white or text-on-primary. Light backgrounds (white, bg-surface, bg-surface-alt) MUST use text-gray-900 or text-on-surface. NEVER use dark text on dark backgrounds or light text on light backgrounds.\n5. **Max 2 font weights per page** \u2014 Pick 2 (e.g. font-semibold + font-normal, or font-bold + font-light). Don't mix 4-5 weights.\n6. **Generous whitespace** \u2014 Don't fill every centimeter. Leave breathing room. Use py-8, py-12, gap-6, gap-8 liberally. Less content per page = more professional.\n\nLAYOUT OVERFLOW PREVENTION \u2014 CRITICAL:\n- Max 2 columns side by side \u2014 each with w-1/2. NEVER use 3+ columns.\n- Decorative sidebars: max w-16 (4rem). NEVER use w-[2.5in] or wider sidebars \u2014 they steal too much space.\n- Stats/metric grids: max 3 items per row (grid-cols-3). Use gap-4 or gap-6.\n- Tables: max 4 columns, use text-xs or text-sm for cell text, px-3 py-2 cell padding.\n- Images: always w-full or max-w-[50%] \u2014 never fixed pixel widths.\n- Text: never use text-6xl or larger except for cover page title. Body text: text-sm or text-base.\n- NEVER use absolute positioning that could overflow \u2014 prefer flex/grid layouts.\n- Decorative shapes with absolute positioning MUST stay fully inside the page. Use overflow-hidden on parent AND keep coordinates positive (no negative right/left values).\n- Large decorative text (text-[200px], text-[10rem] etc.) MUST have opacity-5 or lower AND overflow-hidden on its container. These giant texts frequently overflow \u2014 be extra careful.\n- NEVER place elements beyond the right edge \u2014 all content and decorations must fit within 8.5in width.\n\nDESIGN \u2014 ADAPT to the document type. Read the prompt carefully and match the visual style:\n\nGENERAL PRINCIPLES (apply to ALL documents):\n- First page is ALWAYS a stunning cover/title page with impactful design\n- Typography: strong hierarchy with just 2 weights, clear headings vs body\n- Each page visually distinct \u2014 different layouts, accent placements\n- Use the full page creatively \u2014 backgrounds, sidebars, geometric shapes\n- Professional and polished, never generic or template-looking\n- Icons: use simple inline SVG (12-20px) for visual accents. Keep SVGs minimal (single path, no complex illustrations)\n\nADAPT YOUR STYLE to what the user is creating:\n- Reports/Data: structured grids, tables with alternating rows (bg-surface-alt), progress bars, stat cards, clean data hierarchy\n- Brochures/Marketing: bold hero images, large headlines, feature grids, testimonial-style quotes, visual storytelling\n- Catalogs/Products: product cards with images, specs grids, price highlights, category headers with full-bleed color\n- Invitations/Events: centered dramatic typography, decorative borders, elegant spacing, date/location prominently styled\n- Proposals/Pitches: problem\u2192solution flow, metric highlights, team/about sections, pricing tables\n- CVs/Resumes: clean sidebar layouts, skill bars, timeline for experience, contact info header\n- Creative/General: mix techniques \u2014 bento grids, full-bleed images, overlapping elements, bold color blocking\n\nVISUAL TECHNIQUES available to you:\n- Full-bleed colored pages (bg-primary, gradients)\n- Geometric accent shapes (CSS divs with clip-path or rotation)\n- Asymmetric layouts (grid with unequal columns)\n- Large stat numbers as visual anchors (text-5xl font-black)\n- Header/footer bands with contrasting color\n- Sidebar accents (thin, max w-16)\n- Image + text compositions\n- Bento-grid mixing content blocks of different sizes\n- Tables: alternating row colors, clean borders, generous cell padding (px-4 py-3)\n- For numerical data: CSS progress bars, styled tables with colored cells, large stat numbers \u2014 NEVER canvas/charts\n\nCSS PROGRESS BARS \u2014 use this pattern for data visualization:\n<div class=\"w-full bg-gray-200 rounded-full h-3\"><div class=\"bg-primary h-3 rounded-full\" style=\"width: 75%\"></div></div>\n\nCOLOR SYSTEM \u2014 use semantic classes:\n- bg-primary, text-primary, bg-primary-light, bg-primary-dark, text-on-primary\n- bg-surface, bg-surface-alt, text-on-surface, text-on-surface-muted\n- bg-secondary, text-secondary, bg-accent, text-accent\n- Cover pages should use bold full-bleed backgrounds (bg-primary, gradients from-primary to-primary-dark)\n- CONTRAST: bg-primary/bg-primary-dark/bg-secondary \u2192 text-white or text-on-primary. White/bg-surface \u2192 text-gray-900 or text-on-surface\n\nIMAGES \u2014 USE GENEROUSLY:\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 include a src attribute \u2014 the system auto-replaces data-image-query with a real image\n- For avatar-like elements, use colored divs with initials instead of img tags\n- Include at LEAST 3-5 images across the document \u2014 hero images, section illustrations, backgrounds, product photos\n- Each data-image-query should be a UNIQUE, specific search query in English (e.g. \"modern office workspace aerial view\", \"team brainstorming whiteboard\", \"abstract blue technology network\")\n- Use images to break up text-heavy pages and add visual interest\n\nICONS \u2014 use data-icon-query for professional icons:\n- <span data-icon-query=\"icon-name\" class=\"inline-block w-5 h-5 text-primary\"></span>\n- Use common Lucide icon names in English: star, check, arrow-right, heart, zap, shield, users, mail, phone, calendar, clock, map-pin, briefcase, trending-up, award, target, layers, globe, etc.\n- Use in: feature lists, stat cards, CTAs, list items, contact info, section headers\n- Sizes: w-4 h-4 (small), w-5 h-5 (default), w-8 h-8 (large). Color inherits from text-* class.\n- NEVER draw SVG paths manually \u2014 ALWAYS use data-icon-query instead\n- The system auto-replaces data-icon-query with real SVG icons from Iconify\n\nCHARTS & DATA VISUALIZATION (SVG):\n- For charts, diagrams, and decorative data graphics, use:\n <div data-svg-chart=\"bar chart showing Q1 revenue: Jan $45K, Feb $52K, Mar $61K\" class=\"w-full\"></div>\n- The system generates professional SVG charts with a specialized tool \u2014 NEVER draw SVGs yourself\n- Use descriptive prompts with data points: type of chart + what it shows + actual values\n- Examples: \"donut chart: 40% Marketing, 30% Sales, 20% R&D, 10% Admin\", \"line chart showing growth: Q1 $100K, Q2 $150K, Q3 $220K, Q4 $310K\"\n- For simple metrics, still prefer CSS progress bars (they render faster)\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\nEXAMPLE \u2014 Cover page (simple, no wide sidebars):\n<section class=\"w-[8.5in] h-[11in] relative overflow-hidden flex flex-col bg-white\">\n <div class=\"absolute left-0 top-0 w-2 h-full bg-primary\"></div>\n <div class=\"flex-1 overflow-hidden flex flex-col justify-center px-[1in]\">\n <div class=\"text-sm font-normal text-primary mb-4\">Marzo 2026 \u00B7 Versi\u00F3n 1.0</div>\n <h1 class=\"text-5xl font-bold text-gray-900 leading-tight\">Reporte<br/>Trimestral</h1>\n <div class=\"w-16 h-1 bg-primary mt-6 mb-4\"></div>\n <p class=\"text-lg font-normal text-gray-500\">Resultados y an\u00E1lisis del primer trimestre</p>\n </div>\n</section>\n\nEXAMPLE \u2014 Marketing/brochure page (bold, visual):\n<section class=\"w-[8.5in] h-[11in] relative overflow-hidden flex flex-col bg-primary\">\n <div class=\"flex flex-1 overflow-hidden\">\n <div class=\"w-1/2 flex flex-col justify-center px-[0.75in]\">\n <span class=\"text-sm font-normal text-on-primary opacity-70 uppercase tracking-widest mb-3\">Soluci\u00F3n Premium</span>\n <h2 class=\"text-4xl font-bold text-on-primary leading-tight mb-6\">Transforma tu negocio digital</h2>\n <p class=\"text-base font-normal text-on-primary opacity-80 mb-8\">Herramientas inteligentes que simplifican la gesti\u00F3n de tus activos digitales.</p>\n <div class=\"flex gap-6\">\n <div><div class=\"text-3xl font-bold text-accent\">98%</div><div class=\"text-xs text-on-primary opacity-70\">Satisfacci\u00F3n</div></div>\n <div><div class=\"text-3xl font-bold text-accent\">2.4K</div><div class=\"text-xs text-on-primary opacity-70\">Empresas</div></div>\n </div>\n </div>\n <div class=\"w-1/2 relative\">\n <img data-image-query=\"modern office team collaboration technology\" alt=\"Team working\" class=\"absolute inset-0 w-full h-full object-cover\" />\n </div>\n </div>\n</section>\n\nEXAMPLE \u2014 Catalog/product grid page:\n<section class=\"w-[8.5in] h-[11in] relative overflow-hidden flex flex-col bg-surface\">\n <div class=\"shrink-0 h-1 bg-primary w-full\"></div>\n <div class=\"flex-1 overflow-hidden px-[0.75in] py-[0.5in]\">\n <div class=\"flex justify-between items-baseline mb-6\">\n <h2 class=\"text-2xl font-bold text-on-surface\">Colecci\u00F3n Primavera</h2>\n <span class=\"text-xs font-normal text-on-surface-muted uppercase tracking-wider\">P\u00E1gina 3 de 8</span>\n </div>\n <div class=\"grid grid-cols-2 gap-6\">\n <div class=\"bg-surface-alt rounded-xl overflow-hidden\">\n <img data-image-query=\"minimalist product on white background\" alt=\"Product\" class=\"w-full h-48 object-cover\" />\n <div class=\"p-4\"><h3 class=\"font-bold text-on-surface text-sm\">Producto Alpha</h3><p class=\"text-xs text-on-surface-muted mt-1\">Dise\u00F1o ergon\u00F3mico premium</p><div class=\"text-lg font-bold text-primary mt-2\">$2,490</div></div>\n </div>\n <div class=\"bg-surface-alt rounded-xl overflow-hidden\">\n <img data-image-query=\"elegant product photography studio\" alt=\"Product\" class=\"w-full h-48 object-cover\" />\n <div class=\"p-4\"><h3 class=\"font-bold text-on-surface text-sm\">Producto Beta</h3><p class=\"text-xs text-on-surface-muted mt-1\">Tecnolog\u00EDa de vanguardia</p><div class=\"text-lg font-bold text-primary mt-2\">$3,190</div></div>\n </div>\n </div>\n </div>\n <!-- Footer: direct child of section, shrink-0, full width -->\n <div class=\"shrink-0 w-full bg-surface-alt px-[0.75in] py-3 flex justify-between items-center\">\n <span class=\"text-xs text-on-surface-muted\">Colecci\u00F3n Primavera 2026</span>\n <span class=\"text-xs text-on-surface-muted\">P\u00E1gina 3 de 8</span>\n </div>\n</section>\n\nEXAMPLE \u2014 Content page with table + progress bars:\n<section class=\"w-[8.5in] h-[11in] relative overflow-hidden flex flex-col bg-white\">\n <div class=\"shrink-0 h-1.5 bg-primary w-full\"></div>\n <div class=\"flex-1 overflow-hidden px-[0.75in] py-[0.5in]\">\n <h2 class=\"text-2xl font-bold text-gray-900 mb-1\">M\u00E9tricas de Rendimiento</h2>\n <p class=\"text-sm font-normal text-gray-500 mb-8\">Indicadores clave del periodo enero\u2014marzo</p>\n <table class=\"w-full text-sm mb-10\">\n <thead><tr class=\"bg-primary text-white\"><th class=\"px-4 py-3 text-left font-semibold\">Indicador</th><th class=\"px-4 py-3 text-left font-semibold\">Valor</th><th class=\"px-4 py-3 text-left font-semibold\">Meta</th></tr></thead>\n <tbody>\n <tr class=\"bg-surface-alt\"><td class=\"px-4 py-3 text-gray-900\">Ingresos</td><td class=\"px-4 py-3 text-gray-900\">$1.2M</td><td class=\"px-4 py-3 text-gray-900\">$1.5M</td></tr>\n <tr><td class=\"px-4 py-3 text-gray-900\">Clientes nuevos</td><td class=\"px-4 py-3 text-gray-900\">340</td><td class=\"px-4 py-3 text-gray-900\">300</td></tr>\n <tr class=\"bg-surface-alt\"><td class=\"px-4 py-3 text-gray-900\">Retenci\u00F3n</td><td class=\"px-4 py-3 text-gray-900\">92%</td><td class=\"px-4 py-3 text-gray-900\">90%</td></tr>\n </tbody>\n </table>\n <h3 class=\"text-lg font-bold text-gray-900 mb-4\">Progreso por \u00C1rea</h3>\n <div class=\"space-y-4\">\n <div><div class=\"flex justify-between text-sm mb-1\"><span class=\"text-gray-900 font-semibold\">Ventas</span><span class=\"text-gray-500\">80%</span></div><div class=\"w-full bg-gray-200 rounded-full h-3\"><div class=\"bg-primary h-3 rounded-full\" style=\"width: 80%\"></div></div></div>\n <div><div class=\"flex justify-between text-sm mb-1\"><span class=\"text-gray-900 font-semibold\">Marketing</span><span class=\"text-gray-500\">65%</span></div><div class=\"w-full bg-gray-200 rounded-full h-3\"><div class=\"bg-secondary h-3 rounded-full\" style=\"width: 65%\"></div></div></div>\n <div><div class=\"flex justify-between text-sm mb-1\"><span class=\"text-gray-900 font-semibold\">Producto</span><span class=\"text-gray-500\">95%</span></div><div class=\"w-full bg-gray-200 rounded-full h-3\"><div class=\"bg-accent h-3 rounded-full\" style=\"width: 95%\"></div></div></div>\n </div>\n </div>\n</section>";
7
- declare const DOCUMENT_PROMPT_SUFFIX = "\n\nOUTPUT FORMAT: NDJSON \u2014 one JSON object per line, NO wrapper array, NO markdown fences.\nEach line: {\"label\": \"Page Title\", \"html\": \"<section class='w-[8.5in] h-[11in] relative overflow-hidden flex flex-col'>...</section>\"}\n\nGenerate 3-8 pages depending on content length. First page = cover/title page.\nEach page must fit within letter size (8.5\" \u00D7 11\"). Be conservative with spacing.\nMake each page visually distinct \u2014 different layouts, different accent placements.\nIMPORTANT: Adapt your design style to match the type of document \u2014 not everything is a report. Brochures should feel bold and visual, catalogs should showcase products, invitations should feel elegant, etc.";
6
+ type PageFormat = "letter" | "web";
7
+ declare const PAGE_FORMAT_CONFIG: {
8
+ readonly letter: {
9
+ readonly container: "w-[8.5in] h-[11in]";
10
+ readonly bodyText: "text-sm or text-base (10-11px)";
11
+ readonly maxColumns: 2;
12
+ readonly heightMode: "fixed at 11in";
13
+ readonly description: "letter-sized (8.5\" × 11\") document pages";
14
+ };
15
+ readonly web: {
16
+ readonly container: "w-[1280px] min-h-[800px]";
17
+ readonly bodyText: "text-base or text-lg (16-18px)";
18
+ readonly maxColumns: 1;
19
+ readonly heightMode: "flexible, no max height";
20
+ readonly description: "web-optimized document sections";
21
+ };
22
+ };
23
+ declare function getDocumentSystemPrompt(format?: PageFormat): string;
24
+ declare const DOCUMENT_SYSTEM_PROMPT: string;
25
+ declare function getDocumentPromptSuffix(format?: PageFormat): string;
26
+ declare const DOCUMENT_PROMPT_SUFFIX: string;
8
27
  interface GenerateDocumentOptions {
9
28
  anthropicApiKey?: string;
10
29
  openaiApiKey?: string;
@@ -31,54 +50,26 @@ declare const DocumentOutlineSchema: z.ZodObject<{
31
50
  pages: z.ZodArray<z.ZodObject<{
32
51
  pageNumber: z.ZodNumber;
33
52
  label: z.ZodString;
34
- type: z.ZodEnum<["cover", "content", "data", "visual", "closing"]>;
53
+ type: z.ZodEnum<{
54
+ cover: "cover";
55
+ content: "content";
56
+ data: "data";
57
+ visual: "visual";
58
+ closing: "closing";
59
+ }>;
35
60
  layoutHint: z.ZodString;
36
61
  contentBrief: z.ZodString;
37
- keyElements: z.ZodArray<z.ZodString, "many">;
38
- backgroundStyle: z.ZodEnum<["white", "primary", "gradient", "surface-alt", "image"]>;
62
+ keyElements: z.ZodArray<z.ZodString>;
63
+ backgroundStyle: z.ZodEnum<{
64
+ primary: "primary";
65
+ "surface-alt": "surface-alt";
66
+ image: "image";
67
+ white: "white";
68
+ gradient: "gradient";
69
+ }>;
39
70
  continuesFrom: z.ZodOptional<z.ZodString>;
40
- }, "strip", z.ZodTypeAny, {
41
- type: "cover" | "content" | "data" | "visual" | "closing";
42
- layoutHint: string;
43
- pageNumber: number;
44
- label: string;
45
- contentBrief: string;
46
- keyElements: string[];
47
- backgroundStyle: "primary" | "surface-alt" | "image" | "white" | "gradient";
48
- continuesFrom?: string | undefined;
49
- }, {
50
- type: "cover" | "content" | "data" | "visual" | "closing";
51
- layoutHint: string;
52
- pageNumber: number;
53
- label: string;
54
- contentBrief: string;
55
- keyElements: string[];
56
- backgroundStyle: "primary" | "surface-alt" | "image" | "white" | "gradient";
57
- continuesFrom?: string | undefined;
58
- }>, "many">;
59
- }, "strip", z.ZodTypeAny, {
60
- pages: {
61
- type: "cover" | "content" | "data" | "visual" | "closing";
62
- layoutHint: string;
63
- pageNumber: number;
64
- label: string;
65
- contentBrief: string;
66
- keyElements: string[];
67
- backgroundStyle: "primary" | "surface-alt" | "image" | "white" | "gradient";
68
- continuesFrom?: string | undefined;
69
- }[];
70
- }, {
71
- pages: {
72
- type: "cover" | "content" | "data" | "visual" | "closing";
73
- layoutHint: string;
74
- pageNumber: number;
75
- label: string;
76
- contentBrief: string;
77
- keyElements: string[];
78
- backgroundStyle: "primary" | "surface-alt" | "image" | "white" | "gradient";
79
- continuesFrom?: string | undefined;
80
- }[];
81
- }>;
71
+ }, z.core.$strip>>;
72
+ }, z.core.$strip>;
82
73
  type DocumentOutline = z.infer<typeof DocumentOutlineSchema>;
83
74
  interface GenerateDocumentParallelOptions {
84
75
  anthropicApiKey?: string;
@@ -98,6 +89,7 @@ interface GenerateDocumentParallelOptions {
98
89
  persistImage?: (tempUrl: string, query: string) => Promise<string>;
99
90
  pageCount?: number;
100
91
  skipCover?: boolean;
92
+ pageFormat?: PageFormat;
101
93
  onOutline?: (outline: DocumentOutline) => void;
102
94
  onPageChunk?: (pageIndex: number, partialHtml: string) => void;
103
95
  onPageComplete?: (pageIndex: number, section: Section3) => void;
@@ -112,4 +104,4 @@ interface GenerateDocumentParallelOptions {
112
104
  }
113
105
  declare function generateDocumentParallel(options: GenerateDocumentParallelOptions): Promise<Section3[]>;
114
106
 
115
- export { DOCUMENT_PROMPT_SUFFIX, DOCUMENT_SYSTEM_PROMPT, type DocumentOutline, type GenerateDocumentOptions, type GenerateDocumentParallelOptions, generateDocument, generateDocumentParallel };
107
+ export { DOCUMENT_PROMPT_SUFFIX, DOCUMENT_SYSTEM_PROMPT, type DocumentOutline, type GenerateDocumentOptions, type GenerateDocumentParallelOptions, PAGE_FORMAT_CONFIG, type PageFormat, generateDocument, generateDocumentParallel, getDocumentPromptSuffix, getDocumentSystemPrompt };
@@ -1,14 +1,20 @@
1
1
  import {
2
2
  DOCUMENT_PROMPT_SUFFIX,
3
3
  DOCUMENT_SYSTEM_PROMPT,
4
+ PAGE_FORMAT_CONFIG,
4
5
  generateDocument,
5
- generateDocumentParallel
6
- } from "./chunk-6LK7JW6Q.js";
6
+ generateDocumentParallel,
7
+ getDocumentPromptSuffix,
8
+ getDocumentSystemPrompt
9
+ } from "./chunk-X5MEN76P.js";
7
10
  import "./chunk-YZHRLDQF.js";
8
11
  export {
9
12
  DOCUMENT_PROMPT_SUFFIX,
10
13
  DOCUMENT_SYSTEM_PROMPT,
14
+ PAGE_FORMAT_CONFIG,
11
15
  generateDocument,
12
- generateDocumentParallel
16
+ generateDocumentParallel,
17
+ getDocumentPromptSuffix,
18
+ getDocumentSystemPrompt
13
19
  };
14
20
  //# sourceMappingURL=generateDocument.js.map
package/dist/index.js CHANGED
@@ -15,7 +15,7 @@ import {
15
15
  DOCUMENT_PROMPT_SUFFIX,
16
16
  DOCUMENT_SYSTEM_PROMPT,
17
17
  generateDocument
18
- } from "./chunk-6LK7JW6Q.js";
18
+ } from "./chunk-X5MEN76P.js";
19
19
  import {
20
20
  REFINE_SYSTEM,
21
21
  refineLanding
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@easybits.cloud/html-tailwind-generator",
3
- "version": "0.2.125",
3
+ "version": "0.2.126",
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",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/generateDocument.ts"],"sourcesContent":["import { generateObject, streamText } from \"ai\";\nimport { z } from \"zod\";\nimport { nanoid } from \"nanoid\";\nimport {\n streamGenerate,\n dataUrlToImagePart,\n resolveModel,\n currentDateLine,\n extractJsonObjects,\n addLoadingPlaceholders,\n addSvgLoadingPlaceholders,\n enrichSectionImages,\n enrichSectionSvgCharts,\n enrichSectionIconSlots,\n} from \"./streamCore\";\nimport { sanitizeSemanticColors } from \"./sanitizeColors\";\nimport type { Section3 } from \"./types\";\nimport type { DesignDirection } from \"./directions\";\n\nexport const DOCUMENT_SYSTEM_PROMPT = `You are a professional document designer who creates stunning letter-sized (8.5\" × 11\") document pages using HTML + Tailwind CSS.\n\nRULES:\n- Each page is a <section> element sized for letter paper\n- Page structure: <section class=\"w-[8.5in] h-[11in] relative overflow-hidden flex flex-col\">\n- The section is EXACTLY 11in tall — content MUST fit, never exceed. Use flex flex-col so children can use flex-1.\n- The section itself has NO padding — backgrounds, gradients, and decorative elements go edge-to-edge\n- Use slot layout: shrink-0 for header/footer bands, flex-1 overflow-hidden for main content area\n- For text content, use an inner wrapper: <div class=\"flex-1 overflow-hidden px-[0.75in] py-[0.5in]\">...content...</div>\n- Footer elements (page numbers, decorative bars, contact info) MUST be direct children of <section> with shrink-0 and w-full — NEVER inside the padded content wrapper. This ensures footer backgrounds extend edge-to-edge\n- Cover pages and decorative sections can use full-bleed backgrounds (bg-primary, gradients, images that fill the entire page)\n- Content MUST NOT overflow page boundaries — be conservative with spacing\n- Use Tailwind CDN classes ONLY (no custom CSS, no @apply, no @import)\n- NO JavaScript, only HTML+Tailwind\n- All text content in Spanish unless the prompt specifies otherwise\n- Use real content from the source material, not Lorem ipsum\n- NOT responsive — fixed letter size, no breakpoints needed\n- Sections can have ANY background — full-bleed color, gradients, or white. Not limited to white paper.\n\nSTRICT PROHIBITIONS:\n1. **NO EMOJI** — Never use emoji characters (🚀❌✅📊 etc.). Instead use inline SVG icons or colored divs. For bullet decorators use small colored circles (<span class=\"w-2 h-2 rounded-full bg-primary inline-block\"></span>) or simple SVG.\n2. **NO Chart.js / NO JavaScript** — Never reference Chart.js, canvas, or any JS library. For data visualization use pure CSS: progress bars (div with percentage width + bg-primary), horizontal bars, styled tables with colored cells. Never use <canvas> or <script>.\n3. **NO buttons or CTAs** — This is a print document, not a web page. No \"Contactar\", \"Ver más\", \"Comprar\" buttons. Use text with contact info instead.\n4. **CONTRAST IS MANDATORY** — Dark/colored backgrounds (bg-primary, bg-primary-dark, bg-secondary, dark gradients) MUST use text-white or text-on-primary. Light backgrounds (white, bg-surface, bg-surface-alt) MUST use text-gray-900 or text-on-surface. NEVER use dark text on dark backgrounds or light text on light backgrounds.\n5. **Max 2 font weights per page** — Pick 2 (e.g. font-semibold + font-normal, or font-bold + font-light). Don't mix 4-5 weights.\n6. **Generous whitespace** — Don't fill every centimeter. Leave breathing room. Use py-8, py-12, gap-6, gap-8 liberally. Less content per page = more professional.\n\nLAYOUT OVERFLOW PREVENTION — CRITICAL:\n- Max 2 columns side by side — each with w-1/2. NEVER use 3+ columns.\n- Decorative sidebars: max w-16 (4rem). NEVER use w-[2.5in] or wider sidebars — they steal too much space.\n- Stats/metric grids: max 3 items per row (grid-cols-3). Use gap-4 or gap-6.\n- Tables: max 4 columns, use text-xs or text-sm for cell text, px-3 py-2 cell padding.\n- Images: always w-full or max-w-[50%] — never fixed pixel widths.\n- Text: never use text-6xl or larger except for cover page title. Body text: text-sm or text-base.\n- NEVER use absolute positioning that could overflow — prefer flex/grid layouts.\n- Decorative shapes with absolute positioning MUST stay fully inside the page. Use overflow-hidden on parent AND keep coordinates positive (no negative right/left values).\n- Large decorative text (text-[200px], text-[10rem] etc.) MUST have opacity-5 or lower AND overflow-hidden on its container. These giant texts frequently overflow — be extra careful.\n- NEVER place elements beyond the right edge — all content and decorations must fit within 8.5in width.\n\nDESIGN — ADAPT to the document type. Read the prompt carefully and match the visual style:\n\nGENERAL PRINCIPLES (apply to ALL documents):\n- First page is ALWAYS a stunning cover/title page with impactful design\n- Typography: strong hierarchy with just 2 weights, clear headings vs body\n- Each page visually distinct — different layouts, accent placements\n- Use the full page creatively — backgrounds, sidebars, geometric shapes\n- Professional and polished, never generic or template-looking\n- Icons: use simple inline SVG (12-20px) for visual accents. Keep SVGs minimal (single path, no complex illustrations)\n\nADAPT YOUR STYLE to what the user is creating:\n- Reports/Data: structured grids, tables with alternating rows (bg-surface-alt), progress bars, stat cards, clean data hierarchy\n- Brochures/Marketing: bold hero images, large headlines, feature grids, testimonial-style quotes, visual storytelling\n- Catalogs/Products: product cards with images, specs grids, price highlights, category headers with full-bleed color\n- Invitations/Events: centered dramatic typography, decorative borders, elegant spacing, date/location prominently styled\n- Proposals/Pitches: problem→solution flow, metric highlights, team/about sections, pricing tables\n- CVs/Resumes: clean sidebar layouts, skill bars, timeline for experience, contact info header\n- Creative/General: mix techniques — bento grids, full-bleed images, overlapping elements, bold color blocking\n\nVISUAL TECHNIQUES available to you:\n- Full-bleed colored pages (bg-primary, gradients)\n- Geometric accent shapes (CSS divs with clip-path or rotation)\n- Asymmetric layouts (grid with unequal columns)\n- Large stat numbers as visual anchors (text-5xl font-black)\n- Header/footer bands with contrasting color\n- Sidebar accents (thin, max w-16)\n- Image + text compositions\n- Bento-grid mixing content blocks of different sizes\n- Tables: alternating row colors, clean borders, generous cell padding (px-4 py-3)\n- For numerical data: CSS progress bars, styled tables with colored cells, large stat numbers — NEVER canvas/charts\n\nCSS PROGRESS BARS — use this pattern for data visualization:\n<div class=\"w-full bg-gray-200 rounded-full h-3\"><div class=\"bg-primary h-3 rounded-full\" style=\"width: 75%\"></div></div>\n\nCOLOR SYSTEM — use semantic classes:\n- bg-primary, text-primary, bg-primary-light, bg-primary-dark, text-on-primary\n- bg-surface, bg-surface-alt, text-on-surface, text-on-surface-muted\n- bg-secondary, text-secondary, bg-accent, text-accent\n- Cover pages should use bold full-bleed backgrounds (bg-primary, gradients from-primary to-primary-dark)\n- CONTRAST: bg-primary/bg-primary-dark/bg-secondary → text-white or text-on-primary. White/bg-surface → text-gray-900 or text-on-surface\n\nIMAGES — USE GENEROUSLY:\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 include a src attribute — the system auto-replaces data-image-query with a real image\n- For avatar-like elements, use colored divs with initials instead of img tags\n- Include at LEAST 3-5 images across the document — hero images, section illustrations, backgrounds, product photos\n- Each data-image-query should be a UNIQUE, specific search query in English (e.g. \"modern office workspace aerial view\", \"team brainstorming whiteboard\", \"abstract blue technology network\")\n- Use images to break up text-heavy pages and add visual interest\n\nICONS — use data-icon-query for professional icons:\n- <span data-icon-query=\"icon-name\" class=\"inline-block w-5 h-5 text-primary\"></span>\n- Use common Lucide icon names in English: star, check, arrow-right, heart, zap, shield, users, mail, phone, calendar, clock, map-pin, briefcase, trending-up, award, target, layers, globe, etc.\n- Use in: feature lists, stat cards, CTAs, list items, contact info, section headers\n- Sizes: w-4 h-4 (small), w-5 h-5 (default), w-8 h-8 (large). Color inherits from text-* class.\n- NEVER draw SVG paths manually — ALWAYS use data-icon-query instead\n- The system auto-replaces data-icon-query with real SVG icons from Iconify\n\nCHARTS & DATA VISUALIZATION (SVG):\n- For charts, diagrams, and decorative data graphics, use:\n <div data-svg-chart=\"bar chart showing Q1 revenue: Jan $45K, Feb $52K, Mar $61K\" class=\"w-full\"></div>\n- The system generates professional SVG charts with a specialized tool — NEVER draw SVGs yourself\n- Use descriptive prompts with data points: type of chart + what it shows + actual values\n- Examples: \"donut chart: 40% Marketing, 30% Sales, 20% R&D, 10% Admin\", \"line chart showing growth: Q1 $100K, Q2 $150K, Q3 $220K, Q4 $310K\"\n- For simple metrics, still prefer CSS progress bars (they render faster)\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\nEXAMPLE — Cover page (simple, no wide sidebars):\n<section class=\"w-[8.5in] h-[11in] relative overflow-hidden flex flex-col bg-white\">\n <div class=\"absolute left-0 top-0 w-2 h-full bg-primary\"></div>\n <div class=\"flex-1 overflow-hidden flex flex-col justify-center px-[1in]\">\n <div class=\"text-sm font-normal text-primary mb-4\">Marzo 2026 · Versión 1.0</div>\n <h1 class=\"text-5xl font-bold text-gray-900 leading-tight\">Reporte<br/>Trimestral</h1>\n <div class=\"w-16 h-1 bg-primary mt-6 mb-4\"></div>\n <p class=\"text-lg font-normal text-gray-500\">Resultados y análisis del primer trimestre</p>\n </div>\n</section>\n\nEXAMPLE — Marketing/brochure page (bold, visual):\n<section class=\"w-[8.5in] h-[11in] relative overflow-hidden flex flex-col bg-primary\">\n <div class=\"flex flex-1 overflow-hidden\">\n <div class=\"w-1/2 flex flex-col justify-center px-[0.75in]\">\n <span class=\"text-sm font-normal text-on-primary opacity-70 uppercase tracking-widest mb-3\">Solución Premium</span>\n <h2 class=\"text-4xl font-bold text-on-primary leading-tight mb-6\">Transforma tu negocio digital</h2>\n <p class=\"text-base font-normal text-on-primary opacity-80 mb-8\">Herramientas inteligentes que simplifican la gestión de tus activos digitales.</p>\n <div class=\"flex gap-6\">\n <div><div class=\"text-3xl font-bold text-accent\">98%</div><div class=\"text-xs text-on-primary opacity-70\">Satisfacción</div></div>\n <div><div class=\"text-3xl font-bold text-accent\">2.4K</div><div class=\"text-xs text-on-primary opacity-70\">Empresas</div></div>\n </div>\n </div>\n <div class=\"w-1/2 relative\">\n <img data-image-query=\"modern office team collaboration technology\" alt=\"Team working\" class=\"absolute inset-0 w-full h-full object-cover\" />\n </div>\n </div>\n</section>\n\nEXAMPLE — Catalog/product grid page:\n<section class=\"w-[8.5in] h-[11in] relative overflow-hidden flex flex-col bg-surface\">\n <div class=\"shrink-0 h-1 bg-primary w-full\"></div>\n <div class=\"flex-1 overflow-hidden px-[0.75in] py-[0.5in]\">\n <div class=\"flex justify-between items-baseline mb-6\">\n <h2 class=\"text-2xl font-bold text-on-surface\">Colección Primavera</h2>\n <span class=\"text-xs font-normal text-on-surface-muted uppercase tracking-wider\">Página 3 de 8</span>\n </div>\n <div class=\"grid grid-cols-2 gap-6\">\n <div class=\"bg-surface-alt rounded-xl overflow-hidden\">\n <img data-image-query=\"minimalist product on white background\" alt=\"Product\" class=\"w-full h-48 object-cover\" />\n <div class=\"p-4\"><h3 class=\"font-bold text-on-surface text-sm\">Producto Alpha</h3><p class=\"text-xs text-on-surface-muted mt-1\">Diseño ergonómico premium</p><div class=\"text-lg font-bold text-primary mt-2\">$2,490</div></div>\n </div>\n <div class=\"bg-surface-alt rounded-xl overflow-hidden\">\n <img data-image-query=\"elegant product photography studio\" alt=\"Product\" class=\"w-full h-48 object-cover\" />\n <div class=\"p-4\"><h3 class=\"font-bold text-on-surface text-sm\">Producto Beta</h3><p class=\"text-xs text-on-surface-muted mt-1\">Tecnología de vanguardia</p><div class=\"text-lg font-bold text-primary mt-2\">$3,190</div></div>\n </div>\n </div>\n </div>\n <!-- Footer: direct child of section, shrink-0, full width -->\n <div class=\"shrink-0 w-full bg-surface-alt px-[0.75in] py-3 flex justify-between items-center\">\n <span class=\"text-xs text-on-surface-muted\">Colección Primavera 2026</span>\n <span class=\"text-xs text-on-surface-muted\">Página 3 de 8</span>\n </div>\n</section>\n\nEXAMPLE — Content page with table + progress bars:\n<section class=\"w-[8.5in] h-[11in] relative overflow-hidden flex flex-col bg-white\">\n <div class=\"shrink-0 h-1.5 bg-primary w-full\"></div>\n <div class=\"flex-1 overflow-hidden px-[0.75in] py-[0.5in]\">\n <h2 class=\"text-2xl font-bold text-gray-900 mb-1\">Métricas de Rendimiento</h2>\n <p class=\"text-sm font-normal text-gray-500 mb-8\">Indicadores clave del periodo enero—marzo</p>\n <table class=\"w-full text-sm mb-10\">\n <thead><tr class=\"bg-primary text-white\"><th class=\"px-4 py-3 text-left font-semibold\">Indicador</th><th class=\"px-4 py-3 text-left font-semibold\">Valor</th><th class=\"px-4 py-3 text-left font-semibold\">Meta</th></tr></thead>\n <tbody>\n <tr class=\"bg-surface-alt\"><td class=\"px-4 py-3 text-gray-900\">Ingresos</td><td class=\"px-4 py-3 text-gray-900\">$1.2M</td><td class=\"px-4 py-3 text-gray-900\">$1.5M</td></tr>\n <tr><td class=\"px-4 py-3 text-gray-900\">Clientes nuevos</td><td class=\"px-4 py-3 text-gray-900\">340</td><td class=\"px-4 py-3 text-gray-900\">300</td></tr>\n <tr class=\"bg-surface-alt\"><td class=\"px-4 py-3 text-gray-900\">Retención</td><td class=\"px-4 py-3 text-gray-900\">92%</td><td class=\"px-4 py-3 text-gray-900\">90%</td></tr>\n </tbody>\n </table>\n <h3 class=\"text-lg font-bold text-gray-900 mb-4\">Progreso por Área</h3>\n <div class=\"space-y-4\">\n <div><div class=\"flex justify-between text-sm mb-1\"><span class=\"text-gray-900 font-semibold\">Ventas</span><span class=\"text-gray-500\">80%</span></div><div class=\"w-full bg-gray-200 rounded-full h-3\"><div class=\"bg-primary h-3 rounded-full\" style=\"width: 80%\"></div></div></div>\n <div><div class=\"flex justify-between text-sm mb-1\"><span class=\"text-gray-900 font-semibold\">Marketing</span><span class=\"text-gray-500\">65%</span></div><div class=\"w-full bg-gray-200 rounded-full h-3\"><div class=\"bg-secondary h-3 rounded-full\" style=\"width: 65%\"></div></div></div>\n <div><div class=\"flex justify-between text-sm mb-1\"><span class=\"text-gray-900 font-semibold\">Producto</span><span class=\"text-gray-500\">95%</span></div><div class=\"w-full bg-gray-200 rounded-full h-3\"><div class=\"bg-accent h-3 rounded-full\" style=\"width: 95%\"></div></div></div>\n </div>\n </div>\n</section>`;\n\nexport const DOCUMENT_PROMPT_SUFFIX = `\n\nOUTPUT FORMAT: NDJSON — one JSON object per line, NO wrapper array, NO markdown fences.\nEach line: {\"label\": \"Page Title\", \"html\": \"<section class='w-[8.5in] h-[11in] relative overflow-hidden flex flex-col'>...</section>\"}\n\nGenerate 3-8 pages depending on content length. First page = cover/title page.\nEach page must fit within letter size (8.5\" × 11\"). Be conservative with spacing.\nMake each page visually distinct — different layouts, different accent placements.\nIMPORTANT: Adapt your design style to match the type of document — not everything is a report. Brochures should feel bold and visual, catalogs should showcase products, invitations should feel elegant, etc.`;\n\nexport interface GenerateDocumentOptions {\n anthropicApiKey?: string;\n openaiApiKey?: string;\n prompt: string;\n logoUrl?: string;\n referenceImage?: string;\n extraInstructions?: string;\n model?: string | import(\"ai\").LanguageModel;\n pexelsApiKey?: string;\n /** Design direction — injects Google Fonts + hex colors into the prompt */\n direction?: DesignDirection;\n persistImage?: (tempUrl: string, query: string) => Promise<string>;\n onSection?: (section: Section3) => void;\n onImageUpdate?: (sectionId: string, html: string) => void;\n onRawChunk?: (buffer: string, completedCount: number) => void;\n onDone?: (sections: Section3[]) => void;\n onError?: (error: Error) => void;\n}\n\n/**\n * Generate a multi-page document with streaming AI + image enrichment.\n */\nexport async function generateDocument(options: GenerateDocumentOptions): Promise<Section3[]> {\n const {\n prompt,\n logoUrl,\n referenceImage,\n extraInstructions,\n direction,\n ...rest\n } = options;\n\n const extra = extraInstructions ? `\\nAdditional instructions: ${extraInstructions}` : \"\";\n\n // Build direction style instructions if provided\n let directionInstruction = \"\";\n if (direction) {\n const fontsUrl = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(direction.headingFont).replace(/%20/g, \"+\")}:wght@400;700;900&family=${encodeURIComponent(direction.bodyFont).replace(/%20/g, \"+\")}:wght@400;500;600&display=swap`;\n directionInstruction = `\nDESIGN DIRECTION: \"${direction.name}\" — ${direction.tagline}\nTYPOGRAPHY: Use these Google Fonts via <link href=\"${fontsUrl}\" rel=\"stylesheet\"> on the first page.\n- Headings: font-family: '${direction.headingFont}', sans-serif (via inline style)\n- Body: font-family: '${direction.bodyFont}', sans-serif (via inline style)\nCOLORS — use ONLY semantic Tailwind classes (the editor injects CSS variables that resolve these):\n- bg-primary, text-primary, bg-primary-light, bg-primary-dark, text-on-primary\n- bg-surface, bg-surface-alt, text-on-surface, text-on-surface-muted\n- bg-secondary, text-secondary, bg-accent, text-accent\n- NEVER use hardcoded hex colors like bg-[#xxx] or text-[#xxx] — always use semantic classes\n- The palette is: primary=${direction.colors.primary}, accent=${direction.colors.accent}, surface=${direction.colors.surface}\nMood: ${direction.mood}\nLayout approach: ${direction.layoutHint}\nIMPORTANT: Apply inline style=\"font-family: '${direction.headingFont}'\" on ALL heading elements and style=\"font-family: '${direction.bodyFont}'\" on ALL body text elements. Include the Google Fonts <link> tag inside the FIRST <section> only.`;\n }\n // Truncate prompt to prevent token overflow (max ~15K chars ≈ 5K tokens)\n const safePrompt = prompt.length > 15_000 ? prompt.substring(0, 15_000) + \"\\n[...content truncated...]\" : prompt;\n const logoInstruction = logoUrl\n ? `\\nLOGO: Include this logo on the cover page and as a small header on other pages:\\n<img src=\"${logoUrl}\" alt=\"Logo\" class=\"h-12 object-contain\" />\\nUse this exact <img> tag with this exact src URL — do NOT invent a different URL or modify it.`\n : \"\";\n\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: `Create a professional document inspired by this reference image for: ${safePrompt}${logoInstruction}${directionInstruction}${extra}${DOCUMENT_PROMPT_SUFFIX}`,\n });\n } else {\n content.push({\n type: \"text\",\n text: `Create a professional document for: ${safePrompt}${logoInstruction}${directionInstruction}${extra}${DOCUMENT_PROMPT_SUFFIX}`,\n });\n }\n\n return streamGenerate({\n ...rest,\n systemPrompt: DOCUMENT_SYSTEM_PROMPT,\n userContent: content,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Parallel Document Generation\n// ---------------------------------------------------------------------------\n\nconst DocumentOutlineSchema = z.object({\n pages: z.array(z.object({\n pageNumber: z.number(),\n label: z.string().describe(\"Page title for sidebar\"),\n type: z.enum([\"cover\", \"content\", \"data\", \"visual\", \"closing\"]),\n layoutHint: z.string().describe(\"Layout approach: split, full-bleed, grid, editorial, table-heavy, sidebar\"),\n contentBrief: z.string().describe(\"2-4 sentences describing exactly what goes on this page\"),\n keyElements: z.array(z.string()).describe(\"Specific elements: stats grid, table, hero image, timeline, etc.\"),\n backgroundStyle: z.enum([\"white\", \"primary\", \"gradient\", \"surface-alt\", \"image\"]),\n continuesFrom: z.string().optional().describe(\"How this page relates to the previous one\"),\n })),\n});\n\nexport type DocumentOutline = z.infer<typeof DocumentOutlineSchema>;\n\nexport interface GenerateDocumentParallelOptions {\n anthropicApiKey?: string;\n openaiApiKey?: string;\n prompt: string;\n logoUrl?: string;\n referenceImage?: string;\n /** Per-page reference images (e.g. rendered from PDF pages). Index matches page order. */\n referencePages?: string[];\n extraInstructions?: string;\n /** Model for page generation (quality model) */\n model?: string | import(\"ai\").LanguageModel;\n /** Model for outline generation (fast model) */\n outlineModel?: string | import(\"ai\").LanguageModel;\n pexelsApiKey?: string;\n direction?: DesignDirection;\n persistImage?: (tempUrl: string, query: string) => Promise<string>;\n pageCount?: number;\n skipCover?: boolean;\n onOutline?: (outline: DocumentOutline) => void;\n onPageChunk?: (pageIndex: number, partialHtml: string) => void;\n onPageComplete?: (pageIndex: number, section: Section3) => void;\n onImageUpdate?: (sectionId: string, html: string) => void;\n onDone?: (sections: Section3[]) => void;\n onError?: (error: Error) => void;\n /** Called with accumulated token usage from outline + all pages */\n onUsage?: (usage: { inputTokens: number; outputTokens: number }) => void;\n}\n\nfunction buildDirectionInstruction(direction: DesignDirection): string {\n const fontsUrl = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(direction.headingFont).replace(/%20/g, \"+\")}:wght@400;700;900&family=${encodeURIComponent(direction.bodyFont).replace(/%20/g, \"+\")}:wght@400;500;600&display=swap`;\n return `\nDESIGN DIRECTION: \"${direction.name}\" — ${direction.tagline}\nTYPOGRAPHY: Use these Google Fonts via <link href=\"${fontsUrl}\" rel=\"stylesheet\"> on the first page.\n- Headings: font-family: '${direction.headingFont}', sans-serif (via inline style)\n- Body: font-family: '${direction.bodyFont}', sans-serif (via inline style)\nCOLORS — use ONLY semantic Tailwind classes (the editor injects CSS variables that resolve these):\n- bg-primary, text-primary, bg-primary-light, bg-primary-dark, text-on-primary\n- bg-surface, bg-surface-alt, text-on-surface, text-on-surface-muted\n- bg-secondary, text-secondary, bg-accent, text-accent\n- NEVER use hardcoded hex colors like bg-[#xxx] or text-[#xxx] — always use semantic classes\n- The palette is: primary=${direction.colors.primary}, accent=${direction.colors.accent}, surface=${direction.colors.surface}\nMood: ${direction.mood}\nLayout approach: ${direction.layoutHint}\nIMPORTANT: Apply inline style=\"font-family: '${direction.headingFont}'\" on ALL heading elements and style=\"font-family: '${direction.bodyFont}'\" on ALL body text elements. Include the Google Fonts <link> tag inside the FIRST <section> only.`;\n}\n\n/** Extract partial HTML from a raw JSON buffer (same pattern as onRawChunk) */\nfunction extractPartialHtml(buffer: string): string | null {\n const htmlMatch = buffer.match(/\"html\"\\s*:\\s*\"([\\s\\S]*)/);\n if (!htmlMatch) return null;\n let partial = htmlMatch[1]\n .replace(/\\\\n/g, '\\n').replace(/\\\\\"/g, '\"').replace(/\\\\\\\\/g, '\\\\');\n if (partial.endsWith('\\\\')) partial = partial.slice(0, -1);\n const lastQuote = partial.lastIndexOf('\"');\n if (lastQuote > 0) partial = partial.slice(0, lastQuote);\n if (/<section/i.test(partial) && !/<\\/section>/i.test(partial)) {\n partial += '</section>';\n }\n return partial.length > 20 ? partial : null;\n}\n\nexport async function generateDocumentParallel(options: GenerateDocumentParallelOptions): Promise<Section3[]> {\n const {\n anthropicApiKey,\n openaiApiKey: _openaiApiKey,\n prompt,\n logoUrl,\n referenceImage,\n referencePages,\n extraInstructions,\n model: pageModelId,\n outlineModel: outlineModelId,\n pexelsApiKey,\n direction,\n persistImage,\n pageCount,\n skipCover,\n onOutline,\n onPageChunk,\n onPageComplete,\n onImageUpdate,\n onDone,\n onError,\n onUsage,\n } = options;\n\n const openaiApiKey = _openaiApiKey || process.env.OPENAI_API_KEY;\n\n try {\n // --- Phase 1: Generate outline ---\n const outlineModel = await resolveModel({\n openaiApiKey,\n anthropicApiKey,\n modelId: outlineModelId,\n defaultOpenai: \"gpt-4.1-mini\",\n defaultAnthropic: \"claude-haiku-4-5-20251001\",\n });\n\n const safePrompt = prompt.length > 15_000 ? prompt.substring(0, 15_000) + \"\\n[...content truncated...]\" : prompt;\n const extra = extraInstructions ? `\\nAdditional instructions: ${extraInstructions}` : \"\";\n const pageCountHint = skipCover\n ? `Generate exactly ${Math.max(1, (pageCount || 5) - 1)} content pages (NO cover — it already exists).`\n : pageCount\n ? `Generate exactly ${pageCount} pages including a cover page.`\n : \"Generate 3-8 pages including a cover page.\";\n\n let totalInputTokens = 0;\n let totalOutputTokens = 0;\n\n const { object: rawOutline, usage: outlineUsage } = await generateObject({\n model: outlineModel,\n schema: DocumentOutlineSchema,\n prompt: `You are planning a professional document. Create a detailed page-by-page outline.\n\nDOCUMENT BRIEF: ${safePrompt}${extra}\n\nRULES:\n- ${pageCountHint}\n${skipCover ? \"- CRITICAL: Do NOT include a cover/title page. The cover already exists. Start with page type 'content', 'data', or 'visual'. NEVER use type 'cover'.\" : \"- First page is ALWAYS a stunning cover/title page.\"}\n- Distribute content EVENLY — no page should be overloaded\n- Each page must have a DISTINCT layout (mix split, full-bleed, grid, editorial, sidebar, table-heavy)\n- Narrative flows naturally: ${skipCover ? \"introduction → detail → data → closing\" : \"cover → introduction → detail → data → closing\"}\n- contentBrief must be detailed enough that a separate AI can generate the page independently\n- keyElements must list specific visual elements (not vague descriptions)\n- Vary backgroundStyle across pages — not all white\n- If source content is provided, assign specific portions to each page in the contentBrief\n${direction ? `- Design mood: ${direction.mood}, layout approach: ${direction.layoutHint}` : \"\"}`,\n });\n\n totalInputTokens += outlineUsage?.inputTokens || 0;\n totalOutputTokens += outlineUsage?.outputTokens || 0;\n\n // Filter out any cover pages if skipCover (AI sometimes ignores instructions)\n const outline: DocumentOutline = skipCover\n ? { pages: rawOutline.pages.filter(p => p.type !== \"cover\").map((p, i) => ({ ...p, pageNumber: i + 1 })) }\n : rawOutline;\n\n onOutline?.(outline);\n\n // --- Phase 2: Generate pages in parallel ---\n const directionInstruction = direction ? buildDirectionInstruction(direction) : \"\";\n const logoInstruction = logoUrl\n ? `\\nLOGO: Include this logo on the cover page and as a small header on other pages:\\n<img src=\"${logoUrl}\" alt=\"Logo\" class=\"h-12 object-contain\" />\\nUse this exact <img> tag with this exact src URL.`\n : \"\";\n\n const outlineJson = JSON.stringify(outline.pages, null, 2);\n\n const pageModel = await resolveModel({\n openaiApiKey,\n anthropicApiKey,\n modelId: pageModelId,\n defaultOpenai: \"gpt-4o\",\n defaultAnthropic: \"claude-sonnet-4-6\",\n });\n\n async function generateSinglePage(\n page: DocumentOutline[\"pages\"][number],\n retryCount = 0\n ): Promise<Section3> {\n const pageIdx = page.pageNumber - 1;\n const isCover = page.type === \"cover\";\n\n const userContent: any[] = [];\n\n // Per-page reference image from PDF (takes priority)\n const pageRef = referencePages?.[pageIdx];\n if (pageRef) {\n const converted = dataUrlToImagePart(pageRef);\n if (converted) {\n userContent.push({ type: \"image\", ...converted });\n } else {\n userContent.push({ type: \"image\", image: pageRef });\n }\n } else if (referenceImage && (isCover || page.type === \"visual\")) {\n // Fallback: single reference image for cover/visual pages\n const converted = dataUrlToImagePart(referenceImage);\n if (converted) {\n userContent.push({ type: \"image\", ...converted });\n } else {\n userContent.push({ type: \"image\", image: referenceImage });\n }\n }\n\n const hasRefImage = !!pageRef || !!(referenceImage && (isCover || page.type === \"visual\"));\n userContent.push({\n type: \"text\",\n text: `You are generating PAGE ${page.pageNumber} of ${outline.pages.length} for a professional document.\n${hasRefImage ? \"\\nREFERENCE IMAGE: The attached image shows the design to replicate. Match its layout, typography style, and visual structure as closely as possible while using the semantic color system and content from the brief.\" : \"\"}\n\nFULL DOCUMENT OUTLINE (for context — you are generating ONLY page ${page.pageNumber}):\n${outlineJson}\n\nYOUR PAGE ASSIGNMENT:\n- Label: ${page.label}\n- Type: ${page.type}\n- Layout: ${page.layoutHint}\n- Background: ${page.backgroundStyle}\n- Content: ${page.contentBrief}\n- Key elements: ${page.keyElements.join(\", \")}\n${page.continuesFrom ? `- Continues from: ${page.continuesFrom}` : \"\"}\n${isCover ? logoInstruction : logoUrl ? `\\nSmall logo header: <img src=\"${logoUrl}\" alt=\"Logo\" class=\"h-8 object-contain\" />` : \"\"}\n${directionInstruction}\n\nOUTPUT: A single JSON object on ONE line, no markdown fences:\n{\"label\": \"${page.label}\", \"html\": \"<section class='w-[8.5in] h-[11in] relative overflow-hidden flex flex-col'>...</section>\"}`,\n });\n\n try {\n const result = streamText({\n model: pageModel,\n system: DOCUMENT_SYSTEM_PROMPT + currentDateLine(),\n messages: [{ role: \"user\", content: userContent }],\n });\n\n let buffer = \"\";\n let chunkCount = 0;\n for await (const chunk of result.textStream) {\n buffer += chunk;\n chunkCount++;\n if (chunkCount % 5 === 0) {\n const partial = extractPartialHtml(buffer);\n if (partial) onPageChunk?.(pageIdx, partial);\n }\n }\n\n // Accumulate token usage\n const pageUsage = await result.usage;\n totalInputTokens += pageUsage?.inputTokens || 0;\n totalOutputTokens += pageUsage?.outputTokens || 0;\n\n // Final partial before parse\n const finalPartial = extractPartialHtml(buffer);\n if (finalPartial) onPageChunk?.(pageIdx, finalPartial);\n\n // Parse the JSON object\n let cleaned = buffer.trim();\n if (cleaned.startsWith(\"```\")) {\n cleaned = cleaned.replace(/^```(?:json)?\\s*/, \"\").replace(/\\s*```$/, \"\");\n }\n const [objects] = extractJsonObjects(cleaned);\n const obj = objects[0];\n if (!obj?.html) throw new Error(`No valid HTML output for page ${page.pageNumber}`);\n\n const section: Section3 = {\n id: nanoid(8),\n order: pageIdx,\n html: sanitizeSemanticColors(addSvgLoadingPlaceholders(addLoadingPlaceholders(obj.html))),\n label: obj.label || page.label,\n };\n\n onPageComplete?.(pageIdx, section);\n return section;\n } catch (err) {\n if (retryCount < 1) {\n console.warn(`Page ${page.pageNumber} failed, retrying:`, (err as Error).message);\n return generateSinglePage(page, retryCount + 1);\n }\n // Return error placeholder\n const section: Section3 = {\n id: nanoid(8),\n order: pageIdx,\n html: `<section class=\"w-[8.5in] h-[11in] relative overflow-hidden flex flex-col bg-gray-50 items-center justify-center\"><div class=\"text-center text-gray-400\"><p class=\"text-lg font-semibold\">Error generando página</p><p class=\"text-sm mt-2\">${(err as Error).message?.slice(0, 100) || \"Error desconocido\"}</p></div></section>`,\n label: page.label,\n };\n onPageComplete?.(pageIdx, section);\n return section;\n }\n }\n\n const results = await Promise.allSettled(\n outline.pages.map((page) => generateSinglePage(page))\n );\n\n const sections: Section3[] = results\n .map((r) => r.status === \"fulfilled\" ? r.value : null)\n .filter((s): s is Section3 => s !== null)\n .sort((a, b) => a.order - b.order);\n\n // --- Phase 3: Image enrichment (sequential to respect Pexels rate limits) ---\n for (const section of sections) {\n await enrichSectionImages(section, {\n pexelsApiKey,\n openaiApiKey,\n persistImage,\n onImageUpdate,\n });\n await enrichSectionSvgCharts(section, {\n anthropicApiKey,\n onImageUpdate,\n });\n await enrichSectionIconSlots(section, { onImageUpdate });\n }\n\n // Final fallback for images without src\n for (const section of sections) {\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 if (section.html !== before) {\n onImageUpdate?.(section.id, section.html);\n }\n }\n\n onUsage?.({ inputTokens: totalInputTokens, outputTokens: totalOutputTokens });\n onDone?.(sections);\n return sections;\n } catch (err: any) {\n const error = err instanceof Error ? err : new Error(err?.message || \"Parallel generation failed\");\n onError?.(error);\n throw error;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB,kBAAkB;AAC3C,SAAS,SAAS;AAClB,SAAS,cAAc;AAiBhB,IAAM,yBAAyB;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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