prompts.chat 0.0.6 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/variables/index.ts","../src/similarity/index.ts","../src/quality/index.ts","../src/parser/index.ts","../src/builder/media.ts","../src/builder/video.ts","../src/builder/audio.ts","../src/builder/chat.ts","../src/builder/index.ts"],"sourcesContent":["/**\n * Variable Detection Utility\n * Detects common variable-like patterns in text that could be converted\n * to our supported format: ${variableName} or ${variableName:default}\n */\n\nexport interface DetectedVariable {\n original: string;\n name: string;\n defaultValue?: string;\n pattern: VariablePattern;\n startIndex: number;\n endIndex: number;\n}\n\nexport type VariablePattern = \n | \"double_bracket\" // [[name]] or [[ name ]]\n | \"double_curly\" // {{name}} or {{ name }}\n | \"single_bracket\" // [NAME] or [name]\n | \"single_curly\" // {NAME} or {name}\n | \"angle_bracket\" // <NAME> or <name>\n | \"percent\" // %NAME% or %name%\n | \"dollar_curly\"; // ${name} (already our format)\n\ninterface PatternConfig {\n pattern: VariablePattern;\n regex: RegExp;\n extractName: (match: RegExpExecArray) => string;\n extractDefault?: (match: RegExpExecArray) => string | undefined;\n}\n\n// Patterns to detect, ordered by specificity (more specific first)\nconst PATTERNS: PatternConfig[] = [\n // Double bracket: [[name]] or [[ name ]] or [[name: default]]\n {\n pattern: \"double_bracket\",\n regex: /\\[\\[\\s*([a-zA-Z_][a-zA-Z0-9_\\s]*?)(?:\\s*:\\s*([^\\]]*?))?\\s*\\]\\]/g,\n extractName: (m) => m[1].trim(),\n extractDefault: (m) => m[2]?.trim(),\n },\n // Double curly: {{name}} or {{ name }} or {{name: default}}\n {\n pattern: \"double_curly\",\n regex: /\\{\\{\\s*([a-zA-Z_][a-zA-Z0-9_\\s]*?)(?:\\s*:\\s*([^}]*?))?\\s*\\}\\}/g,\n extractName: (m) => m[1].trim(),\n extractDefault: (m) => m[2]?.trim(),\n },\n // Our supported format (to exclude from warnings)\n {\n pattern: \"dollar_curly\",\n regex: /\\$\\{([a-zA-Z_][a-zA-Z0-9_\\s]*?)(?::([^}]*))?\\}/g,\n extractName: (m) => m[1].trim(),\n },\n // Single bracket with uppercase or placeholder-like: [NAME] or [Your Name]\n {\n pattern: \"single_bracket\",\n regex: /\\[([A-Z][A-Z0-9_\\s]*|[A-Za-z][a-zA-Z0-9_]*(?:\\s+[A-Za-z][a-zA-Z0-9_]*)*)\\]/g,\n extractName: (m) => m[1].trim(),\n },\n // Single curly with uppercase: {NAME} or {Your Name}\n {\n pattern: \"single_curly\",\n regex: /\\{([A-Z][A-Z0-9_\\s]*|[A-Za-z][a-zA-Z0-9_]*(?:\\s+[A-Za-z][a-zA-Z0-9_]*)*)\\}/g,\n extractName: (m) => m[1].trim(),\n },\n // Angle brackets: <NAME> or <name>\n {\n pattern: \"angle_bracket\",\n regex: /<([A-Z][A-Z0-9_\\s]*|[a-zA-Z_][a-zA-Z0-9_\\s]*)>/g,\n extractName: (m) => m[1].trim(),\n },\n // Percent signs: %NAME% or %name%\n {\n pattern: \"percent\",\n regex: /%([a-zA-Z_][a-zA-Z0-9_]*)%/g,\n extractName: (m) => m[1].trim(),\n },\n];\n\n// Common false positives to ignore\nconst FALSE_POSITIVES = new Set([\n // HTML/XML common tags\n \"div\", \"span\", \"p\", \"a\", \"br\", \"hr\", \"img\", \"input\", \"button\",\n \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\", \"ul\", \"ol\", \"li\", \"table\",\n \"tr\", \"td\", \"th\", \"thead\", \"tbody\", \"form\", \"label\", \"select\",\n \"option\", \"textarea\", \"script\", \"style\", \"link\", \"meta\", \"head\",\n \"body\", \"html\", \"section\", \"article\", \"nav\", \"header\", \"footer\",\n \"main\", \"aside\", \"figure\", \"figcaption\", \"strong\", \"em\", \"code\",\n \"pre\", \"blockquote\", \"cite\", \"abbr\", \"address\", \"b\", \"i\", \"u\",\n // Common programming constructs\n \"if\", \"else\", \"for\", \"while\", \"switch\", \"case\", \"break\", \"return\",\n \"function\", \"class\", \"const\", \"let\", \"var\", \"import\", \"export\",\n \"default\", \"try\", \"catch\", \"finally\", \"throw\", \"new\", \"this\",\n \"null\", \"undefined\", \"true\", \"false\", \"typeof\", \"instanceof\",\n // JSON structure keywords (when in context)\n \"type\", \"id\", \"key\", \"value\", \"data\", \"items\", \"properties\",\n]);\n\n/**\n * Check if we're inside a JSON string context\n */\nfunction isInsideJsonString(text: string, index: number): boolean {\n let inString = false;\n for (let i = 0; i < index; i++) {\n if (text[i] === '\"' && (i === 0 || text[i - 1] !== '\\\\')) {\n inString = !inString;\n }\n }\n return inString;\n}\n\n/**\n * Detect variable-like patterns in text\n * Returns detected variables that are NOT in our supported format\n */\nexport function detectVariables(text: string): DetectedVariable[] {\n const detected: DetectedVariable[] = [];\n const seenRanges: Array<[number, number]> = [];\n \n // Track our supported format positions to exclude them\n const supportedVars = new Set<string>();\n const dollarCurlyPattern = /\\$\\{([a-zA-Z_][a-zA-Z0-9_\\s]*?)(?::([^}]*))?\\}/g;\n let match: RegExpExecArray | null;\n \n while ((match = dollarCurlyPattern.exec(text)) !== null) {\n seenRanges.push([match.index, match.index + match[0].length]);\n supportedVars.add(match[0]);\n }\n \n // Check each pattern\n for (const config of PATTERNS) {\n // Skip our supported format pattern for detection\n if (config.pattern === \"dollar_curly\") continue;\n \n const regex = new RegExp(config.regex.source, config.regex.flags);\n \n while ((match = regex.exec(text)) !== null) {\n const startIndex = match.index;\n const endIndex = startIndex + match[0].length;\n \n // Check if this range overlaps with any already detected range\n const overlaps = seenRanges.some(\n ([start, end]) => \n (startIndex >= start && startIndex < end) ||\n (endIndex > start && endIndex <= end)\n );\n \n if (overlaps) continue;\n \n const name = config.extractName(match);\n \n // Skip false positives\n if (FALSE_POSITIVES.has(name.toLowerCase())) continue;\n \n // Skip very short names (likely not variables)\n if (name.length < 2) continue;\n \n // For angle brackets, be more strict\n if (config.pattern === \"angle_bracket\") {\n if (!/^[A-Z]/.test(name) && !name.includes(\" \")) continue;\n }\n \n // For single curly/bracket in JSON context, be more careful\n if (\n (config.pattern === \"single_curly\" || config.pattern === \"single_bracket\") &&\n isInsideJsonString(text, startIndex)\n ) {\n if (!/^[A-Z]/.test(name) && !name.includes(\" \")) continue;\n }\n \n const defaultValue = config.extractDefault?.(match);\n \n detected.push({\n original: match[0],\n name,\n defaultValue,\n pattern: config.pattern,\n startIndex,\n endIndex,\n });\n \n seenRanges.push([startIndex, endIndex]);\n }\n }\n \n // Sort by position and remove duplicates\n return detected\n .sort((a, b) => a.startIndex - b.startIndex)\n .filter((v, i, arr) => \n i === 0 || v.original !== arr[i - 1].original || v.startIndex !== arr[i - 1].startIndex\n );\n}\n\n/**\n * Convert a detected variable to our supported format\n */\nexport function convertToSupportedFormat(variable: DetectedVariable): string {\n // Normalize name: lowercase, replace spaces with underscores\n const normalizedName = variable.name\n .toLowerCase()\n .replace(/\\s+/g, \"_\")\n .replace(/[^a-z0-9_]/g, \"\");\n \n if (variable.defaultValue) {\n return `\\${${normalizedName}:${variable.defaultValue}}`;\n }\n \n return `\\${${normalizedName}}`;\n}\n\n/**\n * Convert all detected variables in text to our supported format\n */\nexport function convertAllVariables(text: string): string {\n const detected = detectVariables(text);\n \n if (detected.length === 0) return text;\n \n // Sort by position descending to replace from end to start\n const sorted = [...detected].sort((a, b) => b.startIndex - a.startIndex);\n \n let result = text;\n for (const variable of sorted) {\n const converted = convertToSupportedFormat(variable);\n result = result.slice(0, variable.startIndex) + converted + result.slice(variable.endIndex);\n }\n \n return result;\n}\n\n/**\n * Alias for convertAllVariables - normalizes all variable formats to ${var}\n */\nexport const normalize = convertAllVariables;\n\n/**\n * Alias for detectVariables\n */\nexport const detect = detectVariables;\n\n/**\n * Get a human-readable pattern description\n */\nexport function getPatternDescription(pattern: VariablePattern): string {\n switch (pattern) {\n case \"double_bracket\": return \"[[...]]\";\n case \"double_curly\": return \"{{...}}\";\n case \"single_bracket\": return \"[...]\";\n case \"single_curly\": return \"{...}\";\n case \"angle_bracket\": return \"<...>\";\n case \"percent\": return \"%...%\";\n case \"dollar_curly\": return \"${...}\";\n }\n}\n\n/**\n * Extract variables from our supported ${var} or ${var:default} format\n */\nexport function extractVariables(text: string): Array<{ name: string; defaultValue?: string }> {\n const regex = /\\$\\{([a-zA-Z_][a-zA-Z0-9_\\s]*?)(?::([^}]*))?\\}/g;\n const variables: Array<{ name: string; defaultValue?: string }> = [];\n let match: RegExpExecArray | null;\n \n while ((match = regex.exec(text)) !== null) {\n variables.push({\n name: match[1].trim(),\n defaultValue: match[2]?.trim(),\n });\n }\n \n return variables;\n}\n\n/**\n * Compile a prompt template with variable values\n */\nexport function compile(\n template: string, \n values: Record<string, string>,\n options: { useDefaults?: boolean } = {}\n): string {\n const { useDefaults = true } = options;\n \n return template.replace(\n /\\$\\{([a-zA-Z_][a-zA-Z0-9_\\s]*?)(?::([^}]*))?\\}/g,\n (match, name, defaultValue) => {\n const trimmedName = name.trim();\n if (trimmedName in values) {\n return values[trimmedName];\n }\n if (useDefaults && defaultValue !== undefined) {\n return defaultValue.trim();\n }\n return match; // Keep original if no value and no default\n }\n );\n}\n","/**\n * Content similarity utilities for duplicate detection\n */\n\n/**\n * Normalize content for comparison by:\n * - Removing variables (${...} patterns)\n * - Converting to lowercase\n * - Removing extra whitespace\n * - Removing punctuation\n */\nexport function normalizeContent(content: string): string {\n return content\n // Remove variables like ${variable} or ${variable:default}\n .replace(/\\$\\{[^}]+\\}/g, \"\")\n // Remove common placeholder patterns like [placeholder] or <placeholder>\n .replace(/\\[[^\\]]+\\]/g, \"\")\n .replace(/<[^>]+>/g, \"\")\n // Convert to lowercase\n .toLowerCase()\n // Remove punctuation\n .replace(/[^\\w\\s]/g, \"\")\n // Normalize whitespace\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\n/**\n * Calculate Jaccard similarity between two strings\n * Returns a value between 0 (completely different) and 1 (identical)\n */\nfunction jaccardSimilarity(str1: string, str2: string): number {\n const set1 = new Set(str1.split(\" \").filter(Boolean));\n const set2 = new Set(str2.split(\" \").filter(Boolean));\n \n if (set1.size === 0 && set2.size === 0) return 1;\n if (set1.size === 0 || set2.size === 0) return 0;\n \n const intersection = new Set([...set1].filter(x => set2.has(x)));\n const union = new Set([...set1, ...set2]);\n \n return intersection.size / union.size;\n}\n\n/**\n * Calculate n-gram similarity for better sequence matching\n * Uses trigrams (3-character sequences) by default\n */\nfunction ngramSimilarity(str1: string, str2: string, n: number = 3): number {\n const getNgrams = (str: string): Set<string> => {\n const ngrams = new Set<string>();\n const padded = \" \".repeat(n - 1) + str + \" \".repeat(n - 1);\n for (let i = 0; i <= padded.length - n; i++) {\n ngrams.add(padded.slice(i, i + n));\n }\n return ngrams;\n };\n \n const ngrams1 = getNgrams(str1);\n const ngrams2 = getNgrams(str2);\n \n if (ngrams1.size === 0 && ngrams2.size === 0) return 1;\n if (ngrams1.size === 0 || ngrams2.size === 0) return 0;\n \n const intersection = new Set([...ngrams1].filter(x => ngrams2.has(x)));\n const union = new Set([...ngrams1, ...ngrams2]);\n \n return intersection.size / union.size;\n}\n\n/**\n * Combined similarity score using multiple algorithms\n * Returns a value between 0 (completely different) and 1 (identical)\n */\nexport function calculateSimilarity(content1: string, content2: string): number {\n const normalized1 = normalizeContent(content1);\n const normalized2 = normalizeContent(content2);\n \n // Exact match after normalization\n if (normalized1 === normalized2) return 1;\n \n // Empty content edge case\n if (!normalized1 || !normalized2) return 0;\n \n // Combine Jaccard (word-level) and n-gram (character-level) similarities\n const jaccard = jaccardSimilarity(normalized1, normalized2);\n const ngram = ngramSimilarity(normalized1, normalized2);\n \n // Weighted average: 60% Jaccard (word overlap), 40% n-gram (sequence similarity)\n return jaccard * 0.6 + ngram * 0.4;\n}\n\n/**\n * Alias for calculateSimilarity\n */\nexport const calculate = calculateSimilarity;\n\n/**\n * Check if two contents are similar enough to be considered duplicates\n * Default threshold is 0.85 (85% similar)\n */\nexport function isSimilarContent(\n content1: string, \n content2: string, \n threshold: number = 0.85\n): boolean {\n return calculateSimilarity(content1, content2) >= threshold;\n}\n\n/**\n * Alias for isSimilarContent\n */\nexport const isDuplicate = isSimilarContent;\n\n/**\n * Get normalized content hash for database indexing/comparison\n * This is a simple hash for quick lookups before full similarity check\n */\nexport function getContentFingerprint(content: string): string {\n const normalized = normalizeContent(content);\n // Take first 500 chars of normalized content as fingerprint\n return normalized.slice(0, 500);\n}\n\n/**\n * Find duplicates in an array of prompts\n * Returns groups of similar prompts\n */\nexport function findDuplicates<T extends { content: string }>(\n prompts: T[],\n threshold: number = 0.85\n): T[][] {\n const groups: T[][] = [];\n const used = new Set<number>();\n\n for (let i = 0; i < prompts.length; i++) {\n if (used.has(i)) continue;\n\n const group: T[] = [prompts[i]];\n used.add(i);\n\n for (let j = i + 1; j < prompts.length; j++) {\n if (used.has(j)) continue;\n\n if (isSimilarContent(prompts[i].content, prompts[j].content, threshold)) {\n group.push(prompts[j]);\n used.add(j);\n }\n }\n\n if (group.length > 1) {\n groups.push(group);\n }\n }\n\n return groups;\n}\n\n/**\n * Deduplicate an array of prompts, keeping the first occurrence\n */\nexport function deduplicate<T extends { content: string }>(\n prompts: T[],\n threshold: number = 0.85\n): T[] {\n const result: T[] = [];\n\n for (const prompt of prompts) {\n const isDupe = result.some(existing => \n isSimilarContent(existing.content, prompt.content, threshold)\n );\n\n if (!isDupe) {\n result.push(prompt);\n }\n }\n\n return result;\n}\n","/**\n * Prompt Quality Checker - Local validation for prompt quality\n * \n * @example\n * ```ts\n * import { quality } from 'prompts.chat';\n * \n * const result = quality.check(\"Act as a developer...\");\n * console.log(result.score); // 0.85\n * console.log(result.issues); // []\n * ```\n */\n\nexport interface QualityIssue {\n type: 'error' | 'warning' | 'suggestion';\n code: string;\n message: string;\n position?: { start: number; end: number };\n}\n\nexport interface QualityResult {\n valid: boolean;\n score: number; // 0-1\n issues: QualityIssue[];\n stats: {\n characterCount: number;\n wordCount: number;\n sentenceCount: number;\n variableCount: number;\n hasRole: boolean;\n hasTask: boolean;\n hasConstraints: boolean;\n hasExamples: boolean;\n };\n}\n\n// Minimum thresholds\nconst MIN_CHAR_COUNT = 20;\nconst MIN_WORD_COUNT = 5;\nconst OPTIMAL_MIN_WORDS = 20;\nconst OPTIMAL_MAX_WORDS = 2000;\n\n/**\n * Check if text looks like gibberish\n */\nfunction isGibberish(text: string): boolean {\n // Check for repeated characters\n if (/(.)\\1{4,}/.test(text)) return true;\n \n // Check for keyboard patterns\n const keyboardPatterns = ['qwerty', 'asdfgh', 'zxcvbn', 'qwertz', 'azerty'];\n const lower = text.toLowerCase();\n if (keyboardPatterns.some(p => lower.includes(p))) return true;\n \n // Check consonant/vowel ratio (gibberish often has unusual ratios)\n const vowels = (text.match(/[aeiouAEIOU]/g) || []).length;\n const consonants = (text.match(/[bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]/g) || []).length;\n \n if (consonants > 0 && vowels / consonants < 0.1) return true;\n \n return false;\n}\n\n/**\n * Detect common prompt patterns\n */\nfunction detectPatterns(text: string): {\n hasRole: boolean;\n hasTask: boolean;\n hasConstraints: boolean;\n hasExamples: boolean;\n} {\n const lower = text.toLowerCase();\n \n return {\n hasRole: /\\b(act as|you are|imagine you|pretend to be|role:|persona:)\\b/i.test(text),\n hasTask: /\\b(your task|you (will|should|must)|please|help me|i need|i want you to)\\b/i.test(text),\n hasConstraints: /\\b(do not|don't|never|always|must|should not|avoid|only|limit)\\b/i.test(text) ||\n /\\b(rule|constraint|requirement|guideline)\\b/i.test(lower),\n hasExamples: /\\b(example|for instance|such as|e\\.g\\.|like this)\\b/i.test(lower) ||\n /```[\\s\\S]*```/.test(text),\n };\n}\n\n/**\n * Count variables in the prompt\n */\nfunction countVariables(text: string): number {\n // Match various variable formats\n const patterns = [\n /\\$\\{[^}]+\\}/g, // ${var}\n /\\{\\{[^}]+\\}\\}/g, // {{var}}\n /\\[\\[[^\\]]+\\]\\]/g, // [[var]]\n /\\[[A-Z][A-Z0-9_\\s]*\\]/g, // [VAR]\n ];\n \n let count = 0;\n for (const pattern of patterns) {\n const matches = text.match(pattern);\n if (matches) count += matches.length;\n }\n \n return count;\n}\n\n/**\n * Calculate quality score based on various factors\n */\nfunction calculateScore(\n stats: QualityResult['stats'],\n issues: QualityIssue[]\n): number {\n let score = 1.0;\n \n // Deduct for errors\n const errors = issues.filter(i => i.type === 'error').length;\n const warnings = issues.filter(i => i.type === 'warning').length;\n \n score -= errors * 0.2;\n score -= warnings * 0.05;\n \n // Bonus for good structure\n if (stats.hasRole) score += 0.05;\n if (stats.hasTask) score += 0.05;\n if (stats.hasConstraints) score += 0.03;\n if (stats.hasExamples) score += 0.05;\n \n // Penalty for being too short\n if (stats.wordCount < OPTIMAL_MIN_WORDS) {\n score -= 0.1 * (1 - stats.wordCount / OPTIMAL_MIN_WORDS);\n }\n \n // Slight penalty for being very long\n if (stats.wordCount > OPTIMAL_MAX_WORDS) {\n score -= 0.05;\n }\n \n // Bonus for having variables (indicates reusability)\n if (stats.variableCount > 0) {\n score += 0.05;\n }\n \n return Math.max(0, Math.min(1, score));\n}\n\n/**\n * Check prompt quality locally (no API needed)\n */\nexport function check(prompt: string): QualityResult {\n const issues: QualityIssue[] = [];\n const trimmed = prompt.trim();\n \n // Basic stats\n const characterCount = trimmed.length;\n const words = trimmed.split(/\\s+/).filter(w => w.length > 0);\n const wordCount = words.length;\n const sentenceCount = (trimmed.match(/[.!?]+/g) || []).length || 1;\n const variableCount = countVariables(trimmed);\n const patterns = detectPatterns(trimmed);\n \n // Check for empty or too short\n if (characterCount === 0) {\n issues.push({\n type: 'error',\n code: 'EMPTY',\n message: 'Prompt is empty',\n });\n } else if (characterCount < MIN_CHAR_COUNT) {\n issues.push({\n type: 'error',\n code: 'TOO_SHORT',\n message: `Prompt is too short (${characterCount} chars, minimum ${MIN_CHAR_COUNT})`,\n });\n }\n \n if (wordCount > 0 && wordCount < MIN_WORD_COUNT) {\n issues.push({\n type: 'warning',\n code: 'FEW_WORDS',\n message: `Prompt has very few words (${wordCount} words, recommended ${OPTIMAL_MIN_WORDS}+)`,\n });\n }\n \n // Check for gibberish\n if (isGibberish(trimmed)) {\n issues.push({\n type: 'error',\n code: 'GIBBERISH',\n message: 'Prompt appears to contain gibberish or random characters',\n });\n }\n \n // Check for common issues\n if (!patterns.hasTask && !patterns.hasRole) {\n issues.push({\n type: 'suggestion',\n code: 'NO_CLEAR_INSTRUCTION',\n message: 'Consider adding a clear task or role definition',\n });\n }\n \n // Check for unbalanced brackets/quotes\n const brackets = [\n { open: '{', close: '}' },\n { open: '[', close: ']' },\n { open: '(', close: ')' },\n ];\n \n for (const { open, close } of brackets) {\n const openCount = (trimmed.match(new RegExp(`\\\\${open}`, 'g')) || []).length;\n const closeCount = (trimmed.match(new RegExp(`\\\\${close}`, 'g')) || []).length;\n \n if (openCount !== closeCount) {\n issues.push({\n type: 'warning',\n code: 'UNBALANCED_BRACKETS',\n message: `Unbalanced ${open}${close} brackets (${openCount} open, ${closeCount} close)`,\n });\n }\n }\n \n // Check for very long lines (readability)\n const lines = trimmed.split('\\n');\n const longLines = lines.filter(l => l.length > 500);\n if (longLines.length > 0) {\n issues.push({\n type: 'suggestion',\n code: 'LONG_LINES',\n message: 'Some lines are very long. Consider breaking them up for readability.',\n });\n }\n \n const stats = {\n characterCount,\n wordCount,\n sentenceCount,\n variableCount,\n ...patterns,\n };\n \n const score = calculateScore(stats, issues);\n const hasErrors = issues.some(i => i.type === 'error');\n \n return {\n valid: !hasErrors,\n score,\n issues,\n stats,\n };\n}\n\n/**\n * Validate a prompt and throw if invalid\n */\nexport function validate(prompt: string): void {\n const result = check(prompt);\n \n if (!result.valid) {\n const errors = result.issues\n .filter(i => i.type === 'error')\n .map(i => i.message)\n .join('; ');\n \n throw new Error(`Invalid prompt: ${errors}`);\n }\n}\n\n/**\n * Check if a prompt is valid\n */\nexport function isValid(prompt: string): boolean {\n return check(prompt).valid;\n}\n\n/**\n * Get suggestions for improving a prompt\n */\nexport function getSuggestions(prompt: string): string[] {\n const result = check(prompt);\n const suggestions: string[] = [];\n \n // From issues\n suggestions.push(\n ...result.issues\n .filter(i => i.type === 'suggestion' || i.type === 'warning')\n .map(i => i.message)\n );\n \n // Additional suggestions based on stats\n if (!result.stats.hasRole) {\n suggestions.push('Add a role definition (e.g., \"Act as a...\")');\n }\n \n if (!result.stats.hasConstraints && result.stats.wordCount > 50) {\n suggestions.push('Consider adding constraints or rules for better control');\n }\n \n if (!result.stats.hasExamples && result.stats.wordCount > 100) {\n suggestions.push('Adding examples can improve output quality');\n }\n \n if (result.stats.variableCount === 0 && result.stats.wordCount > 30) {\n suggestions.push('Consider adding variables (${var}) to make the prompt reusable');\n }\n \n return suggestions;\n}\n","/**\n * Prompt Parser - Parse and load prompt files in various formats\n * \n * Supports:\n * - .prompt.yml / .prompt.yaml (YAML format)\n * - .prompt.json (JSON format)\n * - .prompt.md (Markdown with frontmatter)\n * - .txt (Plain text)\n * \n * @example\n * ```ts\n * import { parser } from 'prompts.chat';\n * \n * const prompt = parser.parse(`\n * name: Code Review\n * messages:\n * - role: system\n * content: You are a code reviewer.\n * `);\n * ```\n */\n\nexport interface PromptMessage {\n role: 'system' | 'user' | 'assistant';\n content: string;\n}\n\nexport interface ParsedPrompt {\n name?: string;\n description?: string;\n model?: string;\n modelParameters?: {\n temperature?: number;\n maxTokens?: number;\n topP?: number;\n frequencyPenalty?: number;\n presencePenalty?: number;\n };\n messages: PromptMessage[];\n variables?: Record<string, {\n description?: string;\n default?: string;\n required?: boolean;\n }>;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Parse YAML content\n * Note: This is a simple YAML parser for common prompt file structures\n * For full YAML support, the consuming project should use a proper YAML library\n */\nfunction parseSimpleYaml(content: string): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n const lines = content.split('\\n');\n \n let currentKey: string | null = null;\n let currentValue: unknown = null;\n let inArray = false;\n let inMultiline = false;\n let multilineContent = '';\n let arrayItems: unknown[] = [];\n let indent = 0;\n \n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const trimmed = line.trim();\n \n // Skip empty lines and comments\n if (!trimmed || trimmed.startsWith('#')) {\n if (inMultiline) {\n multilineContent += '\\n';\n }\n continue;\n }\n \n // Handle multiline content (|)\n if (inMultiline) {\n const lineIndent = line.search(/\\S/);\n if (lineIndent > indent) {\n multilineContent += (multilineContent ? '\\n' : '') + line.slice(indent + 2);\n continue;\n } else {\n // End of multiline\n if (inArray && currentKey) {\n const lastItem = arrayItems[arrayItems.length - 1] as Record<string, unknown>;\n if (lastItem && typeof lastItem === 'object') {\n const keys = Object.keys(lastItem);\n const lastKey = keys[keys.length - 1];\n lastItem[lastKey] = multilineContent.trim();\n }\n } else if (currentKey) {\n result[currentKey] = multilineContent.trim();\n }\n inMultiline = false;\n multilineContent = '';\n }\n }\n \n // Handle array items\n if (trimmed.startsWith('- ')) {\n if (!inArray && currentKey) {\n inArray = true;\n arrayItems = [];\n }\n \n const itemContent = trimmed.slice(2);\n \n // Check if it's a key-value pair\n const kvMatch = itemContent.match(/^(\\w+):\\s*(.*)$/);\n if (kvMatch) {\n const obj: Record<string, unknown> = {};\n obj[kvMatch[1]] = kvMatch[2] === '|' ? '' : (kvMatch[2] || '');\n \n if (kvMatch[2] === '|') {\n inMultiline = true;\n indent = line.search(/\\S/);\n multilineContent = '';\n }\n \n arrayItems.push(obj);\n } else {\n arrayItems.push(itemContent);\n }\n continue;\n }\n \n // Handle nested object properties in arrays\n if (inArray && line.startsWith(' ')) {\n const propMatch = trimmed.match(/^(\\w+):\\s*(.*)$/);\n if (propMatch && arrayItems.length > 0) {\n const lastItem = arrayItems[arrayItems.length - 1];\n if (typeof lastItem === 'object' && lastItem !== null) {\n (lastItem as Record<string, unknown>)[propMatch[1]] = \n propMatch[2] === '|' ? '' : (propMatch[2] || '');\n \n if (propMatch[2] === '|') {\n inMultiline = true;\n indent = line.search(/\\S/);\n multilineContent = '';\n }\n }\n }\n continue;\n }\n \n // End array if we're back to root level\n if (inArray && !line.startsWith(' ') && !line.startsWith('\\t')) {\n if (currentKey) {\n result[currentKey] = arrayItems;\n }\n inArray = false;\n arrayItems = [];\n }\n \n // Handle key-value pairs\n const match = trimmed.match(/^(\\w+):\\s*(.*)$/);\n if (match) {\n currentKey = match[1];\n const value = match[2];\n \n if (value === '' || value === '|' || value === '>') {\n // Multiline or nested content\n if (value === '|' || value === '>') {\n inMultiline = true;\n indent = line.search(/\\S/);\n multilineContent = '';\n }\n } else if (value.startsWith('\"') && value.endsWith('\"')) {\n result[currentKey] = value.slice(1, -1);\n } else if (value.startsWith(\"'\") && value.endsWith(\"'\")) {\n result[currentKey] = value.slice(1, -1);\n } else if (value === 'true') {\n result[currentKey] = true;\n } else if (value === 'false') {\n result[currentKey] = false;\n } else if (!isNaN(Number(value))) {\n result[currentKey] = Number(value);\n } else {\n result[currentKey] = value;\n }\n }\n }\n \n // Handle remaining array\n if (inArray && currentKey) {\n result[currentKey] = arrayItems;\n }\n \n // Handle remaining multiline\n if (inMultiline && currentKey) {\n result[currentKey] = multilineContent.trim();\n }\n \n return result;\n}\n\n/**\n * Parse JSON content\n */\nfunction parseJson(content: string): Record<string, unknown> {\n return JSON.parse(content);\n}\n\n/**\n * Parse Markdown with frontmatter\n */\nfunction parseMarkdown(content: string): Record<string, unknown> {\n const frontmatterMatch = content.match(/^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/);\n \n if (frontmatterMatch) {\n const frontmatter = parseSimpleYaml(frontmatterMatch[1]);\n const body = frontmatterMatch[2].trim();\n \n return {\n ...frontmatter,\n messages: [{ role: 'system', content: body }],\n };\n }\n \n // No frontmatter, treat entire content as system message\n return {\n messages: [{ role: 'system', content: content.trim() }],\n };\n}\n\n/**\n * Normalize parsed data to ParsedPrompt format\n */\nfunction normalize(data: Record<string, unknown>): ParsedPrompt {\n const messages: PromptMessage[] = [];\n \n // Handle messages array\n if (Array.isArray(data.messages)) {\n for (const msg of data.messages) {\n if (typeof msg === 'object' && msg !== null) {\n const m = msg as Record<string, unknown>;\n messages.push({\n role: (m.role as PromptMessage['role']) || 'user',\n content: String(m.content || ''),\n });\n }\n }\n }\n \n // Handle single content field\n if (messages.length === 0 && typeof data.content === 'string') {\n messages.push({ role: 'system', content: data.content });\n }\n \n // Handle prompt field (alias for content)\n if (messages.length === 0 && typeof data.prompt === 'string') {\n messages.push({ role: 'system', content: data.prompt });\n }\n \n return {\n name: data.name as string | undefined,\n description: data.description as string | undefined,\n model: data.model as string | undefined,\n modelParameters: data.modelParameters as ParsedPrompt['modelParameters'],\n messages,\n variables: data.variables as ParsedPrompt['variables'],\n metadata: data.metadata as Record<string, unknown>,\n };\n}\n\n/**\n * Parse prompt content in various formats\n */\nexport function parse(content: string, format?: 'yaml' | 'json' | 'markdown' | 'text'): ParsedPrompt {\n const trimmed = content.trim();\n \n // Auto-detect format if not specified\n if (!format) {\n if (trimmed.startsWith('{')) {\n format = 'json';\n } else if (trimmed.startsWith('---')) {\n format = 'markdown';\n } else if (trimmed.includes(':') && (trimmed.includes('\\n ') || trimmed.includes('\\n-'))) {\n format = 'yaml';\n } else {\n format = 'text';\n }\n }\n \n let data: Record<string, unknown>;\n \n switch (format) {\n case 'json':\n data = parseJson(trimmed);\n break;\n case 'yaml':\n data = parseSimpleYaml(trimmed);\n break;\n case 'markdown':\n data = parseMarkdown(trimmed);\n break;\n case 'text':\n default:\n data = { messages: [{ role: 'system', content: trimmed }] };\n break;\n }\n \n return normalize(data);\n}\n\n/**\n * Serialize a ParsedPrompt to YAML format\n */\nexport function toYaml(prompt: ParsedPrompt): string {\n const lines: string[] = [];\n \n if (prompt.name) {\n lines.push(`name: ${prompt.name}`);\n }\n \n if (prompt.description) {\n lines.push(`description: ${prompt.description}`);\n }\n \n if (prompt.model) {\n lines.push(`model: ${prompt.model}`);\n }\n \n if (prompt.modelParameters) {\n lines.push('modelParameters:');\n for (const [key, value] of Object.entries(prompt.modelParameters)) {\n if (value !== undefined) {\n lines.push(` ${key}: ${value}`);\n }\n }\n }\n \n if (prompt.messages.length > 0) {\n lines.push('messages:');\n for (const msg of prompt.messages) {\n lines.push(` - role: ${msg.role}`);\n if (msg.content.includes('\\n')) {\n lines.push(' content: |');\n for (const line of msg.content.split('\\n')) {\n lines.push(` ${line}`);\n }\n } else {\n lines.push(` content: \"${msg.content.replace(/\"/g, '\\\\\"')}\"`);\n }\n }\n }\n \n return lines.join('\\n');\n}\n\n/**\n * Serialize a ParsedPrompt to JSON format\n */\nexport function toJson(prompt: ParsedPrompt, pretty: boolean = true): string {\n return JSON.stringify(prompt, null, pretty ? 2 : 0);\n}\n\n/**\n * Get the system message content from a parsed prompt\n */\nexport function getSystemPrompt(prompt: ParsedPrompt): string {\n const systemMessage = prompt.messages.find(m => m.role === 'system');\n return systemMessage?.content || '';\n}\n\n/**\n * Interpolate variables in a prompt\n */\nexport function interpolate(\n prompt: ParsedPrompt,\n values: Record<string, string>\n): ParsedPrompt {\n const interpolateString = (str: string): string => {\n return str.replace(/\\{\\{(\\w+)\\}\\}/g, (match, key) => {\n if (key in values) return values[key];\n if (prompt.variables?.[key]?.default) return prompt.variables[key].default!;\n return match;\n });\n };\n \n return {\n ...prompt,\n messages: prompt.messages.map(msg => ({\n ...msg,\n content: interpolateString(msg.content),\n })),\n };\n}\n","/**\n * Media Prompt Builders - The D3.js of Prompt Building\n * \n * Comprehensive, structured builders for Image, Video, and Audio generation prompts.\n * Every attribute a professional would consider is available as a chainable method.\n * \n * @example\n * ```ts\n * import { image, video, audio } from 'prompts.chat/builder';\n * \n * const imagePrompt = image()\n * .subject(\"a lone samurai\")\n * .environment(\"bamboo forest at dawn\")\n * .camera({ angle: \"low\", shot: \"wide\", lens: \"35mm\" })\n * .lighting({ type: \"rim\", time: \"golden-hour\" })\n * .style({ artist: \"Akira Kurosawa\", medium: \"cinematic\" })\n * .build();\n * ```\n */\n\n// ============================================================================\n// TYPES & INTERFACES\n// ============================================================================\n\nexport type OutputFormat = 'text' | 'json' | 'yaml' | 'markdown';\n\n// --- Camera Brands & Models ---\nexport type CameraBrand = \n | 'sony' | 'canon' | 'nikon' | 'fujifilm' | 'leica' | 'hasselblad' | 'phase-one'\n | 'panasonic' | 'olympus' | 'pentax' | 'red' | 'arri' | 'blackmagic' | 'panavision';\n\nexport type CameraModel = \n // Sony\n | 'sony-a7iv' | 'sony-a7riv' | 'sony-a7siii' | 'sony-a1' | 'sony-fx3' | 'sony-fx6'\n | 'sony-venice' | 'sony-venice-2' | 'sony-a9ii' | 'sony-zv-e1'\n // Canon\n | 'canon-r5' | 'canon-r6' | 'canon-r3' | 'canon-r8' | 'canon-c70' | 'canon-c300-iii'\n | 'canon-c500-ii' | 'canon-5d-iv' | 'canon-1dx-iii' | 'canon-eos-r5c'\n // Nikon\n | 'nikon-z9' | 'nikon-z8' | 'nikon-z6-iii' | 'nikon-z7-ii' | 'nikon-d850' | 'nikon-d6'\n // Fujifilm\n | 'fujifilm-x-t5' | 'fujifilm-x-h2s' | 'fujifilm-x100vi' | 'fujifilm-gfx100s'\n | 'fujifilm-gfx100-ii' | 'fujifilm-x-pro3'\n // Leica\n | 'leica-m11' | 'leica-sl2' | 'leica-sl2-s' | 'leica-q3' | 'leica-m10-r'\n // Hasselblad\n | 'hasselblad-x2d' | 'hasselblad-907x' | 'hasselblad-h6d-100c'\n // Cinema Cameras\n | 'arri-alexa-35' | 'arri-alexa-mini-lf' | 'arri-alexa-65' | 'arri-amira'\n | 'red-v-raptor' | 'red-komodo' | 'red-gemini' | 'red-monstro'\n | 'blackmagic-ursa-mini-pro' | 'blackmagic-pocket-6k' | 'blackmagic-pocket-4k'\n | 'panavision-dxl2' | 'panavision-millennium-xl2';\n\nexport type SensorFormat = \n | 'full-frame' | 'aps-c' | 'micro-four-thirds' | 'medium-format' | 'large-format'\n | 'super-35' | 'vista-vision' | 'imax' | '65mm' | '35mm-film' | '16mm-film' | '8mm-film';\n\nexport type FilmFormat = \n | '35mm' | '120-medium-format' | '4x5-large-format' | '8x10-large-format'\n | '110-film' | 'instant-film' | 'super-8' | '16mm' | '65mm-imax';\n\n// --- Camera & Shot Types ---\nexport type CameraAngle = \n | 'eye-level' | 'low-angle' | 'high-angle' | 'dutch-angle' | 'birds-eye' \n | 'worms-eye' | 'over-the-shoulder' | 'point-of-view' | 'aerial' | 'drone'\n | 'canted' | 'oblique' | 'hip-level' | 'knee-level' | 'ground-level';\n\nexport type ShotType = \n | 'extreme-close-up' | 'close-up' | 'medium-close-up' | 'medium' | 'medium-wide'\n | 'wide' | 'extreme-wide' | 'establishing' | 'full-body' | 'portrait' | 'headshot';\n\nexport type LensType = \n | 'wide-angle' | 'ultra-wide' | 'standard' | 'telephoto' | 'macro' | 'fisheye'\n | '14mm' | '24mm' | '35mm' | '50mm' | '85mm' | '100mm' | '135mm' | '200mm' | '400mm'\n | '600mm' | '800mm' | 'tilt-shift' | 'anamorphic' | 'spherical' | 'prime' | 'zoom';\n\nexport type LensBrand = \n | 'zeiss' | 'leica' | 'canon' | 'nikon' | 'sony' | 'sigma' | 'tamron' | 'voigtlander'\n | 'fujifilm' | 'samyang' | 'rokinon' | 'tokina' | 'cooke' | 'arri' | 'panavision'\n | 'angenieux' | 'red' | 'atlas' | 'sirui';\n\nexport type LensModel = \n // Zeiss\n | 'zeiss-otus-55' | 'zeiss-batis-85' | 'zeiss-milvus-35' | 'zeiss-supreme-prime'\n // Leica\n | 'leica-summilux-50' | 'leica-summicron-35' | 'leica-noctilux-50' | 'leica-apo-summicron'\n // Canon\n | 'canon-rf-50-1.2' | 'canon-rf-85-1.2' | 'canon-rf-28-70-f2' | 'canon-rf-100-500'\n // Sony\n | 'sony-gm-24-70' | 'sony-gm-70-200' | 'sony-gm-50-1.2' | 'sony-gm-85-1.4'\n // Sigma Art\n | 'sigma-art-35' | 'sigma-art-50' | 'sigma-art-85' | 'sigma-art-105-macro'\n // Cinema\n | 'cooke-s7i' | 'cooke-anamorphic' | 'arri-signature-prime' | 'arri-ultra-prime'\n | 'panavision-primo' | 'panavision-anamorphic' | 'atlas-orion-anamorphic'\n // Vintage\n | 'helios-44-2' | 'canon-fd-55' | 'minolta-rokkor-58' | 'pentax-takumar-50';\n\nexport type FocusType = \n | 'shallow' | 'deep' | 'soft-focus' | 'tilt-shift' | 'rack-focus' | 'split-diopter'\n | 'zone-focus' | 'hyperfocal' | 'selective' | 'bokeh-heavy' | 'tack-sharp';\n\nexport type BokehStyle = \n | 'smooth' | 'creamy' | 'swirly' | 'busy' | 'soap-bubble' | 'cat-eye' | 'oval-anamorphic';\n\nexport type FilterType = \n | 'uv' | 'polarizer' | 'nd' | 'nd-graduated' | 'black-pro-mist' | 'white-pro-mist'\n | 'glimmer-glass' | 'classic-soft' | 'streak' | 'starburst' | 'diffusion'\n | 'infrared' | 'color-gel' | 'warming' | 'cooling' | 'vintage-look';\n\nexport type CameraMovement = \n | 'static' | 'pan' | 'tilt' | 'dolly' | 'truck' | 'pedestal' | 'zoom' \n | 'handheld' | 'steadicam' | 'crane' | 'drone' | 'tracking' | 'arc' | 'whip-pan'\n | 'roll' | 'boom' | 'jib' | 'cable-cam' | 'motion-control' | 'snorricam'\n | 'dutch-roll' | 'vertigo-effect' | 'crash-zoom' | 'slow-push' | 'slow-pull';\n\nexport type CameraRig = \n | 'tripod' | 'monopod' | 'gimbal' | 'steadicam' | 'easyrig' | 'shoulder-rig'\n | 'slider' | 'dolly' | 'jib' | 'crane' | 'technocrane' | 'russian-arm'\n | 'cable-cam' | 'drone' | 'fpv-drone' | 'motion-control' | 'handheld';\n\nexport type GimbalModel = \n | 'dji-ronin-4d' | 'dji-ronin-rs3-pro' | 'dji-ronin-rs4' | 'moza-air-2'\n | 'zhiyun-crane-3s' | 'freefly-movi-pro' | 'tilta-gravity-g2x';\n\n// --- Lighting Types ---\nexport type LightingType = \n | 'natural' | 'studio' | 'dramatic' | 'soft' | 'hard' | 'diffused'\n | 'key' | 'fill' | 'rim' | 'backlit' | 'silhouette' | 'rembrandt'\n | 'split' | 'butterfly' | 'loop' | 'broad' | 'short' | 'chiaroscuro'\n | 'high-key' | 'low-key' | 'three-point' | 'practical' | 'motivated';\n\nexport type TimeOfDay = \n | 'dawn' | 'sunrise' | 'golden-hour' | 'morning' | 'midday' | 'afternoon'\n | 'blue-hour' | 'sunset' | 'dusk' | 'twilight' | 'night' | 'midnight';\n\nexport type WeatherLighting = \n | 'sunny' | 'cloudy' | 'overcast' | 'foggy' | 'misty' | 'rainy' \n | 'stormy' | 'snowy' | 'hazy';\n\n// --- Style Types ---\nexport type ArtStyle = \n | 'photorealistic' | 'hyperrealistic' | 'cinematic' | 'documentary'\n | 'editorial' | 'fashion' | 'portrait' | 'landscape' | 'street'\n | 'fine-art' | 'conceptual' | 'surreal' | 'abstract' | 'minimalist'\n | 'maximalist' | 'vintage' | 'retro' | 'noir' | 'gothic' | 'romantic'\n | 'impressionist' | 'expressionist' | 'pop-art' | 'art-nouveau' | 'art-deco'\n | 'cyberpunk' | 'steampunk' | 'fantasy' | 'sci-fi' | 'anime' | 'manga'\n | 'comic-book' | 'illustration' | 'digital-art' | 'oil-painting' | 'watercolor'\n | 'sketch' | 'pencil-drawing' | 'charcoal' | 'pastel' | '3d-render';\n\nexport type FilmStock = \n // Kodak Color Negative\n | 'kodak-portra-160' | 'kodak-portra-400' | 'kodak-portra-800' \n | 'kodak-ektar-100' | 'kodak-gold-200' | 'kodak-ultramax-400' | 'kodak-colorplus-200'\n // Kodak Black & White\n | 'kodak-tri-x-400' | 'kodak-tmax-100' | 'kodak-tmax-400' | 'kodak-tmax-3200'\n // Kodak Slide\n | 'kodak-ektachrome-e100' | 'kodachrome-64' | 'kodachrome-200'\n // Kodak Cinema\n | 'kodak-vision3-50d' | 'kodak-vision3-200t' | 'kodak-vision3-250d' | 'kodak-vision3-500t'\n // Fujifilm\n | 'fujifilm-pro-400h' | 'fujifilm-superia-400' | 'fujifilm-c200'\n | 'fujifilm-velvia-50' | 'fujifilm-velvia-100' | 'fujifilm-provia-100f'\n | 'fujifilm-acros-100' | 'fujifilm-neopan-400' | 'fujifilm-eterna-500t'\n // Ilford\n | 'ilford-hp5-plus' | 'ilford-delta-100' | 'ilford-delta-400' | 'ilford-delta-3200'\n | 'ilford-fp4-plus' | 'ilford-pan-f-plus' | 'ilford-xp2-super'\n // CineStill\n | 'cinestill-50d' | 'cinestill-800t' | 'cinestill-400d' | 'cinestill-bwxx'\n // Lomography\n | 'lomography-100' | 'lomography-400' | 'lomography-800'\n | 'lomochrome-purple' | 'lomochrome-metropolis' | 'lomochrome-turquoise'\n // Instant\n | 'polaroid-sx-70' | 'polaroid-600' | 'polaroid-i-type' | 'polaroid-spectra'\n | 'instax-mini' | 'instax-wide' | 'instax-square'\n // Vintage/Discontinued\n | 'agfa-vista-400' | 'agfa-apx-100' | 'fomapan-100' | 'fomapan-400'\n | 'bergger-pancro-400' | 'jch-streetpan-400';\n\nexport type AspectRatio = \n | '1:1' | '4:3' | '3:2' | '16:9' | '21:9' | '9:16' | '2:3' | '4:5' | '5:4';\n\n// --- Color & Mood ---\nexport type ColorPalette = \n | 'warm' | 'cool' | 'neutral' | 'vibrant' | 'muted' | 'pastel' | 'neon'\n | 'monochrome' | 'sepia' | 'desaturated' | 'high-contrast' | 'low-contrast'\n | 'earthy' | 'oceanic' | 'forest' | 'sunset' | 'midnight' | 'golden';\n\nexport type Mood = \n | 'serene' | 'peaceful' | 'melancholic' | 'dramatic' | 'tense' | 'mysterious'\n | 'romantic' | 'nostalgic' | 'hopeful' | 'joyful' | 'energetic' | 'chaotic'\n | 'ethereal' | 'dark' | 'light' | 'whimsical' | 'eerie' | 'epic' | 'intimate';\n\n// --- Video Specific ---\nexport type VideoTransition = \n | 'cut' | 'fade' | 'dissolve' | 'wipe' | 'morph' | 'match-cut' | 'jump-cut'\n | 'cross-dissolve' | 'iris' | 'push' | 'slide';\n\nexport type VideoPacing = \n | 'slow' | 'medium' | 'fast' | 'variable' | 'building' | 'frenetic' | 'contemplative';\n\n// --- Audio/Music Specific ---\nexport type MusicGenre = \n | 'pop' | 'rock' | 'jazz' | 'classical' | 'electronic' | 'hip-hop' | 'r&b'\n | 'country' | 'folk' | 'blues' | 'metal' | 'punk' | 'indie' | 'alternative'\n | 'ambient' | 'lo-fi' | 'synthwave' | 'orchestral' | 'cinematic' | 'world'\n | 'latin' | 'reggae' | 'soul' | 'funk' | 'disco' | 'house' | 'techno' | 'edm';\n\nexport type Instrument = \n | 'piano' | 'guitar' | 'acoustic-guitar' | 'electric-guitar' | 'bass' | 'drums'\n | 'violin' | 'cello' | 'viola' | 'flute' | 'saxophone' | 'trumpet' | 'trombone'\n | 'synthesizer' | 'organ' | 'harp' | 'percussion' | 'strings' | 'brass' | 'woodwinds'\n | 'choir' | 'vocals' | 'beatbox' | 'turntables' | 'harmonica' | 'banjo' | 'ukulele';\n\nexport type VocalStyle = \n | 'male' | 'female' | 'duet' | 'choir' | 'a-cappella' | 'spoken-word' | 'rap'\n | 'falsetto' | 'belting' | 'whisper' | 'growl' | 'melodic' | 'harmonized';\n\nexport type Tempo = \n | 'largo' | 'adagio' | 'andante' | 'moderato' | 'allegro' | 'vivace' | 'presto'\n | number; // BPM\n\n// ============================================================================\n// IMAGE PROMPT BUILDER\n// ============================================================================\n\nexport interface ImageSubject {\n main: string;\n details?: string[];\n expression?: string;\n pose?: string;\n action?: string;\n clothing?: string;\n accessories?: string[];\n age?: string;\n ethnicity?: string;\n gender?: string;\n count?: number | 'single' | 'couple' | 'group' | 'crowd';\n}\n\nexport interface ImageCamera {\n // Framing\n angle?: CameraAngle;\n shot?: ShotType;\n \n // Camera Body\n brand?: CameraBrand;\n model?: CameraModel;\n sensor?: SensorFormat;\n \n // Lens\n lens?: LensType;\n lensModel?: LensModel;\n lensBrand?: LensBrand;\n focalLength?: string;\n \n // Focus & Depth\n focus?: FocusType;\n aperture?: string;\n bokeh?: BokehStyle;\n focusDistance?: string;\n \n // Exposure\n iso?: number;\n shutterSpeed?: string;\n exposureCompensation?: string;\n \n // Film/Digital\n filmStock?: FilmStock;\n filmFormat?: FilmFormat;\n \n // Filters & Accessories\n filter?: FilterType | FilterType[];\n \n // Camera Settings\n whiteBalance?: 'daylight' | 'cloudy' | 'tungsten' | 'fluorescent' | 'flash' | 'custom';\n colorProfile?: string;\n pictureProfile?: string;\n}\n\nexport interface ImageLighting {\n type?: LightingType | LightingType[];\n time?: TimeOfDay;\n weather?: WeatherLighting;\n direction?: 'front' | 'side' | 'back' | 'top' | 'bottom' | 'three-quarter';\n intensity?: 'soft' | 'medium' | 'hard' | 'dramatic';\n color?: string;\n sources?: string[];\n}\n\nexport interface ImageComposition {\n ruleOfThirds?: boolean;\n goldenRatio?: boolean;\n symmetry?: 'none' | 'horizontal' | 'vertical' | 'radial';\n leadingLines?: boolean;\n framing?: string;\n negativeSpace?: boolean;\n layers?: string[];\n foreground?: string;\n midground?: string;\n background?: string;\n}\n\nexport interface ImageStyle {\n medium?: ArtStyle | ArtStyle[];\n artist?: string | string[];\n era?: string;\n influence?: string[];\n quality?: string[];\n render?: string;\n}\n\nexport interface ImageColor {\n palette?: ColorPalette | ColorPalette[];\n primary?: string[];\n accent?: string[];\n grade?: string;\n temperature?: 'warm' | 'neutral' | 'cool';\n saturation?: 'desaturated' | 'natural' | 'vibrant' | 'hyper-saturated';\n contrast?: 'low' | 'medium' | 'high';\n}\n\nexport interface ImageEnvironment {\n setting: string;\n location?: string;\n terrain?: string;\n architecture?: string;\n props?: string[];\n atmosphere?: string;\n season?: 'spring' | 'summer' | 'autumn' | 'winter';\n era?: string;\n}\n\nexport interface ImageTechnical {\n aspectRatio?: AspectRatio;\n resolution?: string;\n quality?: 'draft' | 'standard' | 'high' | 'ultra' | 'masterpiece';\n detail?: 'low' | 'medium' | 'high' | 'extreme';\n noise?: 'none' | 'subtle' | 'filmic' | 'grainy';\n sharpness?: 'soft' | 'natural' | 'sharp' | 'crisp';\n}\n\nexport interface BuiltImagePrompt {\n prompt: string;\n structure: {\n subject?: ImageSubject;\n camera?: ImageCamera;\n lighting?: ImageLighting;\n composition?: ImageComposition;\n style?: ImageStyle;\n color?: ImageColor;\n environment?: ImageEnvironment;\n technical?: ImageTechnical;\n mood?: Mood | Mood[];\n negative?: string[];\n };\n}\n\nexport class ImagePromptBuilder {\n private _subject?: ImageSubject;\n private _camera?: ImageCamera;\n private _lighting?: ImageLighting;\n private _composition?: ImageComposition;\n private _style?: ImageStyle;\n private _color?: ImageColor;\n private _environment?: ImageEnvironment;\n private _technical?: ImageTechnical;\n private _mood?: Mood | Mood[];\n private _negative: string[] = [];\n private _custom: string[] = [];\n\n // --- Subject Methods ---\n \n subject(main: string | ImageSubject): this {\n if (typeof main === 'string') {\n this._subject = { ...(this._subject || {}), main };\n } else {\n this._subject = { ...(this._subject || {}), ...main };\n }\n return this;\n }\n\n subjectDetails(details: string[]): this {\n this._subject = { ...(this._subject || { main: '' }), details };\n return this;\n }\n\n expression(expression: string): this {\n this._subject = { ...(this._subject || { main: '' }), expression };\n return this;\n }\n\n pose(pose: string): this {\n this._subject = { ...(this._subject || { main: '' }), pose };\n return this;\n }\n\n action(action: string): this {\n this._subject = { ...(this._subject || { main: '' }), action };\n return this;\n }\n\n clothing(clothing: string): this {\n this._subject = { ...(this._subject || { main: '' }), clothing };\n return this;\n }\n\n accessories(accessories: string[]): this {\n this._subject = { ...(this._subject || { main: '' }), accessories };\n return this;\n }\n\n subjectCount(count: ImageSubject['count']): this {\n this._subject = { ...(this._subject || { main: '' }), count };\n return this;\n }\n\n // --- Camera Methods ---\n\n camera(settings: ImageCamera): this {\n this._camera = { ...(this._camera || {}), ...settings };\n return this;\n }\n\n angle(angle: CameraAngle): this {\n this._camera = { ...(this._camera || {}), angle };\n return this;\n }\n\n shot(shot: ShotType): this {\n this._camera = { ...(this._camera || {}), shot };\n return this;\n }\n\n lens(lens: LensType): this {\n this._camera = { ...(this._camera || {}), lens };\n return this;\n }\n\n focus(focus: FocusType): this {\n this._camera = { ...(this._camera || {}), focus };\n return this;\n }\n\n aperture(aperture: string): this {\n this._camera = { ...(this._camera || {}), aperture };\n return this;\n }\n\n filmStock(filmStock: FilmStock): this {\n this._camera = { ...(this._camera || {}), filmStock };\n return this;\n }\n\n filmFormat(format: FilmFormat): this {\n this._camera = { ...(this._camera || {}), filmFormat: format };\n return this;\n }\n\n cameraBrand(brand: CameraBrand): this {\n this._camera = { ...(this._camera || {}), brand };\n return this;\n }\n\n cameraModel(model: CameraModel): this {\n this._camera = { ...(this._camera || {}), model };\n return this;\n }\n\n sensor(sensor: SensorFormat): this {\n this._camera = { ...(this._camera || {}), sensor };\n return this;\n }\n\n lensModel(model: LensModel): this {\n this._camera = { ...(this._camera || {}), lensModel: model };\n return this;\n }\n\n lensBrand(brand: LensBrand): this {\n this._camera = { ...(this._camera || {}), lensBrand: brand };\n return this;\n }\n\n focalLength(length: string): this {\n this._camera = { ...(this._camera || {}), focalLength: length };\n return this;\n }\n\n bokeh(style: BokehStyle): this {\n this._camera = { ...(this._camera || {}), bokeh: style };\n return this;\n }\n\n filter(filter: FilterType | FilterType[]): this {\n this._camera = { ...(this._camera || {}), filter };\n return this;\n }\n\n iso(iso: number): this {\n this._camera = { ...(this._camera || {}), iso };\n return this;\n }\n\n shutterSpeed(speed: string): this {\n this._camera = { ...(this._camera || {}), shutterSpeed: speed };\n return this;\n }\n\n whiteBalance(wb: ImageCamera['whiteBalance']): this {\n this._camera = { ...(this._camera || {}), whiteBalance: wb };\n return this;\n }\n\n colorProfile(profile: string): this {\n this._camera = { ...(this._camera || {}), colorProfile: profile };\n return this;\n }\n\n // --- Lighting Methods ---\n\n lighting(settings: ImageLighting): this {\n this._lighting = { ...(this._lighting || {}), ...settings };\n return this;\n }\n\n lightingType(type: LightingType | LightingType[]): this {\n this._lighting = { ...(this._lighting || {}), type };\n return this;\n }\n\n timeOfDay(time: TimeOfDay): this {\n this._lighting = { ...(this._lighting || {}), time };\n return this;\n }\n\n weather(weather: WeatherLighting): this {\n this._lighting = { ...(this._lighting || {}), weather };\n return this;\n }\n\n lightDirection(direction: ImageLighting['direction']): this {\n this._lighting = { ...(this._lighting || {}), direction };\n return this;\n }\n\n lightIntensity(intensity: ImageLighting['intensity']): this {\n this._lighting = { ...(this._lighting || {}), intensity };\n return this;\n }\n\n // --- Composition Methods ---\n\n composition(settings: ImageComposition): this {\n this._composition = { ...(this._composition || {}), ...settings };\n return this;\n }\n\n ruleOfThirds(): this {\n this._composition = { ...(this._composition || {}), ruleOfThirds: true };\n return this;\n }\n\n goldenRatio(): this {\n this._composition = { ...(this._composition || {}), goldenRatio: true };\n return this;\n }\n\n symmetry(type: ImageComposition['symmetry']): this {\n this._composition = { ...(this._composition || {}), symmetry: type };\n return this;\n }\n\n foreground(fg: string): this {\n this._composition = { ...(this._composition || {}), foreground: fg };\n return this;\n }\n\n midground(mg: string): this {\n this._composition = { ...(this._composition || {}), midground: mg };\n return this;\n }\n\n background(bg: string): this {\n this._composition = { ...(this._composition || {}), background: bg };\n return this;\n }\n\n // --- Environment Methods ---\n\n environment(setting: string | ImageEnvironment): this {\n if (typeof setting === 'string') {\n this._environment = { ...(this._environment || { setting: '' }), setting };\n } else {\n this._environment = { ...(this._environment || { setting: '' }), ...setting };\n }\n return this;\n }\n\n location(location: string): this {\n this._environment = { ...(this._environment || { setting: '' }), location };\n return this;\n }\n\n props(props: string[]): this {\n this._environment = { ...(this._environment || { setting: '' }), props };\n return this;\n }\n\n atmosphere(atmosphere: string): this {\n this._environment = { ...(this._environment || { setting: '' }), atmosphere };\n return this;\n }\n\n season(season: ImageEnvironment['season']): this {\n this._environment = { ...(this._environment || { setting: '' }), season };\n return this;\n }\n\n // --- Style Methods ---\n\n style(settings: ImageStyle): this {\n this._style = { ...(this._style || {}), ...settings };\n return this;\n }\n\n medium(medium: ArtStyle | ArtStyle[]): this {\n this._style = { ...(this._style || {}), medium };\n return this;\n }\n\n artist(artist: string | string[]): this {\n this._style = { ...(this._style || {}), artist };\n return this;\n }\n\n influence(influences: string[]): this {\n this._style = { ...(this._style || {}), influence: influences };\n return this;\n }\n\n // --- Color Methods ---\n\n color(settings: ImageColor): this {\n this._color = { ...(this._color || {}), ...settings };\n return this;\n }\n\n palette(palette: ColorPalette | ColorPalette[]): this {\n this._color = { ...(this._color || {}), palette };\n return this;\n }\n\n primaryColors(colors: string[]): this {\n this._color = { ...(this._color || {}), primary: colors };\n return this;\n }\n\n accentColors(colors: string[]): this {\n this._color = { ...(this._color || {}), accent: colors };\n return this;\n }\n\n colorGrade(grade: string): this {\n this._color = { ...(this._color || {}), grade };\n return this;\n }\n\n // --- Technical Methods ---\n\n technical(settings: ImageTechnical): this {\n this._technical = { ...(this._technical || {}), ...settings };\n return this;\n }\n\n aspectRatio(ratio: AspectRatio): this {\n this._technical = { ...(this._technical || {}), aspectRatio: ratio };\n return this;\n }\n\n resolution(resolution: string): this {\n this._technical = { ...(this._technical || {}), resolution };\n return this;\n }\n\n quality(quality: ImageTechnical['quality']): this {\n this._technical = { ...(this._technical || {}), quality };\n return this;\n }\n\n // --- Mood & Misc ---\n\n mood(mood: Mood | Mood[]): this {\n this._mood = mood;\n return this;\n }\n\n negative(items: string[]): this {\n this._negative = [...this._negative, ...items];\n return this;\n }\n\n custom(text: string): this {\n this._custom.push(text);\n return this;\n }\n\n // --- Build Methods ---\n\n private buildPromptText(): string {\n const parts: string[] = [];\n\n // Subject\n if (this._subject) {\n let subjectText = this._subject.main;\n if (this._subject.count && this._subject.count !== 'single') {\n subjectText = `${this._subject.count} ${subjectText}`;\n }\n if (this._subject.expression) subjectText += `, ${this._subject.expression} expression`;\n if (this._subject.pose) subjectText += `, ${this._subject.pose}`;\n if (this._subject.action) subjectText += `, ${this._subject.action}`;\n if (this._subject.clothing) subjectText += `, wearing ${this._subject.clothing}`;\n if (this._subject.accessories?.length) subjectText += `, with ${this._subject.accessories.join(', ')}`;\n if (this._subject.details?.length) subjectText += `, ${this._subject.details.join(', ')}`;\n parts.push(subjectText);\n }\n\n // Environment\n if (this._environment) {\n let envText = this._environment.setting;\n if (this._environment.location) envText += ` in ${this._environment.location}`;\n if (this._environment.atmosphere) envText += `, ${this._environment.atmosphere} atmosphere`;\n if (this._environment.season) envText += `, ${this._environment.season}`;\n if (this._environment.props?.length) envText += `, with ${this._environment.props.join(', ')}`;\n parts.push(envText);\n }\n\n // Composition\n if (this._composition) {\n const compParts: string[] = [];\n if (this._composition.foreground) compParts.push(`foreground: ${this._composition.foreground}`);\n if (this._composition.midground) compParts.push(`midground: ${this._composition.midground}`);\n if (this._composition.background) compParts.push(`background: ${this._composition.background}`);\n if (this._composition.ruleOfThirds) compParts.push('rule of thirds composition');\n if (this._composition.goldenRatio) compParts.push('golden ratio composition');\n if (this._composition.symmetry && this._composition.symmetry !== 'none') {\n compParts.push(`${this._composition.symmetry} symmetry`);\n }\n if (compParts.length) parts.push(compParts.join(', '));\n }\n\n // Camera\n if (this._camera) {\n const camParts: string[] = [];\n if (this._camera.shot) camParts.push(`${this._camera.shot} shot`);\n if (this._camera.angle) camParts.push(`${this._camera.angle}`);\n if (this._camera.lens) camParts.push(`${this._camera.lens} lens`);\n if (this._camera.focus) camParts.push(`${this._camera.focus} depth of field`);\n if (this._camera.aperture) camParts.push(`f/${this._camera.aperture}`);\n if (this._camera.filmStock) camParts.push(`shot on ${this._camera.filmStock}`);\n if (this._camera.brand) camParts.push(`${this._camera.brand}`);\n if (camParts.length) parts.push(camParts.join(', '));\n }\n\n // Lighting\n if (this._lighting) {\n const lightParts: string[] = [];\n if (this._lighting.type) {\n const types = Array.isArray(this._lighting.type) ? this._lighting.type : [this._lighting.type];\n lightParts.push(`${types.join(' and ')} lighting`);\n }\n if (this._lighting.time) lightParts.push(this._lighting.time);\n if (this._lighting.weather) lightParts.push(`${this._lighting.weather} weather`);\n if (this._lighting.direction) lightParts.push(`light from ${this._lighting.direction}`);\n if (this._lighting.intensity) lightParts.push(`${this._lighting.intensity} light`);\n if (lightParts.length) parts.push(lightParts.join(', '));\n }\n\n // Style\n if (this._style) {\n const styleParts: string[] = [];\n if (this._style.medium) {\n const mediums = Array.isArray(this._style.medium) ? this._style.medium : [this._style.medium];\n styleParts.push(mediums.join(', '));\n }\n if (this._style.artist) {\n const artists = Array.isArray(this._style.artist) ? this._style.artist : [this._style.artist];\n styleParts.push(`in the style of ${artists.join(' and ')}`);\n }\n if (this._style.era) styleParts.push(this._style.era);\n if (this._style.influence?.length) styleParts.push(`influenced by ${this._style.influence.join(', ')}`);\n if (this._style.quality?.length) styleParts.push(this._style.quality.join(', '));\n if (styleParts.length) parts.push(styleParts.join(', '));\n }\n\n // Color\n if (this._color) {\n const colorParts: string[] = [];\n if (this._color.palette) {\n const palettes = Array.isArray(this._color.palette) ? this._color.palette : [this._color.palette];\n colorParts.push(`${palettes.join(' and ')} color palette`);\n }\n if (this._color.primary?.length) colorParts.push(`primary colors: ${this._color.primary.join(', ')}`);\n if (this._color.accent?.length) colorParts.push(`accent colors: ${this._color.accent.join(', ')}`);\n if (this._color.grade) colorParts.push(`${this._color.grade} color grade`);\n if (this._color.temperature) colorParts.push(`${this._color.temperature} tones`);\n if (colorParts.length) parts.push(colorParts.join(', '));\n }\n\n // Mood\n if (this._mood) {\n const moods = Array.isArray(this._mood) ? this._mood : [this._mood];\n parts.push(`${moods.join(', ')} mood`);\n }\n\n // Technical\n if (this._technical) {\n const techParts: string[] = [];\n if (this._technical.quality) techParts.push(`${this._technical.quality} quality`);\n if (this._technical.detail) techParts.push(`${this._technical.detail} detail`);\n if (this._technical.resolution) techParts.push(this._technical.resolution);\n if (techParts.length) parts.push(techParts.join(', '));\n }\n\n // Custom\n if (this._custom.length) {\n parts.push(this._custom.join(', '));\n }\n\n let prompt = parts.join(', ');\n\n // Negative prompts\n if (this._negative.length) {\n prompt += ` --no ${this._negative.join(', ')}`;\n }\n\n // Aspect ratio\n if (this._technical?.aspectRatio) {\n prompt += ` --ar ${this._technical.aspectRatio}`;\n }\n\n return prompt;\n }\n\n build(): BuiltImagePrompt {\n return {\n prompt: this.buildPromptText(),\n structure: {\n subject: this._subject,\n camera: this._camera,\n lighting: this._lighting,\n composition: this._composition,\n style: this._style,\n color: this._color,\n environment: this._environment,\n technical: this._technical,\n mood: this._mood,\n negative: this._negative.length ? this._negative : undefined,\n },\n };\n }\n\n toString(): string {\n return this.build().prompt;\n }\n\n toJSON(): string {\n return JSON.stringify(this.build().structure, null, 2);\n }\n\n toYAML(): string {\n return objectToYaml(this.build().structure);\n }\n\n toMarkdown(): string {\n const built = this.build();\n const sections: string[] = ['# Image Prompt\\n'];\n \n sections.push('## Prompt\\n```\\n' + built.prompt + '\\n```\\n');\n \n if (built.structure.subject) {\n sections.push('## Subject\\n' + objectToMarkdownList(built.structure.subject));\n }\n if (built.structure.environment) {\n sections.push('## Environment\\n' + objectToMarkdownList(built.structure.environment));\n }\n if (built.structure.camera) {\n sections.push('## Camera\\n' + objectToMarkdownList(built.structure.camera));\n }\n if (built.structure.lighting) {\n sections.push('## Lighting\\n' + objectToMarkdownList(built.structure.lighting));\n }\n if (built.structure.composition) {\n sections.push('## Composition\\n' + objectToMarkdownList(built.structure.composition));\n }\n if (built.structure.style) {\n sections.push('## Style\\n' + objectToMarkdownList(built.structure.style));\n }\n if (built.structure.color) {\n sections.push('## Color\\n' + objectToMarkdownList(built.structure.color));\n }\n if (built.structure.technical) {\n sections.push('## Technical\\n' + objectToMarkdownList(built.structure.technical));\n }\n \n return sections.join('\\n');\n }\n\n format(fmt: OutputFormat): string {\n switch (fmt) {\n case 'json': return this.toJSON();\n case 'yaml': return this.toYAML();\n case 'markdown': return this.toMarkdown();\n default: return this.toString();\n }\n }\n}\n\n// ============================================================================\n// HELPER FUNCTIONS\n// ============================================================================\n\nfunction objectToYaml(obj: object, indent = 0): string {\n const spaces = ' '.repeat(indent);\n const lines: string[] = [];\n \n for (const [key, value] of Object.entries(obj)) {\n if (value === undefined || value === null) continue;\n \n if (Array.isArray(value)) {\n if (value.length === 0) continue;\n lines.push(`${spaces}${key}:`);\n for (const item of value) {\n if (typeof item === 'object') {\n lines.push(`${spaces} -`);\n lines.push(objectToYaml(item as Record<string, unknown>, indent + 2).replace(/^/gm, ' '));\n } else {\n lines.push(`${spaces} - ${item}`);\n }\n }\n } else if (typeof value === 'object') {\n lines.push(`${spaces}${key}:`);\n lines.push(objectToYaml(value as Record<string, unknown>, indent + 1));\n } else {\n lines.push(`${spaces}${key}: ${value}`);\n }\n }\n \n return lines.join('\\n');\n}\n\nfunction objectToMarkdownList(obj: object, indent = 0): string {\n const spaces = ' '.repeat(indent);\n const lines: string[] = [];\n \n for (const [key, value] of Object.entries(obj)) {\n if (value === undefined || value === null) continue;\n \n if (Array.isArray(value)) {\n lines.push(`${spaces}- **${key}:** ${value.join(', ')}`);\n } else if (typeof value === 'object') {\n lines.push(`${spaces}- **${key}:**`);\n lines.push(objectToMarkdownList(value as Record<string, unknown>, indent + 1));\n } else {\n lines.push(`${spaces}- **${key}:** ${value}`);\n }\n }\n \n return lines.join('\\n');\n}\n\n// ============================================================================\n// FACTORY FUNCTIONS\n// ============================================================================\n\n/**\n * Create a new image prompt builder\n */\nexport function image(): ImagePromptBuilder {\n return new ImagePromptBuilder();\n}\n","/**\n * Video Prompt Builder - Comprehensive video generation prompt builder\n * \n * Based on OpenAI Sora, Runway, and other video generation best practices.\n * \n * @example\n * ```ts\n * import { video } from 'prompts.chat/builder';\n * \n * const prompt = video()\n * .scene(\"A samurai walks through a bamboo forest\")\n * .camera({ movement: \"tracking\", angle: \"low\" })\n * .lighting({ time: \"golden-hour\", type: \"natural\" })\n * .duration(5)\n * .build();\n * ```\n */\n\nimport type {\n CameraAngle, ShotType, LensType, CameraMovement,\n LightingType, TimeOfDay, WeatherLighting,\n ArtStyle, ColorPalette, Mood, VideoTransition, VideoPacing,\n OutputFormat, CameraBrand, CameraModel, SensorFormat,\n LensBrand, LensModel, CameraRig, GimbalModel, FilterType,\n FilmStock, BokehStyle,\n} from './media';\n\n// ============================================================================\n// VIDEO-SPECIFIC TYPES\n// ============================================================================\n\nexport interface VideoScene {\n description: string;\n setting?: string;\n timeOfDay?: TimeOfDay;\n weather?: WeatherLighting;\n atmosphere?: string;\n}\n\nexport interface VideoSubject {\n main: string;\n appearance?: string;\n clothing?: string;\n age?: string;\n gender?: string;\n count?: number | 'single' | 'couple' | 'group' | 'crowd';\n}\n\nexport interface VideoCamera {\n // Framing\n shot?: ShotType;\n angle?: CameraAngle;\n \n // Camera Body\n brand?: CameraBrand;\n model?: CameraModel;\n sensor?: SensorFormat;\n \n // Lens\n lens?: LensType;\n lensModel?: LensModel;\n lensBrand?: LensBrand;\n focalLength?: string;\n anamorphic?: boolean;\n anamorphicRatio?: '1.33x' | '1.5x' | '1.8x' | '2x';\n \n // Focus\n focus?: 'shallow' | 'deep' | 'rack-focus' | 'pull-focus' | 'split-diopter';\n aperture?: string;\n bokeh?: BokehStyle;\n \n // Movement\n movement?: CameraMovement;\n movementSpeed?: 'slow' | 'medium' | 'fast';\n movementDirection?: 'left' | 'right' | 'forward' | 'backward' | 'up' | 'down' | 'arc-left' | 'arc-right';\n \n // Rig & Stabilization\n rig?: CameraRig;\n gimbal?: GimbalModel;\n platform?: 'handheld' | 'steadicam' | 'tripod' | 'drone' | 'crane' | 'gimbal' | 'slider' | 'dolly' | 'technocrane' | 'russian-arm' | 'fpv-drone';\n \n // Technical\n shutterAngle?: number;\n frameRate?: 24 | 25 | 30 | 48 | 60 | 120 | 240;\n slowMotion?: boolean;\n filter?: FilterType | FilterType[];\n \n // Film Look\n filmStock?: FilmStock;\n filmGrain?: 'none' | 'subtle' | 'moderate' | 'heavy';\n halation?: boolean;\n}\n\nexport interface VideoLighting {\n type?: LightingType | LightingType[];\n time?: TimeOfDay;\n weather?: WeatherLighting;\n direction?: 'front' | 'side' | 'back' | 'top' | 'three-quarter';\n intensity?: 'soft' | 'medium' | 'hard' | 'dramatic';\n sources?: string[];\n color?: string;\n}\n\nexport interface VideoAction {\n beat: number;\n action: string;\n duration?: number;\n timing?: 'start' | 'middle' | 'end';\n}\n\nexport interface VideoMotion {\n subject?: string;\n type?: 'walk' | 'run' | 'gesture' | 'turn' | 'look' | 'reach' | 'sit' | 'stand' | 'custom';\n direction?: 'left' | 'right' | 'forward' | 'backward' | 'up' | 'down';\n speed?: 'slow' | 'normal' | 'fast';\n beats?: string[];\n}\n\nexport interface VideoStyle {\n format?: string;\n era?: string;\n filmStock?: string;\n look?: ArtStyle | ArtStyle[];\n grade?: string;\n reference?: string[];\n}\n\nexport interface VideoColor {\n palette?: ColorPalette | ColorPalette[];\n anchors?: string[];\n temperature?: 'warm' | 'neutral' | 'cool';\n grade?: string;\n}\n\nexport interface VideoAudio {\n diegetic?: string[];\n ambient?: string;\n dialogue?: string;\n music?: string;\n soundEffects?: string[];\n mix?: string;\n}\n\nexport interface VideoTechnical {\n duration?: number;\n resolution?: '480p' | '720p' | '1080p' | '4K';\n fps?: 24 | 30 | 60;\n aspectRatio?: '16:9' | '9:16' | '1:1' | '4:3' | '21:9';\n shutterAngle?: number;\n}\n\nexport interface VideoShot {\n timestamp?: string;\n name?: string;\n camera: VideoCamera;\n action?: string;\n purpose?: string;\n}\n\nexport interface BuiltVideoPrompt {\n prompt: string;\n structure: {\n scene?: VideoScene;\n subject?: VideoSubject;\n camera?: VideoCamera;\n lighting?: VideoLighting;\n actions?: VideoAction[];\n motion?: VideoMotion;\n style?: VideoStyle;\n color?: VideoColor;\n audio?: VideoAudio;\n technical?: VideoTechnical;\n shots?: VideoShot[];\n mood?: Mood | Mood[];\n pacing?: VideoPacing;\n transitions?: VideoTransition[];\n };\n}\n\n// ============================================================================\n// VIDEO PROMPT BUILDER\n// ============================================================================\n\nexport class VideoPromptBuilder {\n private _scene?: VideoScene;\n private _subject?: VideoSubject;\n private _camera?: VideoCamera;\n private _lighting?: VideoLighting;\n private _actions: VideoAction[] = [];\n private _motion?: VideoMotion;\n private _style?: VideoStyle;\n private _color?: VideoColor;\n private _audio?: VideoAudio;\n private _technical?: VideoTechnical;\n private _shots: VideoShot[] = [];\n private _mood?: Mood | Mood[];\n private _pacing?: VideoPacing;\n private _transitions: VideoTransition[] = [];\n private _custom: string[] = [];\n\n // --- Scene Methods ---\n\n scene(description: string | VideoScene): this {\n if (typeof description === 'string') {\n this._scene = { ...(this._scene || { description: '' }), description };\n } else {\n this._scene = { ...(this._scene || { description: '' }), ...description };\n }\n return this;\n }\n\n setting(setting: string): this {\n this._scene = { ...(this._scene || { description: '' }), setting };\n return this;\n }\n\n // --- Subject Methods ---\n\n subject(main: string | VideoSubject): this {\n if (typeof main === 'string') {\n this._subject = { ...(this._subject || { main: '' }), main };\n } else {\n this._subject = { ...(this._subject || { main: '' }), ...main };\n }\n return this;\n }\n\n appearance(appearance: string): this {\n this._subject = { ...(this._subject || { main: '' }), appearance };\n return this;\n }\n\n clothing(clothing: string): this {\n this._subject = { ...(this._subject || { main: '' }), clothing };\n return this;\n }\n\n // --- Camera Methods ---\n\n camera(settings: VideoCamera): this {\n this._camera = { ...(this._camera || {}), ...settings };\n return this;\n }\n\n shot(shot: ShotType): this {\n this._camera = { ...(this._camera || {}), shot };\n return this;\n }\n\n angle(angle: CameraAngle): this {\n this._camera = { ...(this._camera || {}), angle };\n return this;\n }\n\n movement(movement: CameraMovement): this {\n this._camera = { ...(this._camera || {}), movement };\n return this;\n }\n\n lens(lens: LensType): this {\n this._camera = { ...(this._camera || {}), lens };\n return this;\n }\n\n platform(platform: VideoCamera['platform']): this {\n this._camera = { ...(this._camera || {}), platform };\n return this;\n }\n\n cameraSpeed(speed: VideoCamera['movementSpeed']): this {\n this._camera = { ...(this._camera || {}), movementSpeed: speed };\n return this;\n }\n\n movementDirection(direction: VideoCamera['movementDirection']): this {\n this._camera = { ...(this._camera || {}), movementDirection: direction };\n return this;\n }\n\n rig(rig: CameraRig): this {\n this._camera = { ...(this._camera || {}), rig };\n return this;\n }\n\n gimbal(gimbal: GimbalModel): this {\n this._camera = { ...(this._camera || {}), gimbal };\n return this;\n }\n\n cameraBrand(brand: CameraBrand): this {\n this._camera = { ...(this._camera || {}), brand };\n return this;\n }\n\n cameraModel(model: CameraModel): this {\n this._camera = { ...(this._camera || {}), model };\n return this;\n }\n\n sensor(sensor: SensorFormat): this {\n this._camera = { ...(this._camera || {}), sensor };\n return this;\n }\n\n lensModel(model: LensModel): this {\n this._camera = { ...(this._camera || {}), lensModel: model };\n return this;\n }\n\n lensBrand(brand: LensBrand): this {\n this._camera = { ...(this._camera || {}), lensBrand: brand };\n return this;\n }\n\n focalLength(length: string): this {\n this._camera = { ...(this._camera || {}), focalLength: length };\n return this;\n }\n\n anamorphic(ratio?: VideoCamera['anamorphicRatio']): this {\n this._camera = { ...(this._camera || {}), anamorphic: true, anamorphicRatio: ratio };\n return this;\n }\n\n aperture(aperture: string): this {\n this._camera = { ...(this._camera || {}), aperture };\n return this;\n }\n\n frameRate(fps: VideoCamera['frameRate']): this {\n this._camera = { ...(this._camera || {}), frameRate: fps };\n return this;\n }\n\n slowMotion(enabled = true): this {\n this._camera = { ...(this._camera || {}), slowMotion: enabled };\n return this;\n }\n\n shutterAngle(angle: number): this {\n this._camera = { ...(this._camera || {}), shutterAngle: angle };\n return this;\n }\n\n filter(filter: FilterType | FilterType[]): this {\n this._camera = { ...(this._camera || {}), filter };\n return this;\n }\n\n filmStock(stock: FilmStock): this {\n this._camera = { ...(this._camera || {}), filmStock: stock };\n return this;\n }\n\n filmGrain(grain: VideoCamera['filmGrain']): this {\n this._camera = { ...(this._camera || {}), filmGrain: grain };\n return this;\n }\n\n halation(enabled = true): this {\n this._camera = { ...(this._camera || {}), halation: enabled };\n return this;\n }\n\n // --- Lighting Methods ---\n\n lighting(settings: VideoLighting): this {\n this._lighting = { ...(this._lighting || {}), ...settings };\n return this;\n }\n\n lightingType(type: LightingType | LightingType[]): this {\n this._lighting = { ...(this._lighting || {}), type };\n return this;\n }\n\n timeOfDay(time: TimeOfDay): this {\n this._lighting = { ...(this._lighting || {}), time };\n this._scene = { ...(this._scene || { description: '' }), timeOfDay: time };\n return this;\n }\n\n weather(weather: WeatherLighting): this {\n this._lighting = { ...(this._lighting || {}), weather };\n this._scene = { ...(this._scene || { description: '' }), weather };\n return this;\n }\n\n // --- Action & Motion Methods ---\n\n action(action: string, options: Partial<Omit<VideoAction, 'action'>> = {}): this {\n this._actions.push({\n beat: this._actions.length + 1,\n action,\n ...options,\n });\n return this;\n }\n\n actions(actions: string[]): this {\n actions.forEach((a, i) => this._actions.push({ beat: i + 1, action: a }));\n return this;\n }\n\n motion(settings: VideoMotion): this {\n this._motion = { ...(this._motion || {}), ...settings };\n return this;\n }\n\n motionBeats(beats: string[]): this {\n this._motion = { ...(this._motion || {}), beats };\n return this;\n }\n\n // --- Style Methods ---\n\n style(settings: VideoStyle): this {\n this._style = { ...(this._style || {}), ...settings };\n return this;\n }\n\n format(format: string): this {\n this._style = { ...(this._style || {}), format };\n return this;\n }\n\n era(era: string): this {\n this._style = { ...(this._style || {}), era };\n return this;\n }\n\n styleFilmStock(stock: string): this {\n this._style = { ...(this._style || {}), filmStock: stock };\n return this;\n }\n\n look(look: ArtStyle | ArtStyle[]): this {\n this._style = { ...(this._style || {}), look };\n return this;\n }\n\n reference(references: string[]): this {\n this._style = { ...(this._style || {}), reference: references };\n return this;\n }\n\n // --- Color Methods ---\n\n color(settings: VideoColor): this {\n this._color = { ...(this._color || {}), ...settings };\n return this;\n }\n\n palette(palette: ColorPalette | ColorPalette[]): this {\n this._color = { ...(this._color || {}), palette };\n return this;\n }\n\n colorAnchors(anchors: string[]): this {\n this._color = { ...(this._color || {}), anchors };\n return this;\n }\n\n colorGrade(grade: string): this {\n this._color = { ...(this._color || {}), grade };\n return this;\n }\n\n // --- Audio Methods ---\n\n audio(settings: VideoAudio): this {\n this._audio = { ...(this._audio || {}), ...settings };\n return this;\n }\n\n dialogue(dialogue: string): this {\n this._audio = { ...(this._audio || {}), dialogue };\n return this;\n }\n\n ambient(ambient: string): this {\n this._audio = { ...(this._audio || {}), ambient };\n return this;\n }\n\n diegetic(sounds: string[]): this {\n this._audio = { ...(this._audio || {}), diegetic: sounds };\n return this;\n }\n\n soundEffects(effects: string[]): this {\n this._audio = { ...(this._audio || {}), soundEffects: effects };\n return this;\n }\n\n music(music: string): this {\n this._audio = { ...(this._audio || {}), music };\n return this;\n }\n\n // --- Technical Methods ---\n\n technical(settings: VideoTechnical): this {\n this._technical = { ...(this._technical || {}), ...settings };\n return this;\n }\n\n duration(seconds: number): this {\n this._technical = { ...(this._technical || {}), duration: seconds };\n return this;\n }\n\n resolution(res: VideoTechnical['resolution']): this {\n this._technical = { ...(this._technical || {}), resolution: res };\n return this;\n }\n\n fps(fps: VideoTechnical['fps']): this {\n this._technical = { ...(this._technical || {}), fps };\n return this;\n }\n\n aspectRatio(ratio: VideoTechnical['aspectRatio']): this {\n this._technical = { ...(this._technical || {}), aspectRatio: ratio };\n return this;\n }\n\n // --- Shot List Methods ---\n\n addShot(shot: VideoShot): this {\n this._shots.push(shot);\n return this;\n }\n\n shotList(shots: VideoShot[]): this {\n this._shots = [...this._shots, ...shots];\n return this;\n }\n\n // --- Mood & Pacing ---\n\n mood(mood: Mood | Mood[]): this {\n this._mood = mood;\n return this;\n }\n\n pacing(pacing: VideoPacing): this {\n this._pacing = pacing;\n return this;\n }\n\n transition(transition: VideoTransition): this {\n this._transitions.push(transition);\n return this;\n }\n\n transitions(transitions: VideoTransition[]): this {\n this._transitions = [...this._transitions, ...transitions];\n return this;\n }\n\n custom(text: string): this {\n this._custom.push(text);\n return this;\n }\n\n // --- Build Methods ---\n\n private buildPromptText(): string {\n const sections: string[] = [];\n\n // Scene description\n if (this._scene) {\n let sceneText = this._scene.description;\n if (this._scene.setting) sceneText = `${this._scene.setting}. ${sceneText}`;\n if (this._scene.atmosphere) sceneText += `, ${this._scene.atmosphere} atmosphere`;\n sections.push(sceneText);\n }\n\n // Subject\n if (this._subject) {\n let subjectText = this._subject.main;\n if (this._subject.appearance) subjectText += `, ${this._subject.appearance}`;\n if (this._subject.clothing) subjectText += `, wearing ${this._subject.clothing}`;\n sections.push(subjectText);\n }\n\n // Camera & Cinematography\n const cinematography: string[] = [];\n if (this._camera) {\n if (this._camera.shot) cinematography.push(`${this._camera.shot} shot`);\n if (this._camera.angle) cinematography.push(this._camera.angle);\n if (this._camera.movement) cinematography.push(`${this._camera.movement} camera`);\n if (this._camera.lens) cinematography.push(`${this._camera.lens} lens`);\n if (this._camera.platform) cinematography.push(this._camera.platform);\n if (this._camera.focus) cinematography.push(`${this._camera.focus} focus`);\n }\n if (cinematography.length) {\n sections.push(`Cinematography: ${cinematography.join(', ')}`);\n }\n\n // Lighting\n if (this._lighting) {\n const lightParts: string[] = [];\n if (this._lighting.type) {\n const types = Array.isArray(this._lighting.type) ? this._lighting.type : [this._lighting.type];\n lightParts.push(`${types.join(' and ')} lighting`);\n }\n if (this._lighting.time) lightParts.push(this._lighting.time);\n if (this._lighting.weather) lightParts.push(`${this._lighting.weather} weather`);\n if (this._lighting.intensity) lightParts.push(`${this._lighting.intensity} light`);\n if (this._lighting.sources?.length) lightParts.push(`light sources: ${this._lighting.sources.join(', ')}`);\n if (lightParts.length) sections.push(`Lighting: ${lightParts.join(', ')}`);\n }\n\n // Actions\n if (this._actions.length) {\n const actionText = this._actions.map(a => `- ${a.action}`).join('\\n');\n sections.push(`Actions:\\n${actionText}`);\n }\n\n // Motion\n if (this._motion?.beats?.length) {\n sections.push(`Motion beats: ${this._motion.beats.join(', ')}`);\n }\n\n // Style\n if (this._style) {\n const styleParts: string[] = [];\n if (this._style.format) styleParts.push(this._style.format);\n if (this._style.era) styleParts.push(this._style.era);\n if (this._style.filmStock) styleParts.push(`shot on ${this._style.filmStock}`);\n if (this._style.look) {\n const looks = Array.isArray(this._style.look) ? this._style.look : [this._style.look];\n styleParts.push(looks.join(', '));\n }\n if (styleParts.length) sections.push(`Style: ${styleParts.join(', ')}`);\n }\n\n // Color\n if (this._color) {\n const colorParts: string[] = [];\n if (this._color.palette) {\n const palettes = Array.isArray(this._color.palette) ? this._color.palette : [this._color.palette];\n colorParts.push(`${palettes.join(' and ')} palette`);\n }\n if (this._color.anchors?.length) colorParts.push(`color anchors: ${this._color.anchors.join(', ')}`);\n if (this._color.grade) colorParts.push(this._color.grade);\n if (colorParts.length) sections.push(`Color: ${colorParts.join(', ')}`);\n }\n\n // Audio\n if (this._audio) {\n const audioParts: string[] = [];\n if (this._audio.dialogue) audioParts.push(`Dialogue: \"${this._audio.dialogue}\"`);\n if (this._audio.ambient) audioParts.push(`Ambient: ${this._audio.ambient}`);\n if (this._audio.diegetic?.length) audioParts.push(`Diegetic sounds: ${this._audio.diegetic.join(', ')}`);\n if (this._audio.music) audioParts.push(`Music: ${this._audio.music}`);\n if (audioParts.length) sections.push(`Audio:\\n${audioParts.join('\\n')}`);\n }\n\n // Mood & Pacing\n if (this._mood) {\n const moods = Array.isArray(this._mood) ? this._mood : [this._mood];\n sections.push(`Mood: ${moods.join(', ')}`);\n }\n if (this._pacing) {\n sections.push(`Pacing: ${this._pacing}`);\n }\n\n // Custom\n if (this._custom.length) {\n sections.push(this._custom.join('\\n'));\n }\n\n return sections.join('\\n\\n');\n }\n\n build(): BuiltVideoPrompt {\n return {\n prompt: this.buildPromptText(),\n structure: {\n scene: this._scene,\n subject: this._subject,\n camera: this._camera,\n lighting: this._lighting,\n actions: this._actions.length ? this._actions : undefined,\n motion: this._motion,\n style: this._style,\n color: this._color,\n audio: this._audio,\n technical: this._technical,\n shots: this._shots.length ? this._shots : undefined,\n mood: this._mood,\n pacing: this._pacing,\n transitions: this._transitions.length ? this._transitions : undefined,\n },\n };\n }\n\n toString(): string {\n return this.build().prompt;\n }\n\n toJSON(): string {\n return JSON.stringify(this.build().structure, null, 2);\n }\n\n toYAML(): string {\n return objectToYaml(this.build().structure);\n }\n\n toMarkdown(): string {\n const built = this.build();\n const sections: string[] = ['# Video Prompt\\n'];\n \n sections.push('## Prompt\\n```\\n' + built.prompt + '\\n```\\n');\n \n if (built.structure.scene) {\n sections.push('## Scene\\n' + objectToMarkdownList(built.structure.scene));\n }\n if (built.structure.subject) {\n sections.push('## Subject\\n' + objectToMarkdownList(built.structure.subject));\n }\n if (built.structure.camera) {\n sections.push('## Camera\\n' + objectToMarkdownList(built.structure.camera));\n }\n if (built.structure.lighting) {\n sections.push('## Lighting\\n' + objectToMarkdownList(built.structure.lighting));\n }\n if (built.structure.actions) {\n sections.push('## Actions\\n' + built.structure.actions.map(a => `- **Beat ${a.beat}:** ${a.action}`).join('\\n'));\n }\n if (built.structure.style) {\n sections.push('## Style\\n' + objectToMarkdownList(built.structure.style));\n }\n if (built.structure.audio) {\n sections.push('## Audio\\n' + objectToMarkdownList(built.structure.audio));\n }\n if (built.structure.technical) {\n sections.push('## Technical\\n' + objectToMarkdownList(built.structure.technical));\n }\n \n return sections.join('\\n');\n }\n\n outputFormat(fmt: OutputFormat): string {\n switch (fmt) {\n case 'json': return this.toJSON();\n case 'yaml': return this.toYAML();\n case 'markdown': return this.toMarkdown();\n default: return this.toString();\n }\n }\n}\n\n// ============================================================================\n// HELPER FUNCTIONS\n// ============================================================================\n\nfunction objectToYaml(obj: object, indent = 0): string {\n const spaces = ' '.repeat(indent);\n const lines: string[] = [];\n \n for (const [key, value] of Object.entries(obj)) {\n if (value === undefined || value === null) continue;\n \n if (Array.isArray(value)) {\n if (value.length === 0) continue;\n lines.push(`${spaces}${key}:`);\n for (const item of value) {\n if (typeof item === 'object') {\n lines.push(`${spaces} -`);\n lines.push(objectToYaml(item, indent + 2).replace(/^/gm, ' '));\n } else {\n lines.push(`${spaces} - ${item}`);\n }\n }\n } else if (typeof value === 'object') {\n lines.push(`${spaces}${key}:`);\n lines.push(objectToYaml(value, indent + 1));\n } else {\n lines.push(`${spaces}${key}: ${value}`);\n }\n }\n \n return lines.join('\\n');\n}\n\nfunction objectToMarkdownList(obj: object, indent = 0): string {\n const spaces = ' '.repeat(indent);\n const lines: string[] = [];\n \n for (const [key, value] of Object.entries(obj)) {\n if (value === undefined || value === null) continue;\n \n if (Array.isArray(value)) {\n lines.push(`${spaces}- **${key}:** ${value.join(', ')}`);\n } else if (typeof value === 'object') {\n lines.push(`${spaces}- **${key}:**`);\n lines.push(objectToMarkdownList(value, indent + 1));\n } else {\n lines.push(`${spaces}- **${key}:** ${value}`);\n }\n }\n \n return lines.join('\\n');\n}\n\n// ============================================================================\n// FACTORY FUNCTION\n// ============================================================================\n\n/**\n * Create a new video prompt builder\n */\nexport function video(): VideoPromptBuilder {\n return new VideoPromptBuilder();\n}\n","/**\n * Audio/Music Prompt Builder - Comprehensive music generation prompt builder\n * \n * Based on Suno, Udio, and other music generation best practices.\n * \n * @example\n * ```ts\n * import { audio } from 'prompts.chat/builder';\n * \n * const prompt = audio()\n * .genre(\"synthwave\")\n * .mood(\"nostalgic\", \"dreamy\")\n * .tempo(110)\n * .instruments([\"synthesizer\", \"drums\", \"bass\"])\n * .structure({ intro: 8, verse: 16, chorus: 16 })\n * .build();\n * ```\n */\n\nimport type { Mood, OutputFormat } from './media';\n\n// ============================================================================\n// AUDIO-SPECIFIC TYPES\n// ============================================================================\n\nexport type MusicGenre = \n | 'pop' | 'rock' | 'jazz' | 'classical' | 'electronic' | 'hip-hop' | 'r&b'\n | 'country' | 'folk' | 'blues' | 'metal' | 'punk' | 'indie' | 'alternative'\n | 'ambient' | 'lo-fi' | 'synthwave' | 'orchestral' | 'cinematic' | 'world'\n | 'latin' | 'reggae' | 'soul' | 'funk' | 'disco' | 'house' | 'techno' | 'edm'\n | 'trap' | 'drill' | 'k-pop' | 'j-pop' | 'bossa-nova' | 'gospel' | 'grunge'\n | 'shoegaze' | 'post-rock' | 'prog-rock' | 'psychedelic' | 'chillwave'\n | 'vaporwave' | 'drum-and-bass' | 'dubstep' | 'trance' | 'hardcore';\n\nexport type Instrument = \n | 'piano' | 'guitar' | 'acoustic-guitar' | 'electric-guitar' | 'bass' | 'drums'\n | 'violin' | 'cello' | 'viola' | 'flute' | 'saxophone' | 'trumpet' | 'trombone'\n | 'synthesizer' | 'organ' | 'harp' | 'percussion' | 'strings' | 'brass' | 'woodwinds'\n | 'choir' | 'vocals' | 'beatbox' | 'turntables' | 'harmonica' | 'banjo' | 'ukulele'\n | 'mandolin' | 'accordion' | 'marimba' | 'vibraphone' | 'xylophone' | 'timpani'\n | 'congas' | 'bongos' | 'djembe' | 'tabla' | 'sitar' | 'erhu' | 'koto'\n | '808' | '909' | 'moog' | 'rhodes' | 'wurlitzer' | 'mellotron' | 'theremin';\n\nexport type VocalStyle = \n | 'male' | 'female' | 'duet' | 'choir' | 'a-cappella' | 'spoken-word' | 'rap'\n | 'falsetto' | 'belting' | 'whisper' | 'growl' | 'melodic' | 'harmonized'\n | 'auto-tuned' | 'operatic' | 'soul' | 'breathy' | 'nasal' | 'raspy' | 'clear';\n\nexport type VocalLanguage =\n | 'english' | 'spanish' | 'french' | 'german' | 'italian' | 'portuguese'\n | 'japanese' | 'korean' | 'chinese' | 'arabic' | 'hindi' | 'russian' | 'turkish'\n | 'instrumental';\n\nexport type TempoMarking = \n | 'largo' | 'adagio' | 'andante' | 'moderato' | 'allegro' | 'vivace' | 'presto';\n\nexport type TimeSignature = '4/4' | '3/4' | '6/8' | '2/4' | '5/4' | '7/8' | '12/8';\n\nexport type MusicalKey = \n | 'C' | 'C#' | 'Db' | 'D' | 'D#' | 'Eb' | 'E' | 'F' | 'F#' | 'Gb' \n | 'G' | 'G#' | 'Ab' | 'A' | 'A#' | 'Bb' | 'B'\n | 'Cm' | 'C#m' | 'Dm' | 'D#m' | 'Ebm' | 'Em' | 'Fm' | 'F#m' \n | 'Gm' | 'G#m' | 'Am' | 'A#m' | 'Bbm' | 'Bm';\n\nexport type SongSection = \n | 'intro' | 'verse' | 'pre-chorus' | 'chorus' | 'bridge' | 'breakdown'\n | 'drop' | 'build-up' | 'outro' | 'solo' | 'interlude' | 'hook';\n\nexport type ProductionStyle =\n | 'lo-fi' | 'hi-fi' | 'vintage' | 'modern' | 'polished' | 'raw' | 'organic'\n | 'synthetic' | 'acoustic' | 'electric' | 'hybrid' | 'minimalist' | 'maximalist'\n | 'layered' | 'sparse' | 'dense' | 'atmospheric' | 'punchy' | 'warm' | 'bright';\n\nexport type Era =\n | '1950s' | '1960s' | '1970s' | '1980s' | '1990s' | '2000s' | '2010s' | '2020s'\n | 'retro' | 'vintage' | 'classic' | 'modern' | 'futuristic';\n\n// ============================================================================\n// AUDIO INTERFACES\n// ============================================================================\n\nexport interface AudioGenre {\n primary: MusicGenre;\n secondary?: MusicGenre[];\n subgenre?: string;\n fusion?: string[];\n}\n\nexport interface AudioMood {\n primary: Mood | string;\n secondary?: (Mood | string)[];\n energy?: 'low' | 'medium' | 'high' | 'building' | 'fluctuating';\n emotion?: string;\n}\n\nexport interface AudioTempo {\n bpm?: number;\n marking?: TempoMarking;\n feel?: 'steady' | 'swung' | 'shuffled' | 'syncopated' | 'rubato' | 'driving';\n variation?: boolean;\n}\n\nexport interface AudioVocals {\n style?: VocalStyle | VocalStyle[];\n language?: VocalLanguage;\n lyrics?: string;\n theme?: string;\n delivery?: string;\n harmonies?: boolean;\n adlibs?: boolean;\n}\n\nexport interface AudioInstrumentation {\n lead?: Instrument | Instrument[];\n rhythm?: Instrument | Instrument[];\n bass?: Instrument;\n percussion?: Instrument | Instrument[];\n pads?: Instrument | Instrument[];\n effects?: string[];\n featured?: Instrument;\n}\n\nexport interface AudioStructure {\n sections?: Array<{\n type: SongSection;\n bars?: number;\n description?: string;\n }>;\n intro?: number;\n verse?: number;\n chorus?: number;\n bridge?: number;\n outro?: number;\n form?: string;\n duration?: number;\n}\n\nexport interface AudioProduction {\n style?: ProductionStyle | ProductionStyle[];\n era?: Era;\n reference?: string[];\n mix?: string;\n mastering?: string;\n effects?: string[];\n texture?: string;\n}\n\nexport interface AudioTechnical {\n key?: MusicalKey;\n timeSignature?: TimeSignature;\n duration?: number;\n format?: 'song' | 'instrumental' | 'jingle' | 'loop' | 'soundtrack';\n}\n\nexport interface BuiltAudioPrompt {\n prompt: string;\n stylePrompt: string;\n lyricsPrompt?: string;\n structure: {\n genre?: AudioGenre;\n mood?: AudioMood;\n tempo?: AudioTempo;\n vocals?: AudioVocals;\n instrumentation?: AudioInstrumentation;\n structure?: AudioStructure;\n production?: AudioProduction;\n technical?: AudioTechnical;\n tags?: string[];\n };\n}\n\n// ============================================================================\n// AUDIO PROMPT BUILDER\n// ============================================================================\n\nexport class AudioPromptBuilder {\n private _genre?: AudioGenre;\n private _mood?: AudioMood;\n private _tempo?: AudioTempo;\n private _vocals?: AudioVocals;\n private _instrumentation?: AudioInstrumentation;\n private _structure?: AudioStructure;\n private _production?: AudioProduction;\n private _technical?: AudioTechnical;\n private _tags: string[] = [];\n private _custom: string[] = [];\n\n // --- Genre Methods ---\n\n genre(primary: MusicGenre | AudioGenre): this {\n if (typeof primary === 'string') {\n this._genre = { ...(this._genre || { primary: 'pop' }), primary };\n } else {\n this._genre = { ...(this._genre || { primary: 'pop' }), ...primary };\n }\n return this;\n }\n\n subgenre(subgenre: string): this {\n this._genre = { ...(this._genre || { primary: 'pop' }), subgenre };\n return this;\n }\n\n fusion(genres: MusicGenre[]): this {\n this._genre = { \n ...(this._genre || { primary: 'pop' }), \n secondary: genres,\n fusion: genres as string[],\n };\n return this;\n }\n\n // --- Mood Methods ---\n\n mood(primary: Mood | string, ...secondary: (Mood | string)[]): this {\n this._mood = { \n primary, \n secondary: secondary.length ? secondary : undefined,\n };\n return this;\n }\n\n energy(level: AudioMood['energy']): this {\n this._mood = { ...(this._mood || { primary: 'energetic' }), energy: level };\n return this;\n }\n\n emotion(emotion: string): this {\n this._mood = { ...(this._mood || { primary: 'emotional' }), emotion };\n return this;\n }\n\n // --- Tempo Methods ---\n\n tempo(bpmOrSettings: number | AudioTempo): this {\n if (typeof bpmOrSettings === 'number') {\n this._tempo = { ...(this._tempo || {}), bpm: bpmOrSettings };\n } else {\n this._tempo = { ...(this._tempo || {}), ...bpmOrSettings };\n }\n return this;\n }\n\n bpm(bpm: number): this {\n this._tempo = { ...(this._tempo || {}), bpm };\n return this;\n }\n\n tempoMarking(marking: TempoMarking): this {\n this._tempo = { ...(this._tempo || {}), marking };\n return this;\n }\n\n tempoFeel(feel: AudioTempo['feel']): this {\n this._tempo = { ...(this._tempo || {}), feel };\n return this;\n }\n\n // --- Vocal Methods ---\n\n vocals(settings: AudioVocals): this {\n this._vocals = { ...(this._vocals || {}), ...settings };\n return this;\n }\n\n vocalStyle(style: VocalStyle | VocalStyle[]): this {\n this._vocals = { ...(this._vocals || {}), style };\n return this;\n }\n\n language(language: VocalLanguage): this {\n this._vocals = { ...(this._vocals || {}), language };\n return this;\n }\n\n lyrics(lyrics: string): this {\n this._vocals = { ...(this._vocals || {}), lyrics };\n return this;\n }\n\n lyricsTheme(theme: string): this {\n this._vocals = { ...(this._vocals || {}), theme };\n return this;\n }\n\n delivery(delivery: string): this {\n this._vocals = { ...(this._vocals || {}), delivery };\n return this;\n }\n\n instrumental(): this {\n this._vocals = { ...(this._vocals || {}), language: 'instrumental' };\n return this;\n }\n\n // --- Instrumentation Methods ---\n\n instruments(instruments: Instrument[]): this {\n this._instrumentation = { \n ...(this._instrumentation || {}), \n lead: instruments,\n };\n return this;\n }\n\n instrumentation(settings: AudioInstrumentation): this {\n this._instrumentation = { ...(this._instrumentation || {}), ...settings };\n return this;\n }\n\n leadInstrument(instrument: Instrument | Instrument[]): this {\n this._instrumentation = { ...(this._instrumentation || {}), lead: instrument };\n return this;\n }\n\n rhythmSection(instruments: Instrument[]): this {\n this._instrumentation = { ...(this._instrumentation || {}), rhythm: instruments };\n return this;\n }\n\n bassInstrument(instrument: Instrument): this {\n this._instrumentation = { ...(this._instrumentation || {}), bass: instrument };\n return this;\n }\n\n percussion(instruments: Instrument | Instrument[]): this {\n this._instrumentation = { ...(this._instrumentation || {}), percussion: instruments };\n return this;\n }\n\n pads(instruments: Instrument | Instrument[]): this {\n this._instrumentation = { ...(this._instrumentation || {}), pads: instruments };\n return this;\n }\n\n featuredInstrument(instrument: Instrument): this {\n this._instrumentation = { ...(this._instrumentation || {}), featured: instrument };\n return this;\n }\n\n // --- Structure Methods ---\n\n structure(settings: AudioStructure | { [key in SongSection]?: number }): this {\n if ('sections' in settings || 'form' in settings || 'duration' in settings) {\n this._structure = { ...(this._structure || {}), ...settings as AudioStructure };\n } else {\n // Convert shorthand to full structure\n const sections: AudioStructure['sections'] = [];\n for (const [type, bars] of Object.entries(settings)) {\n if (typeof bars === 'number') {\n sections.push({ type: type as SongSection, bars });\n }\n }\n this._structure = { ...(this._structure || {}), sections };\n }\n return this;\n }\n\n section(type: SongSection, bars?: number, description?: string): this {\n const sections = this._structure?.sections || [];\n sections.push({ type, bars, description });\n this._structure = { ...(this._structure || {}), sections };\n return this;\n }\n\n form(form: string): this {\n this._structure = { ...(this._structure || {}), form };\n return this;\n }\n\n duration(seconds: number): this {\n this._structure = { ...(this._structure || {}), duration: seconds };\n return this;\n }\n\n // --- Production Methods ---\n\n production(settings: AudioProduction): this {\n this._production = { ...(this._production || {}), ...settings };\n return this;\n }\n\n productionStyle(style: ProductionStyle | ProductionStyle[]): this {\n this._production = { ...(this._production || {}), style };\n return this;\n }\n\n era(era: Era): this {\n this._production = { ...(this._production || {}), era };\n return this;\n }\n\n reference(artists: string[]): this {\n this._production = { ...(this._production || {}), reference: artists };\n return this;\n }\n\n texture(texture: string): this {\n this._production = { ...(this._production || {}), texture };\n return this;\n }\n\n effects(effects: string[]): this {\n this._production = { ...(this._production || {}), effects };\n return this;\n }\n\n // --- Technical Methods ---\n\n technical(settings: AudioTechnical): this {\n this._technical = { ...(this._technical || {}), ...settings };\n return this;\n }\n\n key(key: MusicalKey): this {\n this._technical = { ...(this._technical || {}), key };\n return this;\n }\n\n timeSignature(sig: TimeSignature): this {\n this._technical = { ...(this._technical || {}), timeSignature: sig };\n return this;\n }\n\n formatType(format: AudioTechnical['format']): this {\n this._technical = { ...(this._technical || {}), format };\n return this;\n }\n\n // --- Tags & Custom ---\n\n tag(tag: string): this {\n this._tags.push(tag);\n return this;\n }\n\n tags(tags: string[]): this {\n this._tags = [...this._tags, ...tags];\n return this;\n }\n\n custom(text: string): this {\n this._custom.push(text);\n return this;\n }\n\n // --- Build Methods ---\n\n private buildStylePrompt(): string {\n const parts: string[] = [];\n\n // Genre\n if (this._genre) {\n let genreText: string = this._genre.primary;\n if (this._genre.subgenre) genreText = `${this._genre.subgenre} ${genreText}`;\n if (this._genre.secondary?.length) {\n genreText += ` with ${this._genre.secondary.join(' and ')} influences`;\n }\n parts.push(genreText);\n }\n\n // Mood\n if (this._mood) {\n let moodText = String(this._mood.primary);\n if (this._mood.secondary?.length) {\n moodText += `, ${this._mood.secondary.join(', ')}`;\n }\n if (this._mood.energy) moodText += `, ${this._mood.energy} energy`;\n parts.push(moodText);\n }\n\n // Tempo\n if (this._tempo) {\n const tempoParts: string[] = [];\n if (this._tempo.bpm) tempoParts.push(`${this._tempo.bpm} BPM`);\n if (this._tempo.marking) tempoParts.push(this._tempo.marking);\n if (this._tempo.feel) tempoParts.push(`${this._tempo.feel} feel`);\n if (tempoParts.length) parts.push(tempoParts.join(', '));\n }\n\n // Instrumentation\n if (this._instrumentation) {\n const instrParts: string[] = [];\n if (this._instrumentation.lead) {\n const leads = Array.isArray(this._instrumentation.lead) \n ? this._instrumentation.lead : [this._instrumentation.lead];\n instrParts.push(leads.join(', '));\n }\n if (this._instrumentation.featured) {\n instrParts.push(`featuring ${this._instrumentation.featured}`);\n }\n if (instrParts.length) parts.push(instrParts.join(', '));\n }\n\n // Vocals\n if (this._vocals) {\n const vocalParts: string[] = [];\n if (this._vocals.language === 'instrumental') {\n vocalParts.push('instrumental');\n } else {\n if (this._vocals.style) {\n const styles = Array.isArray(this._vocals.style) \n ? this._vocals.style : [this._vocals.style];\n vocalParts.push(`${styles.join(' and ')} vocals`);\n }\n if (this._vocals.language && this._vocals.language !== 'english') {\n vocalParts.push(`in ${this._vocals.language}`);\n }\n }\n if (vocalParts.length) parts.push(vocalParts.join(' '));\n }\n\n // Production\n if (this._production) {\n const prodParts: string[] = [];\n if (this._production.style) {\n const styles = Array.isArray(this._production.style) \n ? this._production.style : [this._production.style];\n prodParts.push(`${styles.join(', ')} production`);\n }\n if (this._production.era) prodParts.push(`${this._production.era} sound`);\n if (this._production.texture) prodParts.push(this._production.texture);\n if (prodParts.length) parts.push(prodParts.join(', '));\n }\n\n // Technical\n if (this._technical) {\n const techParts: string[] = [];\n if (this._technical.key) techParts.push(`in the key of ${this._technical.key}`);\n if (this._technical.timeSignature && this._technical.timeSignature !== '4/4') {\n techParts.push(`${this._technical.timeSignature} time`);\n }\n if (techParts.length) parts.push(techParts.join(', '));\n }\n\n // Tags\n if (this._tags.length) {\n parts.push(this._tags.join(', '));\n }\n\n // Custom\n if (this._custom.length) {\n parts.push(this._custom.join(', '));\n }\n\n return parts.join(', ');\n }\n\n private buildLyricsPrompt(): string | undefined {\n if (!this._vocals?.lyrics && !this._vocals?.theme) return undefined;\n\n const parts: string[] = [];\n\n if (this._vocals.theme) {\n parts.push(`Theme: ${this._vocals.theme}`);\n }\n\n if (this._vocals.lyrics) {\n parts.push(this._vocals.lyrics);\n }\n\n return parts.join('\\n\\n');\n }\n\n private buildFullPrompt(): string {\n const sections: string[] = [];\n\n sections.push(`Style: ${this.buildStylePrompt()}`);\n\n if (this._structure?.sections?.length) {\n const structureText = this._structure.sections\n .map(s => `[${s.type.toUpperCase()}]${s.description ? ` ${s.description}` : ''}`)\n .join('\\n');\n sections.push(`Structure:\\n${structureText}`);\n }\n\n const lyrics = this.buildLyricsPrompt();\n if (lyrics) {\n sections.push(`Lyrics:\\n${lyrics}`);\n }\n\n return sections.join('\\n\\n');\n }\n\n build(): BuiltAudioPrompt {\n return {\n prompt: this.buildFullPrompt(),\n stylePrompt: this.buildStylePrompt(),\n lyricsPrompt: this.buildLyricsPrompt(),\n structure: {\n genre: this._genre,\n mood: this._mood,\n tempo: this._tempo,\n vocals: this._vocals,\n instrumentation: this._instrumentation,\n structure: this._structure,\n production: this._production,\n technical: this._technical,\n tags: this._tags.length ? this._tags : undefined,\n },\n };\n }\n\n toString(): string {\n return this.build().prompt;\n }\n\n toStyleString(): string {\n return this.build().stylePrompt;\n }\n\n toJSON(): string {\n return JSON.stringify(this.build().structure, null, 2);\n }\n\n toYAML(): string {\n return objectToYaml(this.build().structure);\n }\n\n toMarkdown(): string {\n const built = this.build();\n const sections: string[] = ['# Audio Prompt\\n'];\n \n sections.push('## Style Prompt\\n```\\n' + built.stylePrompt + '\\n```\\n');\n \n if (built.lyricsPrompt) {\n sections.push('## Lyrics\\n```\\n' + built.lyricsPrompt + '\\n```\\n');\n }\n \n if (built.structure.genre) {\n sections.push('## Genre\\n' + objectToMarkdownList(built.structure.genre));\n }\n if (built.structure.mood) {\n sections.push('## Mood\\n' + objectToMarkdownList(built.structure.mood));\n }\n if (built.structure.tempo) {\n sections.push('## Tempo\\n' + objectToMarkdownList(built.structure.tempo));\n }\n if (built.structure.vocals) {\n sections.push('## Vocals\\n' + objectToMarkdownList(built.structure.vocals));\n }\n if (built.structure.instrumentation) {\n sections.push('## Instrumentation\\n' + objectToMarkdownList(built.structure.instrumentation));\n }\n if (built.structure.production) {\n sections.push('## Production\\n' + objectToMarkdownList(built.structure.production));\n }\n \n return sections.join('\\n');\n }\n\n outputFormat(fmt: OutputFormat): string {\n switch (fmt) {\n case 'json': return this.toJSON();\n case 'yaml': return this.toYAML();\n case 'markdown': return this.toMarkdown();\n default: return this.toString();\n }\n }\n}\n\n// ============================================================================\n// HELPER FUNCTIONS\n// ============================================================================\n\nfunction objectToYaml(obj: object, indent = 0): string {\n const spaces = ' '.repeat(indent);\n const lines: string[] = [];\n \n for (const [key, value] of Object.entries(obj)) {\n if (value === undefined || value === null) continue;\n \n if (Array.isArray(value)) {\n if (value.length === 0) continue;\n lines.push(`${spaces}${key}:`);\n for (const item of value) {\n if (typeof item === 'object') {\n lines.push(`${spaces} -`);\n lines.push(objectToYaml(item, indent + 2).replace(/^/gm, ' '));\n } else {\n lines.push(`${spaces} - ${item}`);\n }\n }\n } else if (typeof value === 'object') {\n lines.push(`${spaces}${key}:`);\n lines.push(objectToYaml(value, indent + 1));\n } else {\n lines.push(`${spaces}${key}: ${value}`);\n }\n }\n \n return lines.join('\\n');\n}\n\nfunction objectToMarkdownList(obj: object, indent = 0): string {\n const spaces = ' '.repeat(indent);\n const lines: string[] = [];\n \n for (const [key, value] of Object.entries(obj)) {\n if (value === undefined || value === null) continue;\n \n if (Array.isArray(value)) {\n lines.push(`${spaces}- **${key}:** ${value.join(', ')}`);\n } else if (typeof value === 'object') {\n lines.push(`${spaces}- **${key}:**`);\n lines.push(objectToMarkdownList(value, indent + 1));\n } else {\n lines.push(`${spaces}- **${key}:** ${value}`);\n }\n }\n \n return lines.join('\\n');\n}\n\n// ============================================================================\n// FACTORY FUNCTION\n// ============================================================================\n\n/**\n * Create a new audio/music prompt builder\n */\nexport function audio(): AudioPromptBuilder {\n return new AudioPromptBuilder();\n}\n","/**\n * Chat Prompt Builder - Model-Agnostic Conversation Prompt Builder\n * \n * Build structured prompts for any chat/conversation model.\n * Focus on prompt engineering, not model-specific features.\n * \n * @example\n * ```ts\n * import { chat } from 'prompts.chat/builder';\n * \n * const prompt = chat()\n * .role(\"helpful coding assistant\")\n * .context(\"Building a React application\")\n * .task(\"Explain async/await in JavaScript\")\n * .stepByStep()\n * .detailed()\n * .build();\n * ```\n */\n\n// ============================================================================\n// TYPES & INTERFACES\n// ============================================================================\n\n// --- Message Types ---\nexport type MessageRole = 'system' | 'user' | 'assistant';\n\nexport interface ChatMessage {\n role: MessageRole;\n content: string;\n name?: string;\n}\n\n// --- Response Format Types ---\nexport type ResponseFormatType = 'text' | 'json' | 'markdown' | 'code' | 'table';\n\nexport interface JsonSchema {\n name: string;\n description?: string;\n schema: Record<string, unknown>;\n}\n\nexport interface ResponseFormat {\n type: ResponseFormatType;\n jsonSchema?: JsonSchema;\n language?: string;\n}\n\n// --- Persona Types ---\nexport type PersonaTone = \n | 'professional' | 'casual' | 'formal' | 'friendly' | 'academic'\n | 'technical' | 'creative' | 'empathetic' | 'authoritative' | 'playful'\n | 'concise' | 'detailed' | 'socratic' | 'coaching' | 'analytical'\n | 'encouraging' | 'neutral' | 'humorous' | 'serious';\n\nexport type PersonaExpertise = \n | 'general' | 'coding' | 'writing' | 'analysis' | 'research'\n | 'teaching' | 'counseling' | 'creative' | 'legal' | 'medical'\n | 'financial' | 'scientific' | 'engineering' | 'design' | 'marketing'\n | 'business' | 'philosophy' | 'history' | 'languages' | 'mathematics';\n\n// --- Reasoning Types ---\nexport type ReasoningStyle = \n | 'step-by-step' | 'chain-of-thought' | 'tree-of-thought' \n | 'direct' | 'analytical' | 'comparative' | 'deductive' | 'inductive'\n | 'first-principles' | 'analogical' | 'devil-advocate';\n\n// --- Output Types ---\nexport type OutputLength = 'brief' | 'moderate' | 'detailed' | 'comprehensive' | 'exhaustive';\nexport type OutputStyle = 'prose' | 'bullet-points' | 'numbered-list' | 'table' | 'code' | 'mixed' | 'qa' | 'dialogue';\n\n// ============================================================================\n// INTERFACES\n// ============================================================================\n\nexport interface ChatPersona {\n name?: string;\n role?: string;\n tone?: PersonaTone | PersonaTone[];\n expertise?: PersonaExpertise | PersonaExpertise[];\n personality?: string[];\n background?: string;\n language?: string;\n verbosity?: OutputLength;\n}\n\nexport interface ChatContext {\n background?: string;\n domain?: string;\n audience?: string;\n purpose?: string;\n constraints?: string[];\n assumptions?: string[];\n knowledge?: string[];\n}\n\nexport interface ChatTask {\n instruction: string;\n steps?: string[];\n deliverables?: string[];\n criteria?: string[];\n antiPatterns?: string[];\n priority?: 'accuracy' | 'speed' | 'creativity' | 'thoroughness';\n}\n\nexport interface ChatOutput {\n format?: ResponseFormat;\n length?: OutputLength;\n style?: OutputStyle;\n language?: string;\n includeExplanation?: boolean;\n includeExamples?: boolean;\n includeSources?: boolean;\n includeConfidence?: boolean;\n}\n\nexport interface ChatReasoning {\n style?: ReasoningStyle;\n showWork?: boolean;\n verifyAnswer?: boolean;\n considerAlternatives?: boolean;\n explainAssumptions?: boolean;\n}\n\nexport interface ChatExample {\n input: string;\n output: string;\n explanation?: string;\n}\n\nexport interface ChatMemory {\n summary?: string;\n facts?: string[];\n preferences?: string[];\n history?: ChatMessage[];\n}\n\nexport interface BuiltChatPrompt {\n messages: ChatMessage[];\n systemPrompt: string;\n userPrompt?: string;\n metadata: {\n persona?: ChatPersona;\n context?: ChatContext;\n task?: ChatTask;\n output?: ChatOutput;\n reasoning?: ChatReasoning;\n examples?: ChatExample[];\n };\n}\n\n// ============================================================================\n// CHAT PROMPT BUILDER\n// ============================================================================\n\nexport class ChatPromptBuilder {\n private _messages: ChatMessage[] = [];\n private _persona?: ChatPersona;\n private _context?: ChatContext;\n private _task?: ChatTask;\n private _output?: ChatOutput;\n private _reasoning?: ChatReasoning;\n private _examples: ChatExample[] = [];\n private _memory?: ChatMemory;\n private _customSystemParts: string[] = [];\n\n // --- Message Methods ---\n\n system(content: string): this {\n // Remove existing system message and add new one at beginning\n this._messages = this._messages.filter(m => m.role !== 'system');\n this._messages.unshift({ role: 'system', content });\n return this;\n }\n\n user(content: string, name?: string): this {\n this._messages.push({ role: 'user', content, name });\n return this;\n }\n\n assistant(content: string): this {\n this._messages.push({ role: 'assistant', content });\n return this;\n }\n\n message(role: MessageRole, content: string, name?: string): this {\n this._messages.push({ role, content, name });\n return this;\n }\n\n messages(messages: ChatMessage[]): this {\n this._messages = [...this._messages, ...messages];\n return this;\n }\n\n conversation(turns: Array<{ user: string; assistant?: string }>): this {\n for (const turn of turns) {\n this.user(turn.user);\n if (turn.assistant) {\n this.assistant(turn.assistant);\n }\n }\n return this;\n }\n\n // --- Persona Methods ---\n\n persona(settings: ChatPersona | string): this {\n if (typeof settings === 'string') {\n this._persona = { ...(this._persona || {}), role: settings };\n } else {\n this._persona = { ...(this._persona || {}), ...settings };\n }\n return this;\n }\n\n role(role: string): this {\n this._persona = { ...(this._persona || {}), role };\n return this;\n }\n\n tone(tone: PersonaTone | PersonaTone[]): this {\n this._persona = { ...(this._persona || {}), tone };\n return this;\n }\n\n expertise(expertise: PersonaExpertise | PersonaExpertise[]): this {\n this._persona = { ...(this._persona || {}), expertise };\n return this;\n }\n\n personality(traits: string[]): this {\n this._persona = { ...(this._persona || {}), personality: traits };\n return this;\n }\n\n background(background: string): this {\n this._persona = { ...(this._persona || {}), background };\n return this;\n }\n\n speakAs(name: string): this {\n this._persona = { ...(this._persona || {}), name };\n return this;\n }\n\n responseLanguage(language: string): this {\n this._persona = { ...(this._persona || {}), language };\n return this;\n }\n\n // --- Context Methods ---\n\n context(settings: ChatContext | string): this {\n if (typeof settings === 'string') {\n this._context = { ...(this._context || {}), background: settings };\n } else {\n this._context = { ...(this._context || {}), ...settings };\n }\n return this;\n }\n\n domain(domain: string): this {\n this._context = { ...(this._context || {}), domain };\n return this;\n }\n\n audience(audience: string): this {\n this._context = { ...(this._context || {}), audience };\n return this;\n }\n\n purpose(purpose: string): this {\n this._context = { ...(this._context || {}), purpose };\n return this;\n }\n\n constraints(constraints: string[]): this {\n const existing = this._context?.constraints || [];\n this._context = { ...(this._context || {}), constraints: [...existing, ...constraints] };\n return this;\n }\n\n constraint(constraint: string): this {\n return this.constraints([constraint]);\n }\n\n assumptions(assumptions: string[]): this {\n this._context = { ...(this._context || {}), assumptions };\n return this;\n }\n\n knowledge(facts: string[]): this {\n this._context = { ...(this._context || {}), knowledge: facts };\n return this;\n }\n\n // --- Task Methods ---\n\n task(instruction: string | ChatTask): this {\n if (typeof instruction === 'string') {\n this._task = { ...(this._task || { instruction: '' }), instruction };\n } else {\n this._task = { ...(this._task || { instruction: '' }), ...instruction };\n }\n return this;\n }\n\n instruction(instruction: string): this {\n this._task = { ...(this._task || { instruction: '' }), instruction };\n return this;\n }\n\n steps(steps: string[]): this {\n this._task = { ...(this._task || { instruction: '' }), steps };\n return this;\n }\n\n deliverables(deliverables: string[]): this {\n this._task = { ...(this._task || { instruction: '' }), deliverables };\n return this;\n }\n\n criteria(criteria: string[]): this {\n this._task = { ...(this._task || { instruction: '' }), criteria };\n return this;\n }\n\n avoid(antiPatterns: string[]): this {\n this._task = { ...(this._task || { instruction: '' }), antiPatterns };\n return this;\n }\n\n priority(priority: ChatTask['priority']): this {\n this._task = { ...(this._task || { instruction: '' }), priority };\n return this;\n }\n\n // --- Example Methods ---\n\n example(input: string, output: string, explanation?: string): this {\n this._examples.push({ input, output, explanation });\n return this;\n }\n\n examples(examples: ChatExample[]): this {\n this._examples = [...this._examples, ...examples];\n return this;\n }\n\n fewShot(examples: Array<{ input: string; output: string }>): this {\n for (const ex of examples) {\n this._examples.push(ex);\n }\n return this;\n }\n\n // --- Output Methods ---\n\n output(settings: ChatOutput): this {\n this._output = { ...(this._output || {}), ...settings };\n return this;\n }\n\n outputFormat(format: ResponseFormatType): this {\n this._output = { \n ...(this._output || {}), \n format: { type: format } \n };\n return this;\n }\n\n json(schema?: JsonSchema): this {\n if (schema) {\n this._output = { \n ...(this._output || {}), \n format: { type: 'json', jsonSchema: schema } \n };\n } else {\n this._output = { \n ...(this._output || {}), \n format: { type: 'json' } \n };\n }\n return this;\n }\n\n jsonSchema(name: string, schema: Record<string, unknown>, description?: string): this {\n this._output = { \n ...(this._output || {}), \n format: { \n type: 'json', \n jsonSchema: { name, schema, description } \n } \n };\n return this;\n }\n\n markdown(): this {\n this._output = { ...(this._output || {}), format: { type: 'markdown' } };\n return this;\n }\n\n code(language?: string): this {\n this._output = { ...(this._output || {}), format: { type: 'code', language } };\n return this;\n }\n\n table(): this {\n this._output = { ...(this._output || {}), format: { type: 'table' } };\n return this;\n }\n\n length(length: OutputLength): this {\n this._output = { ...(this._output || {}), length };\n return this;\n }\n\n style(style: OutputStyle): this {\n this._output = { ...(this._output || {}), style };\n return this;\n }\n\n brief(): this {\n return this.length('brief');\n }\n\n moderate(): this {\n return this.length('moderate');\n }\n\n detailed(): this {\n return this.length('detailed');\n }\n\n comprehensive(): this {\n return this.length('comprehensive');\n }\n\n exhaustive(): this {\n return this.length('exhaustive');\n }\n\n withExamples(): this {\n this._output = { ...(this._output || {}), includeExamples: true };\n return this;\n }\n\n withExplanation(): this {\n this._output = { ...(this._output || {}), includeExplanation: true };\n return this;\n }\n\n withSources(): this {\n this._output = { ...(this._output || {}), includeSources: true };\n return this;\n }\n\n withConfidence(): this {\n this._output = { ...(this._output || {}), includeConfidence: true };\n return this;\n }\n\n // --- Reasoning Methods ---\n\n reasoning(settings: ChatReasoning): this {\n this._reasoning = { ...(this._reasoning || {}), ...settings };\n return this;\n }\n\n reasoningStyle(style: ReasoningStyle): this {\n this._reasoning = { ...(this._reasoning || {}), style };\n return this;\n }\n\n stepByStep(): this {\n this._reasoning = { ...(this._reasoning || {}), style: 'step-by-step', showWork: true };\n return this;\n }\n\n chainOfThought(): this {\n this._reasoning = { ...(this._reasoning || {}), style: 'chain-of-thought', showWork: true };\n return this;\n }\n\n treeOfThought(): this {\n this._reasoning = { ...(this._reasoning || {}), style: 'tree-of-thought', showWork: true };\n return this;\n }\n\n firstPrinciples(): this {\n this._reasoning = { ...(this._reasoning || {}), style: 'first-principles', showWork: true };\n return this;\n }\n\n devilsAdvocate(): this {\n this._reasoning = { ...(this._reasoning || {}), style: 'devil-advocate', considerAlternatives: true };\n return this;\n }\n\n showWork(show = true): this {\n this._reasoning = { ...(this._reasoning || {}), showWork: show };\n return this;\n }\n\n verifyAnswer(verify = true): this {\n this._reasoning = { ...(this._reasoning || {}), verifyAnswer: verify };\n return this;\n }\n\n considerAlternatives(consider = true): this {\n this._reasoning = { ...(this._reasoning || {}), considerAlternatives: consider };\n return this;\n }\n\n explainAssumptions(explain = true): this {\n this._reasoning = { ...(this._reasoning || {}), explainAssumptions: explain };\n return this;\n }\n\n // --- Memory Methods ---\n\n memory(memory: ChatMemory): this {\n this._memory = { ...(this._memory || {}), ...memory };\n return this;\n }\n\n remember(facts: string[]): this {\n const existing = this._memory?.facts || [];\n this._memory = { ...(this._memory || {}), facts: [...existing, ...facts] };\n return this;\n }\n\n preferences(prefs: string[]): this {\n this._memory = { ...(this._memory || {}), preferences: prefs };\n return this;\n }\n\n history(messages: ChatMessage[]): this {\n this._memory = { ...(this._memory || {}), history: messages };\n return this;\n }\n\n summarizeHistory(summary: string): this {\n this._memory = { ...(this._memory || {}), summary };\n return this;\n }\n\n // --- Custom System Prompt Parts ---\n\n addSystemPart(part: string): this {\n this._customSystemParts.push(part);\n return this;\n }\n\n raw(content: string): this {\n this._customSystemParts = [content];\n return this;\n }\n\n // --- Build Methods ---\n\n private buildSystemPrompt(): string {\n const parts: string[] = [];\n\n // Persona\n if (this._persona) {\n let personaText = '';\n if (this._persona.name) {\n personaText += `You are ${this._persona.name}`;\n if (this._persona.role) personaText += `, ${this._persona.role}`;\n personaText += '.';\n } else if (this._persona.role) {\n personaText += `You are ${this._persona.role}.`;\n }\n \n if (this._persona.tone) {\n const tones = Array.isArray(this._persona.tone) ? this._persona.tone : [this._persona.tone];\n personaText += ` Your tone is ${tones.join(' and ')}.`;\n }\n \n if (this._persona.expertise) {\n const areas = Array.isArray(this._persona.expertise) ? this._persona.expertise : [this._persona.expertise];\n personaText += ` You have expertise in ${areas.join(', ')}.`;\n }\n \n if (this._persona.personality?.length) {\n personaText += ` You are ${this._persona.personality.join(', ')}.`;\n }\n \n if (this._persona.background) {\n personaText += ` ${this._persona.background}`;\n }\n\n if (this._persona.verbosity) {\n personaText += ` Keep responses ${this._persona.verbosity}.`;\n }\n\n if (this._persona.language) {\n personaText += ` Respond in ${this._persona.language}.`;\n }\n\n if (personaText) parts.push(personaText.trim());\n }\n\n // Context\n if (this._context) {\n const contextParts: string[] = [];\n \n if (this._context.background) {\n contextParts.push(this._context.background);\n }\n if (this._context.domain) {\n contextParts.push(`Domain: ${this._context.domain}`);\n }\n if (this._context.audience) {\n contextParts.push(`Target audience: ${this._context.audience}`);\n }\n if (this._context.purpose) {\n contextParts.push(`Purpose: ${this._context.purpose}`);\n }\n if (this._context.knowledge?.length) {\n contextParts.push(`Known facts:\\n${this._context.knowledge.map(k => `- ${k}`).join('\\n')}`);\n }\n if (this._context.assumptions?.length) {\n contextParts.push(`Assumptions:\\n${this._context.assumptions.map(a => `- ${a}`).join('\\n')}`);\n }\n \n if (contextParts.length) {\n parts.push(`## Context\\n${contextParts.join('\\n')}`);\n }\n }\n\n // Task\n if (this._task) {\n const taskParts: string[] = [];\n \n if (this._task.instruction) {\n taskParts.push(this._task.instruction);\n }\n if (this._task.priority) {\n taskParts.push(`Priority: ${this._task.priority}`);\n }\n if (this._task.steps?.length) {\n taskParts.push(`\\nSteps:\\n${this._task.steps.map((s, i) => `${i + 1}. ${s}`).join('\\n')}`);\n }\n if (this._task.deliverables?.length) {\n taskParts.push(`\\nDeliverables:\\n${this._task.deliverables.map(d => `- ${d}`).join('\\n')}`);\n }\n if (this._task.criteria?.length) {\n taskParts.push(`\\nSuccess criteria:\\n${this._task.criteria.map(c => `- ${c}`).join('\\n')}`);\n }\n if (this._task.antiPatterns?.length) {\n taskParts.push(`\\nAvoid:\\n${this._task.antiPatterns.map(a => `- ${a}`).join('\\n')}`);\n }\n \n if (taskParts.length) {\n parts.push(`## Task\\n${taskParts.join('\\n')}`);\n }\n }\n\n // Constraints\n if (this._context?.constraints?.length) {\n parts.push(`## Constraints\\n${this._context.constraints.map((c, i) => `${i + 1}. ${c}`).join('\\n')}`);\n }\n\n // Examples\n if (this._examples.length) {\n const examplesText = this._examples\n .map((ex, i) => {\n let text = `### Example ${i + 1}\\n**Input:** ${ex.input}\\n**Output:** ${ex.output}`;\n if (ex.explanation) text += `\\n**Explanation:** ${ex.explanation}`;\n return text;\n })\n .join('\\n\\n');\n parts.push(`## Examples\\n${examplesText}`);\n }\n\n // Output format\n if (this._output) {\n const outputParts: string[] = [];\n \n if (this._output.format) {\n switch (this._output.format.type) {\n case 'json':\n if (this._output.format.jsonSchema) {\n outputParts.push(`Respond in valid JSON matching this schema:\\n\\`\\`\\`json\\n${JSON.stringify(this._output.format.jsonSchema.schema, null, 2)}\\n\\`\\`\\``);\n } else {\n outputParts.push('Respond in valid JSON format.');\n }\n break;\n case 'markdown':\n outputParts.push('Format your response using Markdown.');\n break;\n case 'code':\n outputParts.push(`Respond with code${this._output.format.language ? ` in ${this._output.format.language}` : ''}.`);\n break;\n case 'table':\n outputParts.push('Format your response as a table.');\n break;\n }\n }\n if (this._output.length) {\n outputParts.push(`Keep your response ${this._output.length}.`);\n }\n if (this._output.style) {\n const styleMap: Record<OutputStyle, string> = {\n 'prose': 'flowing prose',\n 'bullet-points': 'bullet points',\n 'numbered-list': 'a numbered list',\n 'table': 'a table',\n 'code': 'code',\n 'mixed': 'a mix of prose and lists',\n 'qa': 'Q&A format',\n 'dialogue': 'dialogue format',\n };\n outputParts.push(`Structure as ${styleMap[this._output.style]}.`);\n }\n if (this._output.language) {\n outputParts.push(`Respond in ${this._output.language}.`);\n }\n if (this._output.includeExamples) {\n outputParts.push('Include relevant examples.');\n }\n if (this._output.includeExplanation) {\n outputParts.push('Include clear explanations.');\n }\n if (this._output.includeSources) {\n outputParts.push('Cite your sources.');\n }\n if (this._output.includeConfidence) {\n outputParts.push('Include your confidence level in the answer.');\n }\n \n if (outputParts.length) {\n parts.push(`## Output Format\\n${outputParts.join('\\n')}`);\n }\n }\n\n // Reasoning\n if (this._reasoning) {\n const reasoningParts: string[] = [];\n \n if (this._reasoning.style) {\n const styleInstructions: Record<ReasoningStyle, string> = {\n 'step-by-step': 'Think through this step by step.',\n 'chain-of-thought': 'Use chain-of-thought reasoning to work through the problem.',\n 'tree-of-thought': 'Consider multiple approaches and evaluate each before deciding.',\n 'direct': 'Provide a direct answer.',\n 'analytical': 'Analyze the problem systematically.',\n 'comparative': 'Compare different options or approaches.',\n 'deductive': 'Use deductive reasoning from general principles.',\n 'inductive': 'Use inductive reasoning from specific examples.',\n 'first-principles': 'Reason from first principles, breaking down to fundamental truths.',\n 'analogical': 'Use analogies to explain and reason about the problem.',\n 'devil-advocate': 'Consider and argue against your own conclusions.',\n };\n reasoningParts.push(styleInstructions[this._reasoning.style]);\n }\n if (this._reasoning.showWork) {\n reasoningParts.push('Show your reasoning process.');\n }\n if (this._reasoning.verifyAnswer) {\n reasoningParts.push('Verify your answer before presenting it.');\n }\n if (this._reasoning.considerAlternatives) {\n reasoningParts.push('Consider alternative perspectives and solutions.');\n }\n if (this._reasoning.explainAssumptions) {\n reasoningParts.push('Explicitly state any assumptions you make.');\n }\n \n if (reasoningParts.length) {\n parts.push(`## Reasoning\\n${reasoningParts.join('\\n')}`);\n }\n }\n\n // Memory\n if (this._memory) {\n const memoryParts: string[] = [];\n \n if (this._memory.summary) {\n memoryParts.push(`Previous conversation summary: ${this._memory.summary}`);\n }\n if (this._memory.facts?.length) {\n memoryParts.push(`Known facts:\\n${this._memory.facts.map(f => `- ${f}`).join('\\n')}`);\n }\n if (this._memory.preferences?.length) {\n memoryParts.push(`User preferences:\\n${this._memory.preferences.map(p => `- ${p}`).join('\\n')}`);\n }\n \n if (memoryParts.length) {\n parts.push(`## Memory\\n${memoryParts.join('\\n')}`);\n }\n }\n\n // Custom parts\n if (this._customSystemParts.length) {\n parts.push(...this._customSystemParts);\n }\n\n return parts.join('\\n\\n');\n }\n\n build(): BuiltChatPrompt {\n const systemPrompt = this.buildSystemPrompt();\n \n // Ensure system message is first\n let messages = [...this._messages];\n const hasSystemMessage = messages.some(m => m.role === 'system');\n \n if (systemPrompt && !hasSystemMessage) {\n messages = [{ role: 'system', content: systemPrompt }, ...messages];\n } else if (systemPrompt && hasSystemMessage) {\n // Prepend built system prompt to existing system message\n messages = messages.map(m => \n m.role === 'system' ? { ...m, content: `${systemPrompt}\\n\\n${m.content}` } : m\n );\n }\n\n // Add memory history if present\n if (this._memory?.history) {\n const systemIdx = messages.findIndex(m => m.role === 'system');\n const insertIdx = systemIdx >= 0 ? systemIdx + 1 : 0;\n messages.splice(insertIdx, 0, ...this._memory.history);\n }\n\n // Get user prompt if exists\n const userMessages = messages.filter(m => m.role === 'user');\n const userPrompt = userMessages.length ? userMessages[userMessages.length - 1].content : undefined;\n\n return {\n messages,\n systemPrompt,\n userPrompt,\n metadata: {\n persona: this._persona,\n context: this._context,\n task: this._task,\n output: this._output,\n reasoning: this._reasoning,\n examples: this._examples.length ? this._examples : undefined,\n },\n };\n }\n\n // --- Output Methods ---\n\n toString(): string {\n return this.buildSystemPrompt();\n }\n\n toSystemPrompt(): string {\n return this.buildSystemPrompt();\n }\n\n toMessages(): ChatMessage[] {\n return this.build().messages;\n }\n\n toJSON(): string {\n return JSON.stringify(this.build(), null, 2);\n }\n\n toYAML(): string {\n return objectToYaml(this.build());\n }\n\n toMarkdown(): string {\n const built = this.build();\n const sections: string[] = ['# Chat Prompt\\n'];\n \n sections.push('## System Prompt\\n```\\n' + built.systemPrompt + '\\n```\\n');\n \n if (built.messages.length > 1) {\n sections.push('## Messages\\n');\n for (const msg of built.messages) {\n if (msg.role === 'system') continue;\n sections.push(`**${msg.role.toUpperCase()}${msg.name ? ` (${msg.name})` : ''}:**\\n${msg.content}\\n`);\n }\n }\n \n return sections.join('\\n');\n }\n}\n\n// ============================================================================\n// HELPER FUNCTIONS\n// ============================================================================\n\nfunction objectToYaml(obj: object, indent = 0): string {\n const spaces = ' '.repeat(indent);\n const lines: string[] = [];\n \n for (const [key, value] of Object.entries(obj)) {\n if (value === undefined || value === null) continue;\n \n if (Array.isArray(value)) {\n if (value.length === 0) continue;\n lines.push(`${spaces}${key}:`);\n for (const item of value) {\n if (typeof item === 'object') {\n lines.push(`${spaces} -`);\n lines.push(objectToYaml(item, indent + 2).replace(/^/gm, ' '));\n } else {\n lines.push(`${spaces} - ${item}`);\n }\n }\n } else if (typeof value === 'object') {\n lines.push(`${spaces}${key}:`);\n lines.push(objectToYaml(value, indent + 1));\n } else if (typeof value === 'string' && value.includes('\\n')) {\n lines.push(`${spaces}${key}: |`);\n for (const line of value.split('\\n')) {\n lines.push(`${spaces} ${line}`);\n }\n } else {\n lines.push(`${spaces}${key}: ${value}`);\n }\n }\n \n return lines.join('\\n');\n}\n\n// ============================================================================\n// FACTORY FUNCTION\n// ============================================================================\n\n/**\n * Create a new chat prompt builder\n */\nexport function chat(): ChatPromptBuilder {\n return new ChatPromptBuilder();\n}\n\n// ============================================================================\n// PRESET BUILDERS\n// ============================================================================\n\nexport const chatPresets = {\n /**\n * Code assistant preset\n */\n coder: (language?: string) => {\n const c = chat()\n .role(\"expert software developer\")\n .expertise(\"coding\")\n .tone(\"technical\");\n \n if (language) {\n c.context(`Programming language: ${language}`);\n }\n \n return c;\n },\n\n /**\n * Writing assistant preset\n */\n writer: (style?: 'creative' | 'professional' | 'academic') => {\n const c = chat()\n .role(\"skilled writer and editor\")\n .expertise(\"writing\");\n \n if (style) {\n c.tone(style === 'creative' ? 'creative' : style === 'academic' ? 'academic' : 'professional');\n }\n \n return c;\n },\n\n /**\n * Teacher/tutor preset\n */\n tutor: (subject?: string) => {\n const c = chat()\n .role(\"patient and knowledgeable tutor\")\n .expertise(\"teaching\")\n .tone(['friendly', 'empathetic'])\n .stepByStep()\n .withExamples();\n \n if (subject) {\n c.domain(subject);\n }\n \n return c;\n },\n\n /**\n * Analyst preset\n */\n analyst: () => {\n return chat()\n .role(\"data analyst and researcher\")\n .expertise(\"analysis\")\n .tone(\"analytical\")\n .chainOfThought()\n .detailed()\n .withSources();\n },\n\n /**\n * Socratic dialogue preset\n */\n socratic: () => {\n return chat()\n .role(\"Socratic philosopher and teacher\")\n .tone(\"socratic\")\n .reasoning({ style: 'deductive', showWork: true })\n .avoid([\"Give direct answers\", \"Lecture\", \"Be condescending\"]);\n },\n\n /**\n * Critic preset\n */\n critic: () => {\n return chat()\n .role(\"constructive critic\")\n .tone(['analytical', 'professional'])\n .devilsAdvocate()\n .detailed()\n .avoid([\"Be harsh\", \"Dismiss ideas without explanation\"]);\n },\n\n /**\n * Brainstormer preset\n */\n brainstormer: () => {\n return chat()\n .role(\"creative brainstorming partner\")\n .tone(['creative', 'encouraging'])\n .expertise(\"creative\")\n .considerAlternatives()\n .avoid([\"Dismiss ideas\", \"Be negative\", \"Limit creativity\"]);\n },\n\n /**\n * JSON response preset\n */\n jsonResponder: (schemaName: string, schema: Record<string, unknown>) => {\n return chat()\n .role(\"data processing assistant\")\n .tone(\"concise\")\n .jsonSchema(schemaName, schema)\n .avoid([\"Include markdown\", \"Add explanations outside JSON\", \"Include code fences\"]);\n },\n\n /**\n * Summarizer preset\n */\n summarizer: (length: OutputLength = 'brief') => {\n return chat()\n .role(\"expert summarizer\")\n .expertise(\"analysis\")\n .tone(\"concise\")\n .length(length)\n .task(\"Summarize the provided content, preserving key information\");\n },\n\n /**\n * Translator preset\n */\n translator: (targetLanguage: string) => {\n return chat()\n .role(\"professional translator\")\n .expertise(\"languages\")\n .responseLanguage(targetLanguage)\n .avoid([\"Add commentary\", \"Change meaning\", \"Omit content\"]);\n },\n};\n","/**\n * Prompt Builder - A fluent DSL for creating structured prompts\n * \n * @example\n * ```ts\n * import { builder } from 'prompts.chat';\n * \n * const prompt = builder()\n * .role(\"Senior TypeScript Developer\")\n * .context(\"You are helping review code\")\n * .task(\"Analyze the following code for bugs\")\n * .constraints([\"Be concise\", \"Focus on critical issues\"])\n * .output(\"JSON with { bugs: [], suggestions: [] }\")\n * .variable(\"code\", { required: true })\n * .build();\n * ```\n */\n\nexport interface PromptVariable {\n name: string;\n description?: string;\n required?: boolean;\n defaultValue?: string;\n}\n\nexport interface BuiltPrompt {\n content: string;\n variables: PromptVariable[];\n metadata: {\n role?: string;\n context?: string;\n task?: string;\n constraints?: string[];\n outputFormat?: string;\n examples?: Array<{ input: string; output: string }>;\n };\n}\n\nexport class PromptBuilder {\n private _role?: string;\n private _context?: string;\n private _task?: string;\n private _constraints: string[] = [];\n private _outputFormat?: string;\n private _examples: Array<{ input: string; output: string }> = [];\n private _variables: PromptVariable[] = [];\n private _customSections: Array<{ title: string; content: string }> = [];\n private _rawContent?: string;\n\n /**\n * Set the role/persona for the AI\n */\n role(role: string): this {\n this._role = role;\n return this;\n }\n\n /**\n * Alias for role()\n */\n persona(persona: string): this {\n return this.role(persona);\n }\n\n /**\n * Set the context/background information\n */\n context(context: string): this {\n this._context = context;\n return this;\n }\n\n /**\n * Alias for context()\n */\n background(background: string): this {\n return this.context(background);\n }\n\n /**\n * Set the main task/instruction\n */\n task(task: string): this {\n this._task = task;\n return this;\n }\n\n /**\n * Alias for task()\n */\n instruction(instruction: string): this {\n return this.task(instruction);\n }\n\n /**\n * Add constraints/rules the AI should follow\n */\n constraints(constraints: string[]): this {\n this._constraints = [...this._constraints, ...constraints];\n return this;\n }\n\n /**\n * Add a single constraint\n */\n constraint(constraint: string): this {\n this._constraints.push(constraint);\n return this;\n }\n\n /**\n * Alias for constraints()\n */\n rules(rules: string[]): this {\n return this.constraints(rules);\n }\n\n /**\n * Set the expected output format\n */\n output(format: string): this {\n this._outputFormat = format;\n return this;\n }\n\n /**\n * Alias for output()\n */\n format(format: string): this {\n return this.output(format);\n }\n\n /**\n * Add an example input/output pair\n */\n example(input: string, output: string): this {\n this._examples.push({ input, output });\n return this;\n }\n\n /**\n * Add multiple examples\n */\n examples(examples: Array<{ input: string; output: string }>): this {\n this._examples = [...this._examples, ...examples];\n return this;\n }\n\n /**\n * Define a variable placeholder\n */\n variable(\n name: string, \n options: { description?: string; required?: boolean; defaultValue?: string } = {}\n ): this {\n this._variables.push({\n name,\n description: options.description,\n required: options.required ?? true,\n defaultValue: options.defaultValue,\n });\n return this;\n }\n\n /**\n * Add a custom section\n */\n section(title: string, content: string): this {\n this._customSections.push({ title, content });\n return this;\n }\n\n /**\n * Set raw content (bypasses structured building)\n */\n raw(content: string): this {\n this._rawContent = content;\n return this;\n }\n\n /**\n * Build the final prompt\n */\n build(): BuiltPrompt {\n if (this._rawContent) {\n return {\n content: this._rawContent,\n variables: this._variables,\n metadata: {},\n };\n }\n\n const sections: string[] = [];\n\n // Role section\n if (this._role) {\n sections.push(`You are ${this._role}.`);\n }\n\n // Context section\n if (this._context) {\n sections.push(`\\n## Context\\n${this._context}`);\n }\n\n // Task section\n if (this._task) {\n sections.push(`\\n## Task\\n${this._task}`);\n }\n\n // Constraints section\n if (this._constraints.length > 0) {\n const constraintsList = this._constraints\n .map((c, i) => `${i + 1}. ${c}`)\n .join('\\n');\n sections.push(`\\n## Constraints\\n${constraintsList}`);\n }\n\n // Output format section\n if (this._outputFormat) {\n sections.push(`\\n## Output Format\\n${this._outputFormat}`);\n }\n\n // Examples section\n if (this._examples.length > 0) {\n const examplesText = this._examples\n .map((e, i) => `### Example ${i + 1}\\n**Input:** ${e.input}\\n**Output:** ${e.output}`)\n .join('\\n\\n');\n sections.push(`\\n## Examples\\n${examplesText}`);\n }\n\n // Custom sections\n for (const section of this._customSections) {\n sections.push(`\\n## ${section.title}\\n${section.content}`);\n }\n\n // Variables section (as placeholders info)\n if (this._variables.length > 0) {\n const varsText = this._variables\n .map(v => {\n const placeholder = v.defaultValue \n ? `\\${${v.name}:${v.defaultValue}}`\n : `\\${${v.name}}`;\n const desc = v.description ? ` - ${v.description}` : '';\n const req = v.required ? ' (required)' : ' (optional)';\n return `- ${placeholder}${desc}${req}`;\n })\n .join('\\n');\n sections.push(`\\n## Variables\\n${varsText}`);\n }\n\n return {\n content: sections.join('\\n').trim(),\n variables: this._variables,\n metadata: {\n role: this._role,\n context: this._context,\n task: this._task,\n constraints: this._constraints.length > 0 ? this._constraints : undefined,\n outputFormat: this._outputFormat,\n examples: this._examples.length > 0 ? this._examples : undefined,\n },\n };\n }\n\n /**\n * Build and return only the content string\n */\n toString(): string {\n return this.build().content;\n }\n}\n\n/**\n * Create a new prompt builder\n */\nexport function builder(): PromptBuilder {\n return new PromptBuilder();\n}\n\n/**\n * Create a prompt builder from an existing prompt\n */\nexport function fromPrompt(content: string): PromptBuilder {\n return new PromptBuilder().raw(content);\n}\n\n// Re-export media builders\nexport { image, ImagePromptBuilder } from './media';\nexport type { \n BuiltImagePrompt, \n ImageSubject, \n ImageCamera, \n ImageLighting, \n ImageComposition,\n ImageStyle,\n ImageColor,\n ImageEnvironment,\n ImageTechnical,\n CameraAngle,\n ShotType,\n LensType,\n LightingType,\n TimeOfDay,\n ArtStyle,\n ColorPalette,\n Mood,\n AspectRatio,\n OutputFormat,\n} from './media';\n\nexport { video, VideoPromptBuilder } from './video';\nexport type { \n BuiltVideoPrompt,\n VideoScene,\n VideoSubject,\n VideoCamera,\n VideoLighting,\n VideoAction,\n VideoMotion,\n VideoStyle,\n VideoColor,\n VideoAudio,\n VideoTechnical,\n VideoShot,\n} from './video';\n\nexport { audio, AudioPromptBuilder } from './audio';\nexport type {\n BuiltAudioPrompt,\n AudioGenre,\n AudioMood,\n AudioTempo,\n AudioVocals,\n AudioInstrumentation,\n AudioStructure,\n AudioProduction,\n AudioTechnical,\n MusicGenre,\n Instrument,\n VocalStyle,\n TempoMarking,\n TimeSignature,\n MusicalKey,\n SongSection,\n ProductionStyle,\n} from './audio';\n\n// Re-export chat builder\nexport { chat, ChatPromptBuilder, chatPresets } from './chat';\nexport type {\n BuiltChatPrompt,\n ChatMessage,\n ChatPersona,\n ChatContext,\n ChatTask,\n ChatOutput,\n ChatReasoning,\n ChatMemory,\n ChatExample,\n MessageRole,\n ResponseFormat,\n ResponseFormatType,\n JsonSchema,\n PersonaTone,\n PersonaExpertise,\n ReasoningStyle,\n OutputLength,\n OutputStyle,\n} from './chat';\n\n// Pre-built templates\nexport const templates = {\n /**\n * Create a code review prompt\n */\n codeReview: (options: { language?: string; focus?: string[] } = {}) => {\n const b = builder()\n .role(\"expert code reviewer\")\n .task(\"Review the provided code and identify issues, improvements, and best practices.\")\n .variable(\"code\", { required: true, description: \"The code to review\" });\n\n if (options.language) {\n b.context(`You are reviewing ${options.language} code.`);\n }\n\n if (options.focus && options.focus.length > 0) {\n b.constraints(options.focus.map(f => `Focus on ${f}`));\n }\n\n return b.output(\"Provide a structured review with: issues found, suggestions, and overall assessment.\");\n },\n\n /**\n * Create a translation prompt\n */\n translation: (from: string, to: string) => {\n return builder()\n .role(`professional translator fluent in ${from} and ${to}`)\n .task(`Translate the following text from ${from} to ${to}.`)\n .constraints([\n \"Maintain the original meaning and tone\",\n \"Use natural, idiomatic expressions in the target language\",\n \"Preserve formatting and structure\",\n ])\n .variable(\"text\", { required: true, description: \"Text to translate\" });\n },\n\n /**\n * Create a summarization prompt\n */\n summarize: (options: { maxLength?: number; style?: 'bullet' | 'paragraph' } = {}) => {\n const b = builder()\n .role(\"expert summarizer\")\n .task(\"Summarize the following content concisely while preserving key information.\")\n .variable(\"content\", { required: true, description: \"Content to summarize\" });\n\n if (options.maxLength) {\n b.constraint(`Keep the summary under ${options.maxLength} words`);\n }\n\n if (options.style === 'bullet') {\n b.output(\"Provide the summary as bullet points\");\n }\n\n return b;\n },\n\n /**\n * Create a Q&A prompt\n */\n qa: (context?: string) => {\n const b = builder()\n .role(\"helpful assistant\")\n .task(\"Answer the question based on the provided context.\")\n .variable(\"question\", { required: true, description: \"The question to answer\" });\n\n if (context) {\n b.context(context);\n } else {\n b.variable(\"context\", { required: false, description: \"Additional context\" });\n }\n\n return b.constraints([\n \"Be accurate and concise\",\n \"If you don't know the answer, say so\",\n \"Cite relevant parts of the context if applicable\",\n ]);\n },\n};\n"],"mappings":";;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAgCA,IAAM,WAA4B;AAAA;AAAA,EAEhC;AAAA,IACE,SAAS;AAAA,IACT,OAAO;AAAA,IACP,aAAa,CAAC,MAAM,EAAE,CAAC,EAAE,KAAK;AAAA,IAC9B,gBAAgB,CAAC,MAAM,EAAE,CAAC,GAAG,KAAK;AAAA,EACpC;AAAA;AAAA,EAEA;AAAA,IACE,SAAS;AAAA,IACT,OAAO;AAAA,IACP,aAAa,CAAC,MAAM,EAAE,CAAC,EAAE,KAAK;AAAA,IAC9B,gBAAgB,CAAC,MAAM,EAAE,CAAC,GAAG,KAAK;AAAA,EACpC;AAAA;AAAA,EAEA;AAAA,IACE,SAAS;AAAA,IACT,OAAO;AAAA,IACP,aAAa,CAAC,MAAM,EAAE,CAAC,EAAE,KAAK;AAAA,EAChC;AAAA;AAAA,EAEA;AAAA,IACE,SAAS;AAAA,IACT,OAAO;AAAA,IACP,aAAa,CAAC,MAAM,EAAE,CAAC,EAAE,KAAK;AAAA,EAChC;AAAA;AAAA,EAEA;AAAA,IACE,SAAS;AAAA,IACT,OAAO;AAAA,IACP,aAAa,CAAC,MAAM,EAAE,CAAC,EAAE,KAAK;AAAA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,"sources":["../src/variables/index.ts","../src/similarity/index.ts","../src/quality/index.ts","../src/parser/index.ts","../src/builder/media.ts","../src/builder/video.ts","../src/builder/audio.ts","../src/builder/chat.ts","../src/builder/index.ts"],"sourcesContent":["/**\n * Variable Detection Utility\n * Detects common variable-like patterns in text that could be converted\n * to our supported format: ${variableName} or ${variableName:default}\n */\n\nexport interface DetectedVariable {\n original: string;\n name: string;\n defaultValue?: string;\n pattern: VariablePattern;\n startIndex: number;\n endIndex: number;\n}\n\nexport type VariablePattern = \n | \"double_bracket\" // [[name]] or [[ name ]]\n | \"double_curly\" // {{name}} or {{ name }}\n | \"single_bracket\" // [NAME] or [name]\n | \"single_curly\" // {NAME} or {name}\n | \"angle_bracket\" // <NAME> or <name>\n | \"percent\" // %NAME% or %name%\n | \"dollar_curly\"; // ${name} (already our format)\n\ninterface PatternConfig {\n pattern: VariablePattern;\n regex: RegExp;\n extractName: (match: RegExpExecArray) => string;\n extractDefault?: (match: RegExpExecArray) => string | undefined;\n}\n\n// Patterns to detect, ordered by specificity (more specific first)\nconst PATTERNS: PatternConfig[] = [\n // Double bracket: [[name]] or [[ name ]] or [[name: default]]\n {\n pattern: \"double_bracket\",\n regex: /\\[\\[\\s*([a-zA-Z_][a-zA-Z0-9_\\s]*?)(?:\\s*:\\s*([^\\]]*?))?\\s*\\]\\]/g,\n extractName: (m) => m[1].trim(),\n extractDefault: (m) => m[2]?.trim(),\n },\n // Double curly: {{name}} or {{ name }} or {{name: default}}\n {\n pattern: \"double_curly\",\n regex: /\\{\\{\\s*([a-zA-Z_][a-zA-Z0-9_\\s]*?)(?:\\s*:\\s*([^}]*?))?\\s*\\}\\}/g,\n extractName: (m) => m[1].trim(),\n extractDefault: (m) => m[2]?.trim(),\n },\n // Our supported format (to exclude from warnings)\n {\n pattern: \"dollar_curly\",\n regex: /\\$\\{([a-zA-Z_][a-zA-Z0-9_\\s]*?)(?::([^}]*))?\\}/g,\n extractName: (m) => m[1].trim(),\n },\n // Single bracket with uppercase or placeholder-like: [NAME] or [Your Name]\n {\n pattern: \"single_bracket\",\n regex: /\\[([A-Z][A-Z0-9_\\s]*|[A-Za-z][a-zA-Z0-9_]*(?:\\s+[A-Za-z][a-zA-Z0-9_]*)*)\\]/g,\n extractName: (m) => m[1].trim(),\n },\n // Single curly with uppercase: {NAME} or {Your Name}\n {\n pattern: \"single_curly\",\n regex: /\\{([A-Z][A-Z0-9_\\s]*|[A-Za-z][a-zA-Z0-9_]*(?:\\s+[A-Za-z][a-zA-Z0-9_]*)*)\\}/g,\n extractName: (m) => m[1].trim(),\n },\n // Angle brackets: <NAME> or <name>\n {\n pattern: \"angle_bracket\",\n regex: /<([A-Z][A-Z0-9_\\s]*|[a-zA-Z_][a-zA-Z0-9_\\s]*)>/g,\n extractName: (m) => m[1].trim(),\n },\n // Percent signs: %NAME% or %name%\n {\n pattern: \"percent\",\n regex: /%([a-zA-Z_][a-zA-Z0-9_]*)%/g,\n extractName: (m) => m[1].trim(),\n },\n];\n\n// Common false positives to ignore\nconst FALSE_POSITIVES = new Set([\n // HTML/XML common tags\n \"div\", \"span\", \"p\", \"a\", \"br\", \"hr\", \"img\", \"input\", \"button\",\n \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\", \"ul\", \"ol\", \"li\", \"table\",\n \"tr\", \"td\", \"th\", \"thead\", \"tbody\", \"form\", \"label\", \"select\",\n \"option\", \"textarea\", \"script\", \"style\", \"link\", \"meta\", \"head\",\n \"body\", \"html\", \"section\", \"article\", \"nav\", \"header\", \"footer\",\n \"main\", \"aside\", \"figure\", \"figcaption\", \"strong\", \"em\", \"code\",\n \"pre\", \"blockquote\", \"cite\", \"abbr\", \"address\", \"b\", \"i\", \"u\",\n // Common programming constructs\n \"if\", \"else\", \"for\", \"while\", \"switch\", \"case\", \"break\", \"return\",\n \"function\", \"class\", \"const\", \"let\", \"var\", \"import\", \"export\",\n \"default\", \"try\", \"catch\", \"finally\", \"throw\", \"new\", \"this\",\n \"null\", \"undefined\", \"true\", \"false\", \"typeof\", \"instanceof\",\n // JSON structure keywords (when in context)\n \"type\", \"id\", \"key\", \"value\", \"data\", \"items\", \"properties\",\n]);\n\n/**\n * Check if we're inside a JSON string context\n */\nfunction isInsideJsonString(text: string, index: number): boolean {\n let inString = false;\n for (let i = 0; i < index; i++) {\n if (text[i] === '\"' && (i === 0 || text[i - 1] !== '\\\\')) {\n inString = !inString;\n }\n }\n return inString;\n}\n\n/**\n * Detect variable-like patterns in text\n * Returns detected variables that are NOT in our supported format\n */\nexport function detectVariables(text: string): DetectedVariable[] {\n const detected: DetectedVariable[] = [];\n const seenRanges: Array<[number, number]> = [];\n \n // Track our supported format positions to exclude them\n const supportedVars = new Set<string>();\n const dollarCurlyPattern = /\\$\\{([a-zA-Z_][a-zA-Z0-9_\\s]*?)(?::([^}]*))?\\}/g;\n let match: RegExpExecArray | null;\n \n while ((match = dollarCurlyPattern.exec(text)) !== null) {\n seenRanges.push([match.index, match.index + match[0].length]);\n supportedVars.add(match[0]);\n }\n \n // Check each pattern\n for (const config of PATTERNS) {\n // Skip our supported format pattern for detection\n if (config.pattern === \"dollar_curly\") continue;\n \n const regex = new RegExp(config.regex.source, config.regex.flags);\n \n while ((match = regex.exec(text)) !== null) {\n const startIndex = match.index;\n const endIndex = startIndex + match[0].length;\n \n // Check if this range overlaps with any already detected range\n const overlaps = seenRanges.some(\n ([start, end]) => \n (startIndex >= start && startIndex < end) ||\n (endIndex > start && endIndex <= end)\n );\n \n if (overlaps) continue;\n \n const name = config.extractName(match);\n \n // Skip false positives\n if (FALSE_POSITIVES.has(name.toLowerCase())) continue;\n \n // Skip very short names (likely not variables)\n if (name.length < 2) continue;\n \n // For angle brackets, be more strict\n if (config.pattern === \"angle_bracket\") {\n if (!/^[A-Z]/.test(name) && !name.includes(\" \")) continue;\n }\n \n // For single curly/bracket in JSON context, be more careful\n if (\n (config.pattern === \"single_curly\" || config.pattern === \"single_bracket\") &&\n isInsideJsonString(text, startIndex)\n ) {\n if (!/^[A-Z]/.test(name) && !name.includes(\" \")) continue;\n }\n \n const defaultValue = config.extractDefault?.(match);\n \n detected.push({\n original: match[0],\n name,\n defaultValue,\n pattern: config.pattern,\n startIndex,\n endIndex,\n });\n \n seenRanges.push([startIndex, endIndex]);\n }\n }\n \n // Sort by position and remove duplicates\n return detected\n .sort((a, b) => a.startIndex - b.startIndex)\n .filter((v, i, arr) => \n i === 0 || v.original !== arr[i - 1].original || v.startIndex !== arr[i - 1].startIndex\n );\n}\n\n/**\n * Convert a detected variable to our supported format\n */\nexport function convertToSupportedFormat(variable: DetectedVariable): string {\n // Normalize name: lowercase, replace spaces with underscores\n const normalizedName = variable.name\n .toLowerCase()\n .replace(/\\s+/g, \"_\")\n .replace(/[^a-z0-9_]/g, \"\");\n \n if (variable.defaultValue) {\n return `\\${${normalizedName}:${variable.defaultValue}}`;\n }\n \n return `\\${${normalizedName}}`;\n}\n\n/**\n * Convert all detected variables in text to our supported format\n */\nexport function convertAllVariables(text: string): string {\n const detected = detectVariables(text);\n \n if (detected.length === 0) return text;\n \n // Sort by position descending to replace from end to start\n const sorted = [...detected].sort((a, b) => b.startIndex - a.startIndex);\n \n let result = text;\n for (const variable of sorted) {\n const converted = convertToSupportedFormat(variable);\n result = result.slice(0, variable.startIndex) + converted + result.slice(variable.endIndex);\n }\n \n return result;\n}\n\n/**\n * Alias for convertAllVariables - normalizes all variable formats to ${var}\n */\nexport const normalize = convertAllVariables;\n\n/**\n * Alias for detectVariables\n */\nexport const detect = detectVariables;\n\n/**\n * Get a human-readable pattern description\n */\nexport function getPatternDescription(pattern: VariablePattern): string {\n switch (pattern) {\n case \"double_bracket\": return \"[[...]]\";\n case \"double_curly\": return \"{{...}}\";\n case \"single_bracket\": return \"[...]\";\n case \"single_curly\": return \"{...}\";\n case \"angle_bracket\": return \"<...>\";\n case \"percent\": return \"%...%\";\n case \"dollar_curly\": return \"${...}\";\n }\n}\n\n/**\n * Extract variables from our supported ${var} or ${var:default} format\n */\nexport function extractVariables(text: string): Array<{ name: string; defaultValue?: string }> {\n const regex = /\\$\\{([a-zA-Z_][a-zA-Z0-9_\\s]*?)(?::([^}]*))?\\}/g;\n const variables: Array<{ name: string; defaultValue?: string }> = [];\n let match: RegExpExecArray | null;\n \n while ((match = regex.exec(text)) !== null) {\n variables.push({\n name: match[1].trim(),\n defaultValue: match[2]?.trim(),\n });\n }\n \n return variables;\n}\n\n/**\n * Compile a prompt template with variable values\n */\nexport function compile(\n template: string, \n values: Record<string, string>,\n options: { useDefaults?: boolean } = {}\n): string {\n const { useDefaults = true } = options;\n \n return template.replace(\n /\\$\\{([a-zA-Z_][a-zA-Z0-9_\\s]*?)(?::([^}]*))?\\}/g,\n (match, name, defaultValue) => {\n const trimmedName = name.trim();\n if (trimmedName in values) {\n return values[trimmedName];\n }\n if (useDefaults && defaultValue !== undefined) {\n return defaultValue.trim();\n }\n return match; // Keep original if no value and no default\n }\n );\n}\n","/**\n * Content similarity utilities for duplicate detection\n */\n\n/**\n * Normalize content for comparison by:\n * - Removing variables (${...} patterns)\n * - Converting to lowercase\n * - Removing extra whitespace\n * - Removing punctuation\n */\nexport function normalizeContent(content: string): string {\n return content\n // Remove variables like ${variable} or ${variable:default}\n .replace(/\\$\\{[^}]+\\}/g, \"\")\n // Remove common placeholder patterns like [placeholder] or <placeholder>\n .replace(/\\[[^\\]]+\\]/g, \"\")\n .replace(/<[^>]+>/g, \"\")\n // Convert to lowercase\n .toLowerCase()\n // Remove punctuation\n .replace(/[^\\w\\s]/g, \"\")\n // Normalize whitespace\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\n/**\n * Calculate Jaccard similarity between two strings\n * Returns a value between 0 (completely different) and 1 (identical)\n */\nfunction jaccardSimilarity(str1: string, str2: string): number {\n const set1 = new Set(str1.split(\" \").filter(Boolean));\n const set2 = new Set(str2.split(\" \").filter(Boolean));\n \n if (set1.size === 0 && set2.size === 0) return 1;\n if (set1.size === 0 || set2.size === 0) return 0;\n \n const intersection = new Set([...set1].filter(x => set2.has(x)));\n const union = new Set([...set1, ...set2]);\n \n return intersection.size / union.size;\n}\n\n/**\n * Calculate n-gram similarity for better sequence matching\n * Uses trigrams (3-character sequences) by default\n */\nfunction ngramSimilarity(str1: string, str2: string, n: number = 3): number {\n const getNgrams = (str: string): Set<string> => {\n const ngrams = new Set<string>();\n const padded = \" \".repeat(n - 1) + str + \" \".repeat(n - 1);\n for (let i = 0; i <= padded.length - n; i++) {\n ngrams.add(padded.slice(i, i + n));\n }\n return ngrams;\n };\n \n const ngrams1 = getNgrams(str1);\n const ngrams2 = getNgrams(str2);\n \n if (ngrams1.size === 0 && ngrams2.size === 0) return 1;\n if (ngrams1.size === 0 || ngrams2.size === 0) return 0;\n \n const intersection = new Set([...ngrams1].filter(x => ngrams2.has(x)));\n const union = new Set([...ngrams1, ...ngrams2]);\n \n return intersection.size / union.size;\n}\n\n/**\n * Combined similarity score using multiple algorithms\n * Returns a value between 0 (completely different) and 1 (identical)\n */\nexport function calculateSimilarity(content1: string, content2: string): number {\n const normalized1 = normalizeContent(content1);\n const normalized2 = normalizeContent(content2);\n \n // Exact match after normalization\n if (normalized1 === normalized2) return 1;\n \n // Empty content edge case\n if (!normalized1 || !normalized2) return 0;\n \n // Combine Jaccard (word-level) and n-gram (character-level) similarities\n const jaccard = jaccardSimilarity(normalized1, normalized2);\n const ngram = ngramSimilarity(normalized1, normalized2);\n \n // Weighted average: 60% Jaccard (word overlap), 40% n-gram (sequence similarity)\n return jaccard * 0.6 + ngram * 0.4;\n}\n\n/**\n * Alias for calculateSimilarity\n */\nexport const calculate = calculateSimilarity;\n\n/**\n * Check if two contents are similar enough to be considered duplicates\n * Default threshold is 0.85 (85% similar)\n */\nexport function isSimilarContent(\n content1: string, \n content2: string, \n threshold: number = 0.85\n): boolean {\n return calculateSimilarity(content1, content2) >= threshold;\n}\n\n/**\n * Alias for isSimilarContent\n */\nexport const isDuplicate = isSimilarContent;\n\n/**\n * Get normalized content hash for database indexing/comparison\n * This is a simple hash for quick lookups before full similarity check\n */\nexport function getContentFingerprint(content: string): string {\n const normalized = normalizeContent(content);\n // Take first 500 chars of normalized content as fingerprint\n return normalized.slice(0, 500);\n}\n\n/**\n * Find duplicates in an array of prompts\n * Returns groups of similar prompts\n */\nexport function findDuplicates<T extends { content: string }>(\n prompts: T[],\n threshold: number = 0.85\n): T[][] {\n const groups: T[][] = [];\n const used = new Set<number>();\n\n for (let i = 0; i < prompts.length; i++) {\n if (used.has(i)) continue;\n\n const group: T[] = [prompts[i]];\n used.add(i);\n\n for (let j = i + 1; j < prompts.length; j++) {\n if (used.has(j)) continue;\n\n if (isSimilarContent(prompts[i].content, prompts[j].content, threshold)) {\n group.push(prompts[j]);\n used.add(j);\n }\n }\n\n if (group.length > 1) {\n groups.push(group);\n }\n }\n\n return groups;\n}\n\n/**\n * Deduplicate an array of prompts, keeping the first occurrence\n */\nexport function deduplicate<T extends { content: string }>(\n prompts: T[],\n threshold: number = 0.85\n): T[] {\n const result: T[] = [];\n\n for (const prompt of prompts) {\n const isDupe = result.some(existing => \n isSimilarContent(existing.content, prompt.content, threshold)\n );\n\n if (!isDupe) {\n result.push(prompt);\n }\n }\n\n return result;\n}\n","/**\n * Prompt Quality Checker - Local validation for prompt quality\n * \n * @example\n * ```ts\n * import { quality } from 'prompts.chat';\n * \n * const result = quality.check(\"Act as a developer...\");\n * console.log(result.score); // 0.85\n * console.log(result.issues); // []\n * ```\n */\n\nexport interface QualityIssue {\n type: 'error' | 'warning' | 'suggestion';\n code: string;\n message: string;\n position?: { start: number; end: number };\n}\n\nexport interface QualityResult {\n valid: boolean;\n score: number; // 0-1\n issues: QualityIssue[];\n stats: {\n characterCount: number;\n wordCount: number;\n sentenceCount: number;\n variableCount: number;\n hasRole: boolean;\n hasTask: boolean;\n hasConstraints: boolean;\n hasExamples: boolean;\n };\n}\n\n// Minimum thresholds\nconst MIN_CHAR_COUNT = 20;\nconst MIN_WORD_COUNT = 5;\nconst OPTIMAL_MIN_WORDS = 20;\nconst OPTIMAL_MAX_WORDS = 2000;\n\n/**\n * Check if text looks like gibberish\n */\nfunction isGibberish(text: string): boolean {\n // Check for repeated characters\n if (/(.)\\1{4,}/.test(text)) return true;\n \n // Check for keyboard patterns\n const keyboardPatterns = ['qwerty', 'asdfgh', 'zxcvbn', 'qwertz', 'azerty'];\n const lower = text.toLowerCase();\n if (keyboardPatterns.some(p => lower.includes(p))) return true;\n \n // Check consonant/vowel ratio (gibberish often has unusual ratios)\n const vowels = (text.match(/[aeiouAEIOU]/g) || []).length;\n const consonants = (text.match(/[bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]/g) || []).length;\n \n if (consonants > 0 && vowels / consonants < 0.1) return true;\n \n return false;\n}\n\n/**\n * Detect common prompt patterns\n */\nfunction detectPatterns(text: string): {\n hasRole: boolean;\n hasTask: boolean;\n hasConstraints: boolean;\n hasExamples: boolean;\n} {\n const lower = text.toLowerCase();\n \n return {\n hasRole: /\\b(act as|you are|imagine you|pretend to be|role:|persona:)\\b/i.test(text),\n hasTask: /\\b(your task|you (will|should|must)|please|help me|i need|i want you to)\\b/i.test(text),\n hasConstraints: /\\b(do not|don't|never|always|must|should not|avoid|only|limit)\\b/i.test(text) ||\n /\\b(rule|constraint|requirement|guideline)\\b/i.test(lower),\n hasExamples: /\\b(example|for instance|such as|e\\.g\\.|like this)\\b/i.test(lower) ||\n /```[\\s\\S]*```/.test(text),\n };\n}\n\n/**\n * Count variables in the prompt\n */\nfunction countVariables(text: string): number {\n // Match various variable formats\n const patterns = [\n /\\$\\{[^}]+\\}/g, // ${var}\n /\\{\\{[^}]+\\}\\}/g, // {{var}}\n /\\[\\[[^\\]]+\\]\\]/g, // [[var]]\n /\\[[A-Z][A-Z0-9_\\s]*\\]/g, // [VAR]\n ];\n \n let count = 0;\n for (const pattern of patterns) {\n const matches = text.match(pattern);\n if (matches) count += matches.length;\n }\n \n return count;\n}\n\n/**\n * Calculate quality score based on various factors\n */\nfunction calculateScore(\n stats: QualityResult['stats'],\n issues: QualityIssue[]\n): number {\n let score = 1.0;\n \n // Deduct for errors\n const errors = issues.filter(i => i.type === 'error').length;\n const warnings = issues.filter(i => i.type === 'warning').length;\n \n score -= errors * 0.2;\n score -= warnings * 0.05;\n \n // Bonus for good structure\n if (stats.hasRole) score += 0.05;\n if (stats.hasTask) score += 0.05;\n if (stats.hasConstraints) score += 0.03;\n if (stats.hasExamples) score += 0.05;\n \n // Penalty for being too short\n if (stats.wordCount < OPTIMAL_MIN_WORDS) {\n score -= 0.1 * (1 - stats.wordCount / OPTIMAL_MIN_WORDS);\n }\n \n // Slight penalty for being very long\n if (stats.wordCount > OPTIMAL_MAX_WORDS) {\n score -= 0.05;\n }\n \n // Bonus for having variables (indicates reusability)\n if (stats.variableCount > 0) {\n score += 0.05;\n }\n \n return Math.max(0, Math.min(1, score));\n}\n\n/**\n * Check prompt quality locally (no API needed)\n */\nexport function check(prompt: string): QualityResult {\n const issues: QualityIssue[] = [];\n const trimmed = prompt.trim();\n \n // Basic stats\n const characterCount = trimmed.length;\n const words = trimmed.split(/\\s+/).filter(w => w.length > 0);\n const wordCount = words.length;\n const sentenceCount = (trimmed.match(/[.!?]+/g) || []).length || 1;\n const variableCount = countVariables(trimmed);\n const patterns = detectPatterns(trimmed);\n \n // Check for empty or too short\n if (characterCount === 0) {\n issues.push({\n type: 'error',\n code: 'EMPTY',\n message: 'Prompt is empty',\n });\n } else if (characterCount < MIN_CHAR_COUNT) {\n issues.push({\n type: 'error',\n code: 'TOO_SHORT',\n message: `Prompt is too short (${characterCount} chars, minimum ${MIN_CHAR_COUNT})`,\n });\n }\n \n if (wordCount > 0 && wordCount < MIN_WORD_COUNT) {\n issues.push({\n type: 'warning',\n code: 'FEW_WORDS',\n message: `Prompt has very few words (${wordCount} words, recommended ${OPTIMAL_MIN_WORDS}+)`,\n });\n }\n \n // Check for gibberish\n if (isGibberish(trimmed)) {\n issues.push({\n type: 'error',\n code: 'GIBBERISH',\n message: 'Prompt appears to contain gibberish or random characters',\n });\n }\n \n // Check for common issues\n if (!patterns.hasTask && !patterns.hasRole) {\n issues.push({\n type: 'suggestion',\n code: 'NO_CLEAR_INSTRUCTION',\n message: 'Consider adding a clear task or role definition',\n });\n }\n \n // Check for unbalanced brackets/quotes\n const brackets = [\n { open: '{', close: '}' },\n { open: '[', close: ']' },\n { open: '(', close: ')' },\n ];\n \n for (const { open, close } of brackets) {\n const openCount = (trimmed.match(new RegExp(`\\\\${open}`, 'g')) || []).length;\n const closeCount = (trimmed.match(new RegExp(`\\\\${close}`, 'g')) || []).length;\n \n if (openCount !== closeCount) {\n issues.push({\n type: 'warning',\n code: 'UNBALANCED_BRACKETS',\n message: `Unbalanced ${open}${close} brackets (${openCount} open, ${closeCount} close)`,\n });\n }\n }\n \n // Check for very long lines (readability)\n const lines = trimmed.split('\\n');\n const longLines = lines.filter(l => l.length > 500);\n if (longLines.length > 0) {\n issues.push({\n type: 'suggestion',\n code: 'LONG_LINES',\n message: 'Some lines are very long. Consider breaking them up for readability.',\n });\n }\n \n const stats = {\n characterCount,\n wordCount,\n sentenceCount,\n variableCount,\n ...patterns,\n };\n \n const score = calculateScore(stats, issues);\n const hasErrors = issues.some(i => i.type === 'error');\n \n return {\n valid: !hasErrors,\n score,\n issues,\n stats,\n };\n}\n\n/**\n * Validate a prompt and throw if invalid\n */\nexport function validate(prompt: string): void {\n const result = check(prompt);\n \n if (!result.valid) {\n const errors = result.issues\n .filter(i => i.type === 'error')\n .map(i => i.message)\n .join('; ');\n \n throw new Error(`Invalid prompt: ${errors}`);\n }\n}\n\n/**\n * Check if a prompt is valid\n */\nexport function isValid(prompt: string): boolean {\n return check(prompt).valid;\n}\n\n/**\n * Get suggestions for improving a prompt\n */\nexport function getSuggestions(prompt: string): string[] {\n const result = check(prompt);\n const suggestions: string[] = [];\n \n // From issues\n suggestions.push(\n ...result.issues\n .filter(i => i.type === 'suggestion' || i.type === 'warning')\n .map(i => i.message)\n );\n \n // Additional suggestions based on stats\n if (!result.stats.hasRole) {\n suggestions.push('Add a role definition (e.g., \"Act as a...\")');\n }\n \n if (!result.stats.hasConstraints && result.stats.wordCount > 50) {\n suggestions.push('Consider adding constraints or rules for better control');\n }\n \n if (!result.stats.hasExamples && result.stats.wordCount > 100) {\n suggestions.push('Adding examples can improve output quality');\n }\n \n if (result.stats.variableCount === 0 && result.stats.wordCount > 30) {\n suggestions.push('Consider adding variables (${var}) to make the prompt reusable');\n }\n \n return suggestions;\n}\n","/**\n * Prompt Parser - Parse and load prompt files in various formats\n * \n * Supports:\n * - .prompt.yml / .prompt.yaml (YAML format)\n * - .prompt.json (JSON format)\n * - .prompt.md (Markdown with frontmatter)\n * - .txt (Plain text)\n * \n * @example\n * ```ts\n * import { parser } from 'prompts.chat';\n * \n * const prompt = parser.parse(`\n * name: Code Review\n * messages:\n * - role: system\n * content: You are a code reviewer.\n * `);\n * ```\n */\n\nexport interface PromptMessage {\n role: 'system' | 'user' | 'assistant';\n content: string;\n}\n\nexport interface ParsedPrompt {\n name?: string;\n description?: string;\n model?: string;\n modelParameters?: {\n temperature?: number;\n maxTokens?: number;\n topP?: number;\n frequencyPenalty?: number;\n presencePenalty?: number;\n };\n messages: PromptMessage[];\n variables?: Record<string, {\n description?: string;\n default?: string;\n required?: boolean;\n }>;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Parse YAML content\n * Note: This is a simple YAML parser for common prompt file structures\n * For full YAML support, the consuming project should use a proper YAML library\n */\nfunction parseSimpleYaml(content: string): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n const lines = content.split('\\n');\n \n let currentKey: string | null = null;\n let currentValue: unknown = null;\n let inArray = false;\n let inMultiline = false;\n let multilineContent = '';\n let arrayItems: unknown[] = [];\n let indent = 0;\n \n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const trimmed = line.trim();\n \n // Skip empty lines and comments\n if (!trimmed || trimmed.startsWith('#')) {\n if (inMultiline) {\n multilineContent += '\\n';\n }\n continue;\n }\n \n // Handle multiline content (|)\n if (inMultiline) {\n const lineIndent = line.search(/\\S/);\n if (lineIndent > indent) {\n multilineContent += (multilineContent ? '\\n' : '') + line.slice(indent + 2);\n continue;\n } else {\n // End of multiline\n if (inArray && currentKey) {\n const lastItem = arrayItems[arrayItems.length - 1] as Record<string, unknown>;\n if (lastItem && typeof lastItem === 'object') {\n const keys = Object.keys(lastItem);\n const lastKey = keys[keys.length - 1];\n lastItem[lastKey] = multilineContent.trim();\n }\n } else if (currentKey) {\n result[currentKey] = multilineContent.trim();\n }\n inMultiline = false;\n multilineContent = '';\n }\n }\n \n // Handle array items\n if (trimmed.startsWith('- ')) {\n if (!inArray && currentKey) {\n inArray = true;\n arrayItems = [];\n }\n \n const itemContent = trimmed.slice(2);\n \n // Check if it's a key-value pair\n const kvMatch = itemContent.match(/^(\\w+):\\s*(.*)$/);\n if (kvMatch) {\n const obj: Record<string, unknown> = {};\n obj[kvMatch[1]] = kvMatch[2] === '|' ? '' : (kvMatch[2] || '');\n \n if (kvMatch[2] === '|') {\n inMultiline = true;\n indent = line.search(/\\S/);\n multilineContent = '';\n }\n \n arrayItems.push(obj);\n } else {\n arrayItems.push(itemContent);\n }\n continue;\n }\n \n // Handle nested object properties in arrays\n if (inArray && line.startsWith(' ')) {\n const propMatch = trimmed.match(/^(\\w+):\\s*(.*)$/);\n if (propMatch && arrayItems.length > 0) {\n const lastItem = arrayItems[arrayItems.length - 1];\n if (typeof lastItem === 'object' && lastItem !== null) {\n (lastItem as Record<string, unknown>)[propMatch[1]] = \n propMatch[2] === '|' ? '' : (propMatch[2] || '');\n \n if (propMatch[2] === '|') {\n inMultiline = true;\n indent = line.search(/\\S/);\n multilineContent = '';\n }\n }\n }\n continue;\n }\n \n // End array if we're back to root level\n if (inArray && !line.startsWith(' ') && !line.startsWith('\\t')) {\n if (currentKey) {\n result[currentKey] = arrayItems;\n }\n inArray = false;\n arrayItems = [];\n }\n \n // Handle key-value pairs\n const match = trimmed.match(/^(\\w+):\\s*(.*)$/);\n if (match) {\n currentKey = match[1];\n const value = match[2];\n \n if (value === '' || value === '|' || value === '>') {\n // Multiline or nested content\n if (value === '|' || value === '>') {\n inMultiline = true;\n indent = line.search(/\\S/);\n multilineContent = '';\n }\n } else if (value.startsWith('\"') && value.endsWith('\"')) {\n result[currentKey] = value.slice(1, -1);\n } else if (value.startsWith(\"'\") && value.endsWith(\"'\")) {\n result[currentKey] = value.slice(1, -1);\n } else if (value === 'true') {\n result[currentKey] = true;\n } else if (value === 'false') {\n result[currentKey] = false;\n } else if (!isNaN(Number(value))) {\n result[currentKey] = Number(value);\n } else {\n result[currentKey] = value;\n }\n }\n }\n \n // Handle remaining array\n if (inArray && currentKey) {\n result[currentKey] = arrayItems;\n }\n \n // Handle remaining multiline\n if (inMultiline && currentKey) {\n result[currentKey] = multilineContent.trim();\n }\n \n return result;\n}\n\n/**\n * Parse JSON content\n */\nfunction parseJson(content: string): Record<string, unknown> {\n return JSON.parse(content);\n}\n\n/**\n * Parse Markdown with frontmatter\n */\nfunction parseMarkdown(content: string): Record<string, unknown> {\n const frontmatterMatch = content.match(/^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/);\n \n if (frontmatterMatch) {\n const frontmatter = parseSimpleYaml(frontmatterMatch[1]);\n const body = frontmatterMatch[2].trim();\n \n return {\n ...frontmatter,\n messages: [{ role: 'system', content: body }],\n };\n }\n \n // No frontmatter, treat entire content as system message\n return {\n messages: [{ role: 'system', content: content.trim() }],\n };\n}\n\n/**\n * Normalize parsed data to ParsedPrompt format\n */\nfunction normalize(data: Record<string, unknown>): ParsedPrompt {\n const messages: PromptMessage[] = [];\n \n // Handle messages array\n if (Array.isArray(data.messages)) {\n for (const msg of data.messages) {\n if (typeof msg === 'object' && msg !== null) {\n const m = msg as Record<string, unknown>;\n messages.push({\n role: (m.role as PromptMessage['role']) || 'user',\n content: String(m.content || ''),\n });\n }\n }\n }\n \n // Handle single content field\n if (messages.length === 0 && typeof data.content === 'string') {\n messages.push({ role: 'system', content: data.content });\n }\n \n // Handle prompt field (alias for content)\n if (messages.length === 0 && typeof data.prompt === 'string') {\n messages.push({ role: 'system', content: data.prompt });\n }\n \n return {\n name: data.name as string | undefined,\n description: data.description as string | undefined,\n model: data.model as string | undefined,\n modelParameters: data.modelParameters as ParsedPrompt['modelParameters'],\n messages,\n variables: data.variables as ParsedPrompt['variables'],\n metadata: data.metadata as Record<string, unknown>,\n };\n}\n\n/**\n * Parse prompt content in various formats\n */\nexport function parse(content: string, format?: 'yaml' | 'json' | 'markdown' | 'text'): ParsedPrompt {\n const trimmed = content.trim();\n \n // Auto-detect format if not specified\n if (!format) {\n if (trimmed.startsWith('{')) {\n format = 'json';\n } else if (trimmed.startsWith('---')) {\n format = 'markdown';\n } else if (trimmed.includes(':') && (trimmed.includes('\\n ') || trimmed.includes('\\n-'))) {\n format = 'yaml';\n } else {\n format = 'text';\n }\n }\n \n let data: Record<string, unknown>;\n \n switch (format) {\n case 'json':\n data = parseJson(trimmed);\n break;\n case 'yaml':\n data = parseSimpleYaml(trimmed);\n break;\n case 'markdown':\n data = parseMarkdown(trimmed);\n break;\n case 'text':\n default:\n data = { messages: [{ role: 'system', content: trimmed }] };\n break;\n }\n \n return normalize(data);\n}\n\n/**\n * Serialize a ParsedPrompt to YAML format\n */\nexport function toYaml(prompt: ParsedPrompt): string {\n const lines: string[] = [];\n \n if (prompt.name) {\n lines.push(`name: ${prompt.name}`);\n }\n \n if (prompt.description) {\n lines.push(`description: ${prompt.description}`);\n }\n \n if (prompt.model) {\n lines.push(`model: ${prompt.model}`);\n }\n \n if (prompt.modelParameters) {\n lines.push('modelParameters:');\n for (const [key, value] of Object.entries(prompt.modelParameters)) {\n if (value !== undefined) {\n lines.push(` ${key}: ${value}`);\n }\n }\n }\n \n if (prompt.messages.length > 0) {\n lines.push('messages:');\n for (const msg of prompt.messages) {\n lines.push(` - role: ${msg.role}`);\n if (msg.content.includes('\\n')) {\n lines.push(' content: |');\n for (const line of msg.content.split('\\n')) {\n lines.push(` ${line}`);\n }\n } else {\n lines.push(` content: \"${msg.content.replace(/\"/g, '\\\\\"')}\"`);\n }\n }\n }\n \n return lines.join('\\n');\n}\n\n/**\n * Serialize a ParsedPrompt to JSON format\n */\nexport function toJson(prompt: ParsedPrompt, pretty: boolean = true): string {\n return JSON.stringify(prompt, null, pretty ? 2 : 0);\n}\n\n/**\n * Get the system message content from a parsed prompt\n */\nexport function getSystemPrompt(prompt: ParsedPrompt): string {\n const systemMessage = prompt.messages.find(m => m.role === 'system');\n return systemMessage?.content || '';\n}\n\n/**\n * Interpolate variables in a prompt\n */\nexport function interpolate(\n prompt: ParsedPrompt,\n values: Record<string, string>\n): ParsedPrompt {\n const interpolateString = (str: string): string => {\n return str.replace(/\\{\\{(\\w+)\\}\\}/g, (match, key) => {\n if (key in values) return values[key];\n if (prompt.variables?.[key]?.default) return prompt.variables[key].default!;\n return match;\n });\n };\n \n return {\n ...prompt,\n messages: prompt.messages.map(msg => ({\n ...msg,\n content: interpolateString(msg.content),\n })),\n };\n}\n","/**\n * Media Prompt Builders - The D3.js of Prompt Building\n * \n * Comprehensive, structured builders for Image, Video, and Audio generation prompts.\n * Every attribute a professional would consider is available as a chainable method.\n * \n * @example\n * ```ts\n * import { image, video, audio } from 'prompts.chat/builder';\n * \n * const imagePrompt = image()\n * .subject(\"a lone samurai\")\n * .environment(\"bamboo forest at dawn\")\n * .camera({ angle: \"low\", shot: \"wide\", lens: \"35mm\" })\n * .lighting({ type: \"rim\", time: \"golden-hour\" })\n * .style({ artist: \"Akira Kurosawa\", medium: \"cinematic\" })\n * .build();\n * ```\n */\n\n// ============================================================================\n// TYPES & INTERFACES\n// ============================================================================\n\nexport type OutputFormat = 'text' | 'json' | 'yaml' | 'markdown';\n\n// --- Camera Brands & Models ---\nexport type CameraBrand = \n | 'sony' | 'canon' | 'nikon' | 'fujifilm' | 'leica' | 'hasselblad' | 'phase-one'\n | 'panasonic' | 'olympus' | 'pentax' | 'red' | 'arri' | 'blackmagic' | 'panavision';\n\nexport type CameraModel = \n // Sony\n | 'sony-a7iv' | 'sony-a7riv' | 'sony-a7siii' | 'sony-a1' | 'sony-fx3' | 'sony-fx6'\n | 'sony-venice' | 'sony-venice-2' | 'sony-a9ii' | 'sony-zv-e1'\n // Canon\n | 'canon-r5' | 'canon-r6' | 'canon-r3' | 'canon-r8' | 'canon-c70' | 'canon-c300-iii'\n | 'canon-c500-ii' | 'canon-5d-iv' | 'canon-1dx-iii' | 'canon-eos-r5c'\n // Nikon\n | 'nikon-z9' | 'nikon-z8' | 'nikon-z6-iii' | 'nikon-z7-ii' | 'nikon-d850' | 'nikon-d6'\n // Fujifilm\n | 'fujifilm-x-t5' | 'fujifilm-x-h2s' | 'fujifilm-x100vi' | 'fujifilm-gfx100s'\n | 'fujifilm-gfx100-ii' | 'fujifilm-x-pro3'\n // Leica\n | 'leica-m11' | 'leica-sl2' | 'leica-sl2-s' | 'leica-q3' | 'leica-m10-r'\n // Hasselblad\n | 'hasselblad-x2d' | 'hasselblad-907x' | 'hasselblad-h6d-100c'\n // Cinema Cameras\n | 'arri-alexa-35' | 'arri-alexa-mini-lf' | 'arri-alexa-65' | 'arri-amira'\n | 'red-v-raptor' | 'red-komodo' | 'red-gemini' | 'red-monstro'\n | 'blackmagic-ursa-mini-pro' | 'blackmagic-pocket-6k' | 'blackmagic-pocket-4k'\n | 'panavision-dxl2' | 'panavision-millennium-xl2';\n\nexport type SensorFormat = \n | 'full-frame' | 'aps-c' | 'micro-four-thirds' | 'medium-format' | 'large-format'\n | 'super-35' | 'vista-vision' | 'imax' | '65mm' | '35mm-film' | '16mm-film' | '8mm-film';\n\nexport type FilmFormat = \n | '35mm' | '120-medium-format' | '4x5-large-format' | '8x10-large-format'\n | '110-film' | 'instant-film' | 'super-8' | '16mm' | '65mm-imax';\n\n// --- Camera & Shot Types ---\nexport type CameraAngle = \n | 'eye-level' | 'low-angle' | 'high-angle' | 'dutch-angle' | 'birds-eye' \n | 'worms-eye' | 'over-the-shoulder' | 'point-of-view' | 'aerial' | 'drone'\n | 'canted' | 'oblique' | 'hip-level' | 'knee-level' | 'ground-level';\n\nexport type ShotType = \n | 'extreme-close-up' | 'close-up' | 'medium-close-up' | 'medium' | 'medium-wide'\n | 'wide' | 'extreme-wide' | 'establishing' | 'full-body' | 'portrait' | 'headshot';\n\nexport type LensType = \n | 'wide-angle' | 'ultra-wide' | 'standard' | 'telephoto' | 'macro' | 'fisheye'\n | '14mm' | '24mm' | '35mm' | '50mm' | '85mm' | '100mm' | '135mm' | '200mm' | '400mm'\n | '600mm' | '800mm' | 'tilt-shift' | 'anamorphic' | 'spherical' | 'prime' | 'zoom';\n\nexport type LensBrand = \n | 'zeiss' | 'leica' | 'canon' | 'nikon' | 'sony' | 'sigma' | 'tamron' | 'voigtlander'\n | 'fujifilm' | 'samyang' | 'rokinon' | 'tokina' | 'cooke' | 'arri' | 'panavision'\n | 'angenieux' | 'red' | 'atlas' | 'sirui';\n\nexport type LensModel = \n // Zeiss\n | 'zeiss-otus-55' | 'zeiss-batis-85' | 'zeiss-milvus-35' | 'zeiss-supreme-prime'\n // Leica\n | 'leica-summilux-50' | 'leica-summicron-35' | 'leica-noctilux-50' | 'leica-apo-summicron'\n // Canon\n | 'canon-rf-50-1.2' | 'canon-rf-85-1.2' | 'canon-rf-28-70-f2' | 'canon-rf-100-500'\n // Sony\n | 'sony-gm-24-70' | 'sony-gm-70-200' | 'sony-gm-50-1.2' | 'sony-gm-85-1.4'\n // Sigma Art\n | 'sigma-art-35' | 'sigma-art-50' | 'sigma-art-85' | 'sigma-art-105-macro'\n // Cinema\n | 'cooke-s7i' | 'cooke-anamorphic' | 'arri-signature-prime' | 'arri-ultra-prime'\n | 'panavision-primo' | 'panavision-anamorphic' | 'atlas-orion-anamorphic'\n // Vintage\n | 'helios-44-2' | 'canon-fd-55' | 'minolta-rokkor-58' | 'pentax-takumar-50';\n\nexport type FocusType = \n | 'shallow' | 'deep' | 'soft-focus' | 'tilt-shift' | 'rack-focus' | 'split-diopter'\n | 'zone-focus' | 'hyperfocal' | 'selective' | 'bokeh-heavy' | 'tack-sharp';\n\nexport type BokehStyle = \n | 'smooth' | 'creamy' | 'swirly' | 'busy' | 'soap-bubble' | 'cat-eye' | 'oval-anamorphic';\n\nexport type FilterType = \n | 'uv' | 'polarizer' | 'nd' | 'nd-graduated' | 'black-pro-mist' | 'white-pro-mist'\n | 'glimmer-glass' | 'classic-soft' | 'streak' | 'starburst' | 'diffusion'\n | 'infrared' | 'color-gel' | 'warming' | 'cooling' | 'vintage-look';\n\nexport type CameraMovement = \n | 'static' | 'pan' | 'tilt' | 'dolly' | 'truck' | 'pedestal' | 'zoom' \n | 'handheld' | 'steadicam' | 'crane' | 'drone' | 'tracking' | 'arc' | 'whip-pan'\n | 'roll' | 'boom' | 'jib' | 'cable-cam' | 'motion-control' | 'snorricam'\n | 'dutch-roll' | 'vertigo-effect' | 'crash-zoom' | 'slow-push' | 'slow-pull';\n\nexport type CameraRig = \n | 'tripod' | 'monopod' | 'gimbal' | 'steadicam' | 'easyrig' | 'shoulder-rig'\n | 'slider' | 'dolly' | 'jib' | 'crane' | 'technocrane' | 'russian-arm'\n | 'cable-cam' | 'drone' | 'fpv-drone' | 'motion-control' | 'handheld';\n\nexport type GimbalModel = \n | 'dji-ronin-4d' | 'dji-ronin-rs3-pro' | 'dji-ronin-rs4' | 'moza-air-2'\n | 'zhiyun-crane-3s' | 'freefly-movi-pro' | 'tilta-gravity-g2x';\n\n// --- Lighting Types ---\nexport type LightingType = \n | 'natural' | 'studio' | 'dramatic' | 'soft' | 'hard' | 'diffused'\n | 'key' | 'fill' | 'rim' | 'backlit' | 'silhouette' | 'rembrandt'\n | 'split' | 'butterfly' | 'loop' | 'broad' | 'short' | 'chiaroscuro'\n | 'high-key' | 'low-key' | 'three-point' | 'practical' | 'motivated';\n\nexport type TimeOfDay = \n | 'dawn' | 'sunrise' | 'golden-hour' | 'morning' | 'midday' | 'afternoon'\n | 'blue-hour' | 'sunset' | 'dusk' | 'twilight' | 'night' | 'midnight';\n\nexport type WeatherLighting = \n | 'sunny' | 'cloudy' | 'overcast' | 'foggy' | 'misty' | 'rainy' \n | 'stormy' | 'snowy' | 'hazy';\n\n// --- Style Types ---\nexport type ArtStyle = \n | 'photorealistic' | 'hyperrealistic' | 'cinematic' | 'documentary'\n | 'editorial' | 'fashion' | 'portrait' | 'landscape' | 'street'\n | 'fine-art' | 'conceptual' | 'surreal' | 'abstract' | 'minimalist'\n | 'maximalist' | 'vintage' | 'retro' | 'noir' | 'gothic' | 'romantic'\n | 'impressionist' | 'expressionist' | 'pop-art' | 'art-nouveau' | 'art-deco'\n | 'cyberpunk' | 'steampunk' | 'fantasy' | 'sci-fi' | 'anime' | 'manga'\n | 'comic-book' | 'illustration' | 'digital-art' | 'oil-painting' | 'watercolor'\n | 'sketch' | 'pencil-drawing' | 'charcoal' | 'pastel' | '3d-render';\n\nexport type FilmStock = \n // Kodak Color Negative\n | 'kodak-portra-160' | 'kodak-portra-400' | 'kodak-portra-800' \n | 'kodak-ektar-100' | 'kodak-gold-200' | 'kodak-ultramax-400' | 'kodak-colorplus-200'\n // Kodak Black & White\n | 'kodak-tri-x-400' | 'kodak-tmax-100' | 'kodak-tmax-400' | 'kodak-tmax-3200'\n // Kodak Slide\n | 'kodak-ektachrome-e100' | 'kodachrome-64' | 'kodachrome-200'\n // Kodak Cinema\n | 'kodak-vision3-50d' | 'kodak-vision3-200t' | 'kodak-vision3-250d' | 'kodak-vision3-500t'\n // Fujifilm\n | 'fujifilm-pro-400h' | 'fujifilm-superia-400' | 'fujifilm-c200'\n | 'fujifilm-velvia-50' | 'fujifilm-velvia-100' | 'fujifilm-provia-100f'\n | 'fujifilm-acros-100' | 'fujifilm-neopan-400' | 'fujifilm-eterna-500t'\n // Ilford\n | 'ilford-hp5-plus' | 'ilford-delta-100' | 'ilford-delta-400' | 'ilford-delta-3200'\n | 'ilford-fp4-plus' | 'ilford-pan-f-plus' | 'ilford-xp2-super'\n // CineStill\n | 'cinestill-50d' | 'cinestill-800t' | 'cinestill-400d' | 'cinestill-bwxx'\n // Lomography\n | 'lomography-100' | 'lomography-400' | 'lomography-800'\n | 'lomochrome-purple' | 'lomochrome-metropolis' | 'lomochrome-turquoise'\n // Instant\n | 'polaroid-sx-70' | 'polaroid-600' | 'polaroid-i-type' | 'polaroid-spectra'\n | 'instax-mini' | 'instax-wide' | 'instax-square'\n // Vintage/Discontinued\n | 'agfa-vista-400' | 'agfa-apx-100' | 'fomapan-100' | 'fomapan-400'\n | 'bergger-pancro-400' | 'jch-streetpan-400';\n\nexport type AspectRatio = \n | '1:1' | '4:3' | '3:2' | '16:9' | '21:9' | '9:16' | '2:3' | '4:5' | '5:4';\n\n// --- Color & Mood ---\nexport type ColorPalette = \n | 'warm' | 'cool' | 'neutral' | 'vibrant' | 'muted' | 'pastel' | 'neon'\n | 'monochrome' | 'sepia' | 'desaturated' | 'high-contrast' | 'low-contrast'\n | 'earthy' | 'oceanic' | 'forest' | 'sunset' | 'midnight' | 'golden';\n\nexport type Mood = \n | 'serene' | 'peaceful' | 'melancholic' | 'dramatic' | 'tense' | 'mysterious'\n | 'romantic' | 'nostalgic' | 'hopeful' | 'joyful' | 'energetic' | 'chaotic'\n | 'ethereal' | 'dark' | 'light' | 'whimsical' | 'eerie' | 'epic' | 'intimate';\n\n// --- Video Specific ---\nexport type VideoTransition = \n | 'cut' | 'fade' | 'dissolve' | 'wipe' | 'morph' | 'match-cut' | 'jump-cut'\n | 'cross-dissolve' | 'iris' | 'push' | 'slide';\n\nexport type VideoPacing = \n | 'slow' | 'medium' | 'fast' | 'variable' | 'building' | 'frenetic' | 'contemplative';\n\n// --- Audio/Music Specific ---\nexport type MusicGenre = \n | 'pop' | 'rock' | 'jazz' | 'classical' | 'electronic' | 'hip-hop' | 'r&b'\n | 'country' | 'folk' | 'blues' | 'metal' | 'punk' | 'indie' | 'alternative'\n | 'ambient' | 'lo-fi' | 'synthwave' | 'orchestral' | 'cinematic' | 'world'\n | 'latin' | 'reggae' | 'soul' | 'funk' | 'disco' | 'house' | 'techno' | 'edm';\n\nexport type Instrument = \n | 'piano' | 'guitar' | 'acoustic-guitar' | 'electric-guitar' | 'bass' | 'drums'\n | 'violin' | 'cello' | 'viola' | 'flute' | 'saxophone' | 'trumpet' | 'trombone'\n | 'synthesizer' | 'organ' | 'harp' | 'percussion' | 'strings' | 'brass' | 'woodwinds'\n | 'choir' | 'vocals' | 'beatbox' | 'turntables' | 'harmonica' | 'banjo' | 'ukulele';\n\nexport type VocalStyle = \n | 'male' | 'female' | 'duet' | 'choir' | 'a-cappella' | 'spoken-word' | 'rap'\n | 'falsetto' | 'belting' | 'whisper' | 'growl' | 'melodic' | 'harmonized';\n\nexport type Tempo = \n | 'largo' | 'adagio' | 'andante' | 'moderato' | 'allegro' | 'vivace' | 'presto'\n | number; // BPM\n\n// ============================================================================\n// IMAGE PROMPT BUILDER\n// ============================================================================\n\nexport interface ImageSubject {\n main: string;\n details?: string[];\n expression?: string;\n pose?: string;\n action?: string;\n clothing?: string;\n accessories?: string[];\n age?: string;\n ethnicity?: string;\n gender?: string;\n count?: number | 'single' | 'couple' | 'group' | 'crowd';\n}\n\nexport interface ImageCamera {\n // Framing\n angle?: CameraAngle;\n shot?: ShotType;\n \n // Camera Body\n brand?: CameraBrand;\n model?: CameraModel;\n sensor?: SensorFormat;\n \n // Lens\n lens?: LensType;\n lensModel?: LensModel;\n lensBrand?: LensBrand;\n focalLength?: string;\n \n // Focus & Depth\n focus?: FocusType;\n aperture?: string;\n bokeh?: BokehStyle;\n focusDistance?: string;\n \n // Exposure\n iso?: number;\n shutterSpeed?: string;\n exposureCompensation?: string;\n \n // Film/Digital\n filmStock?: FilmStock;\n filmFormat?: FilmFormat;\n \n // Filters & Accessories\n filter?: FilterType | FilterType[];\n \n // Camera Settings\n whiteBalance?: 'daylight' | 'cloudy' | 'tungsten' | 'fluorescent' | 'flash' | 'custom';\n colorProfile?: string;\n pictureProfile?: string;\n}\n\nexport interface ImageLighting {\n type?: LightingType | LightingType[];\n time?: TimeOfDay;\n weather?: WeatherLighting;\n direction?: 'front' | 'side' | 'back' | 'top' | 'bottom' | 'three-quarter';\n intensity?: 'soft' | 'medium' | 'hard' | 'dramatic';\n color?: string;\n sources?: string[];\n}\n\nexport interface ImageComposition {\n ruleOfThirds?: boolean;\n goldenRatio?: boolean;\n symmetry?: 'none' | 'horizontal' | 'vertical' | 'radial';\n leadingLines?: boolean;\n framing?: string;\n negativeSpace?: boolean;\n layers?: string[];\n foreground?: string;\n midground?: string;\n background?: string;\n}\n\nexport interface ImageStyle {\n medium?: ArtStyle | ArtStyle[];\n artist?: string | string[];\n era?: string;\n influence?: string[];\n quality?: string[];\n render?: string;\n}\n\nexport interface ImageColor {\n palette?: ColorPalette | ColorPalette[];\n primary?: string[];\n accent?: string[];\n grade?: string;\n temperature?: 'warm' | 'neutral' | 'cool';\n saturation?: 'desaturated' | 'natural' | 'vibrant' | 'hyper-saturated';\n contrast?: 'low' | 'medium' | 'high';\n}\n\nexport interface ImageEnvironment {\n setting: string;\n location?: string;\n terrain?: string;\n architecture?: string;\n props?: string[];\n atmosphere?: string;\n season?: 'spring' | 'summer' | 'autumn' | 'winter';\n era?: string;\n}\n\nexport interface ImageTechnical {\n aspectRatio?: AspectRatio;\n resolution?: string;\n quality?: 'draft' | 'standard' | 'high' | 'ultra' | 'masterpiece';\n detail?: 'low' | 'medium' | 'high' | 'extreme';\n noise?: 'none' | 'subtle' | 'filmic' | 'grainy';\n sharpness?: 'soft' | 'natural' | 'sharp' | 'crisp';\n}\n\nexport interface BuiltImagePrompt {\n prompt: string;\n structure: {\n subject?: ImageSubject;\n camera?: ImageCamera;\n lighting?: ImageLighting;\n composition?: ImageComposition;\n style?: ImageStyle;\n color?: ImageColor;\n environment?: ImageEnvironment;\n technical?: ImageTechnical;\n mood?: Mood | Mood[];\n negative?: string[];\n };\n}\n\nexport class ImagePromptBuilder {\n private _subject?: ImageSubject;\n private _camera?: ImageCamera;\n private _lighting?: ImageLighting;\n private _composition?: ImageComposition;\n private _style?: ImageStyle;\n private _color?: ImageColor;\n private _environment?: ImageEnvironment;\n private _technical?: ImageTechnical;\n private _mood?: Mood | Mood[];\n private _negative: string[] = [];\n private _custom: string[] = [];\n\n // --- Subject Methods ---\n \n subject(main: string | ImageSubject): this {\n if (typeof main === 'string') {\n this._subject = { ...(this._subject || {}), main };\n } else {\n this._subject = { ...(this._subject || {}), ...main };\n }\n return this;\n }\n\n subjectDetails(details: string[]): this {\n this._subject = { ...(this._subject || { main: '' }), details };\n return this;\n }\n\n expression(expression: string): this {\n this._subject = { ...(this._subject || { main: '' }), expression };\n return this;\n }\n\n pose(pose: string): this {\n this._subject = { ...(this._subject || { main: '' }), pose };\n return this;\n }\n\n action(action: string): this {\n this._subject = { ...(this._subject || { main: '' }), action };\n return this;\n }\n\n clothing(clothing: string): this {\n this._subject = { ...(this._subject || { main: '' }), clothing };\n return this;\n }\n\n accessories(accessories: string[]): this {\n this._subject = { ...(this._subject || { main: '' }), accessories };\n return this;\n }\n\n subjectCount(count: ImageSubject['count']): this {\n this._subject = { ...(this._subject || { main: '' }), count };\n return this;\n }\n\n // --- Camera Methods ---\n\n camera(settings: ImageCamera): this {\n this._camera = { ...(this._camera || {}), ...settings };\n return this;\n }\n\n angle(angle: CameraAngle): this {\n this._camera = { ...(this._camera || {}), angle };\n return this;\n }\n\n shot(shot: ShotType): this {\n this._camera = { ...(this._camera || {}), shot };\n return this;\n }\n\n lens(lens: LensType): this {\n this._camera = { ...(this._camera || {}), lens };\n return this;\n }\n\n focus(focus: FocusType): this {\n this._camera = { ...(this._camera || {}), focus };\n return this;\n }\n\n aperture(aperture: string): this {\n this._camera = { ...(this._camera || {}), aperture };\n return this;\n }\n\n filmStock(filmStock: FilmStock): this {\n this._camera = { ...(this._camera || {}), filmStock };\n return this;\n }\n\n filmFormat(format: FilmFormat): this {\n this._camera = { ...(this._camera || {}), filmFormat: format };\n return this;\n }\n\n cameraBrand(brand: CameraBrand): this {\n this._camera = { ...(this._camera || {}), brand };\n return this;\n }\n\n cameraModel(model: CameraModel): this {\n this._camera = { ...(this._camera || {}), model };\n return this;\n }\n\n sensor(sensor: SensorFormat): this {\n this._camera = { ...(this._camera || {}), sensor };\n return this;\n }\n\n lensModel(model: LensModel): this {\n this._camera = { ...(this._camera || {}), lensModel: model };\n return this;\n }\n\n lensBrand(brand: LensBrand): this {\n this._camera = { ...(this._camera || {}), lensBrand: brand };\n return this;\n }\n\n focalLength(length: string): this {\n this._camera = { ...(this._camera || {}), focalLength: length };\n return this;\n }\n\n bokeh(style: BokehStyle): this {\n this._camera = { ...(this._camera || {}), bokeh: style };\n return this;\n }\n\n filter(filter: FilterType | FilterType[]): this {\n this._camera = { ...(this._camera || {}), filter };\n return this;\n }\n\n iso(iso: number): this {\n this._camera = { ...(this._camera || {}), iso };\n return this;\n }\n\n shutterSpeed(speed: string): this {\n this._camera = { ...(this._camera || {}), shutterSpeed: speed };\n return this;\n }\n\n whiteBalance(wb: ImageCamera['whiteBalance']): this {\n this._camera = { ...(this._camera || {}), whiteBalance: wb };\n return this;\n }\n\n colorProfile(profile: string): this {\n this._camera = { ...(this._camera || {}), colorProfile: profile };\n return this;\n }\n\n // --- Lighting Methods ---\n\n lighting(settings: ImageLighting): this {\n this._lighting = { ...(this._lighting || {}), ...settings };\n return this;\n }\n\n lightingType(type: LightingType | LightingType[]): this {\n this._lighting = { ...(this._lighting || {}), type };\n return this;\n }\n\n timeOfDay(time: TimeOfDay): this {\n this._lighting = { ...(this._lighting || {}), time };\n return this;\n }\n\n weather(weather: WeatherLighting): this {\n this._lighting = { ...(this._lighting || {}), weather };\n return this;\n }\n\n lightDirection(direction: ImageLighting['direction']): this {\n this._lighting = { ...(this._lighting || {}), direction };\n return this;\n }\n\n lightIntensity(intensity: ImageLighting['intensity']): this {\n this._lighting = { ...(this._lighting || {}), intensity };\n return this;\n }\n\n // --- Composition Methods ---\n\n composition(settings: ImageComposition): this {\n this._composition = { ...(this._composition || {}), ...settings };\n return this;\n }\n\n ruleOfThirds(): this {\n this._composition = { ...(this._composition || {}), ruleOfThirds: true };\n return this;\n }\n\n goldenRatio(): this {\n this._composition = { ...(this._composition || {}), goldenRatio: true };\n return this;\n }\n\n symmetry(type: ImageComposition['symmetry']): this {\n this._composition = { ...(this._composition || {}), symmetry: type };\n return this;\n }\n\n foreground(fg: string): this {\n this._composition = { ...(this._composition || {}), foreground: fg };\n return this;\n }\n\n midground(mg: string): this {\n this._composition = { ...(this._composition || {}), midground: mg };\n return this;\n }\n\n background(bg: string): this {\n this._composition = { ...(this._composition || {}), background: bg };\n return this;\n }\n\n // --- Environment Methods ---\n\n environment(setting: string | ImageEnvironment): this {\n if (typeof setting === 'string') {\n this._environment = { ...(this._environment || { setting: '' }), setting };\n } else {\n this._environment = { ...(this._environment || { setting: '' }), ...setting };\n }\n return this;\n }\n\n location(location: string): this {\n this._environment = { ...(this._environment || { setting: '' }), location };\n return this;\n }\n\n props(props: string[]): this {\n this._environment = { ...(this._environment || { setting: '' }), props };\n return this;\n }\n\n atmosphere(atmosphere: string): this {\n this._environment = { ...(this._environment || { setting: '' }), atmosphere };\n return this;\n }\n\n season(season: ImageEnvironment['season']): this {\n this._environment = { ...(this._environment || { setting: '' }), season };\n return this;\n }\n\n // --- Style Methods ---\n\n style(settings: ImageStyle): this {\n this._style = { ...(this._style || {}), ...settings };\n return this;\n }\n\n medium(medium: ArtStyle | ArtStyle[]): this {\n this._style = { ...(this._style || {}), medium };\n return this;\n }\n\n artist(artist: string | string[]): this {\n this._style = { ...(this._style || {}), artist };\n return this;\n }\n\n influence(influences: string[]): this {\n this._style = { ...(this._style || {}), influence: influences };\n return this;\n }\n\n // --- Color Methods ---\n\n color(settings: ImageColor): this {\n this._color = { ...(this._color || {}), ...settings };\n return this;\n }\n\n palette(palette: ColorPalette | ColorPalette[]): this {\n this._color = { ...(this._color || {}), palette };\n return this;\n }\n\n primaryColors(colors: string[]): this {\n this._color = { ...(this._color || {}), primary: colors };\n return this;\n }\n\n accentColors(colors: string[]): this {\n this._color = { ...(this._color || {}), accent: colors };\n return this;\n }\n\n colorGrade(grade: string): this {\n this._color = { ...(this._color || {}), grade };\n return this;\n }\n\n // --- Technical Methods ---\n\n technical(settings: ImageTechnical): this {\n this._technical = { ...(this._technical || {}), ...settings };\n return this;\n }\n\n aspectRatio(ratio: AspectRatio): this {\n this._technical = { ...(this._technical || {}), aspectRatio: ratio };\n return this;\n }\n\n resolution(resolution: string): this {\n this._technical = { ...(this._technical || {}), resolution };\n return this;\n }\n\n quality(quality: ImageTechnical['quality']): this {\n this._technical = { ...(this._technical || {}), quality };\n return this;\n }\n\n // --- Mood & Misc ---\n\n mood(mood: Mood | Mood[]): this {\n this._mood = mood;\n return this;\n }\n\n negative(items: string[]): this {\n this._negative = [...this._negative, ...items];\n return this;\n }\n\n custom(text: string): this {\n this._custom.push(text);\n return this;\n }\n\n // --- Build Methods ---\n\n private buildPromptText(): string {\n const parts: string[] = [];\n\n // Subject\n if (this._subject) {\n let subjectText = this._subject.main;\n if (this._subject.count && this._subject.count !== 'single') {\n subjectText = `${this._subject.count} ${subjectText}`;\n }\n if (this._subject.expression) subjectText += `, ${this._subject.expression} expression`;\n if (this._subject.pose) subjectText += `, ${this._subject.pose}`;\n if (this._subject.action) subjectText += `, ${this._subject.action}`;\n if (this._subject.clothing) subjectText += `, wearing ${this._subject.clothing}`;\n if (this._subject.accessories?.length) subjectText += `, with ${this._subject.accessories.join(', ')}`;\n if (this._subject.details?.length) subjectText += `, ${this._subject.details.join(', ')}`;\n parts.push(subjectText);\n }\n\n // Environment\n if (this._environment) {\n let envText = this._environment.setting;\n if (this._environment.location) envText += ` in ${this._environment.location}`;\n if (this._environment.atmosphere) envText += `, ${this._environment.atmosphere} atmosphere`;\n if (this._environment.season) envText += `, ${this._environment.season}`;\n if (this._environment.props?.length) envText += `, with ${this._environment.props.join(', ')}`;\n parts.push(envText);\n }\n\n // Composition\n if (this._composition) {\n const compParts: string[] = [];\n if (this._composition.foreground) compParts.push(`foreground: ${this._composition.foreground}`);\n if (this._composition.midground) compParts.push(`midground: ${this._composition.midground}`);\n if (this._composition.background) compParts.push(`background: ${this._composition.background}`);\n if (this._composition.ruleOfThirds) compParts.push('rule of thirds composition');\n if (this._composition.goldenRatio) compParts.push('golden ratio composition');\n if (this._composition.symmetry && this._composition.symmetry !== 'none') {\n compParts.push(`${this._composition.symmetry} symmetry`);\n }\n if (compParts.length) parts.push(compParts.join(', '));\n }\n\n // Camera\n if (this._camera) {\n const camParts: string[] = [];\n if (this._camera.shot) camParts.push(`${this._camera.shot} shot`);\n if (this._camera.angle) camParts.push(`${this._camera.angle}`);\n if (this._camera.lens) camParts.push(`${this._camera.lens} lens`);\n if (this._camera.focus) camParts.push(`${this._camera.focus} depth of field`);\n if (this._camera.aperture) camParts.push(`f/${this._camera.aperture}`);\n if (this._camera.filmStock) camParts.push(`shot on ${this._camera.filmStock}`);\n if (this._camera.brand) camParts.push(`${this._camera.brand}`);\n if (camParts.length) parts.push(camParts.join(', '));\n }\n\n // Lighting\n if (this._lighting) {\n const lightParts: string[] = [];\n if (this._lighting.type) {\n const types = Array.isArray(this._lighting.type) ? this._lighting.type : [this._lighting.type];\n lightParts.push(`${types.join(' and ')} lighting`);\n }\n if (this._lighting.time) lightParts.push(this._lighting.time);\n if (this._lighting.weather) lightParts.push(`${this._lighting.weather} weather`);\n if (this._lighting.direction) lightParts.push(`light from ${this._lighting.direction}`);\n if (this._lighting.intensity) lightParts.push(`${this._lighting.intensity} light`);\n if (lightParts.length) parts.push(lightParts.join(', '));\n }\n\n // Style\n if (this._style) {\n const styleParts: string[] = [];\n if (this._style.medium) {\n const mediums = Array.isArray(this._style.medium) ? this._style.medium : [this._style.medium];\n styleParts.push(mediums.join(', '));\n }\n if (this._style.artist) {\n const artists = Array.isArray(this._style.artist) ? this._style.artist : [this._style.artist];\n styleParts.push(`in the style of ${artists.join(' and ')}`);\n }\n if (this._style.era) styleParts.push(this._style.era);\n if (this._style.influence?.length) styleParts.push(`influenced by ${this._style.influence.join(', ')}`);\n if (this._style.quality?.length) styleParts.push(this._style.quality.join(', '));\n if (styleParts.length) parts.push(styleParts.join(', '));\n }\n\n // Color\n if (this._color) {\n const colorParts: string[] = [];\n if (this._color.palette) {\n const palettes = Array.isArray(this._color.palette) ? this._color.palette : [this._color.palette];\n colorParts.push(`${palettes.join(' and ')} color palette`);\n }\n if (this._color.primary?.length) colorParts.push(`primary colors: ${this._color.primary.join(', ')}`);\n if (this._color.accent?.length) colorParts.push(`accent colors: ${this._color.accent.join(', ')}`);\n if (this._color.grade) colorParts.push(`${this._color.grade} color grade`);\n if (this._color.temperature) colorParts.push(`${this._color.temperature} tones`);\n if (colorParts.length) parts.push(colorParts.join(', '));\n }\n\n // Mood\n if (this._mood) {\n const moods = Array.isArray(this._mood) ? this._mood : [this._mood];\n parts.push(`${moods.join(', ')} mood`);\n }\n\n // Technical\n if (this._technical) {\n const techParts: string[] = [];\n if (this._technical.quality) techParts.push(`${this._technical.quality} quality`);\n if (this._technical.detail) techParts.push(`${this._technical.detail} detail`);\n if (this._technical.resolution) techParts.push(this._technical.resolution);\n if (techParts.length) parts.push(techParts.join(', '));\n }\n\n // Custom\n if (this._custom.length) {\n parts.push(this._custom.join(', '));\n }\n\n let prompt = parts.join(', ');\n\n // Negative prompts\n if (this._negative.length) {\n prompt += ` --no ${this._negative.join(', ')}`;\n }\n\n // Aspect ratio\n if (this._technical?.aspectRatio) {\n prompt += ` --ar ${this._technical.aspectRatio}`;\n }\n\n return prompt;\n }\n\n build(): BuiltImagePrompt {\n return {\n prompt: this.buildPromptText(),\n structure: {\n subject: this._subject,\n camera: this._camera,\n lighting: this._lighting,\n composition: this._composition,\n style: this._style,\n color: this._color,\n environment: this._environment,\n technical: this._technical,\n mood: this._mood,\n negative: this._negative.length ? this._negative : undefined,\n },\n };\n }\n\n toString(): string {\n return this.build().prompt;\n }\n\n toJSON(): string {\n return JSON.stringify(this.build().structure, null, 2);\n }\n\n toYAML(): string {\n return objectToYaml(this.build().structure);\n }\n\n toMarkdown(): string {\n const built = this.build();\n const sections: string[] = ['# Image Prompt\\n'];\n \n sections.push('## Prompt\\n```\\n' + built.prompt + '\\n```\\n');\n \n if (built.structure.subject) {\n sections.push('## Subject\\n' + objectToMarkdownList(built.structure.subject));\n }\n if (built.structure.environment) {\n sections.push('## Environment\\n' + objectToMarkdownList(built.structure.environment));\n }\n if (built.structure.camera) {\n sections.push('## Camera\\n' + objectToMarkdownList(built.structure.camera));\n }\n if (built.structure.lighting) {\n sections.push('## Lighting\\n' + objectToMarkdownList(built.structure.lighting));\n }\n if (built.structure.composition) {\n sections.push('## Composition\\n' + objectToMarkdownList(built.structure.composition));\n }\n if (built.structure.style) {\n sections.push('## Style\\n' + objectToMarkdownList(built.structure.style));\n }\n if (built.structure.color) {\n sections.push('## Color\\n' + objectToMarkdownList(built.structure.color));\n }\n if (built.structure.technical) {\n sections.push('## Technical\\n' + objectToMarkdownList(built.structure.technical));\n }\n \n return sections.join('\\n');\n }\n\n format(fmt: OutputFormat): string {\n switch (fmt) {\n case 'json': return this.toJSON();\n case 'yaml': return this.toYAML();\n case 'markdown': return this.toMarkdown();\n default: return this.toString();\n }\n }\n}\n\n// ============================================================================\n// HELPER FUNCTIONS\n// ============================================================================\n\nfunction objectToYaml(obj: object, indent = 0): string {\n const spaces = ' '.repeat(indent);\n const lines: string[] = [];\n \n for (const [key, value] of Object.entries(obj)) {\n if (value === undefined || value === null) continue;\n \n if (Array.isArray(value)) {\n if (value.length === 0) continue;\n lines.push(`${spaces}${key}:`);\n for (const item of value) {\n if (typeof item === 'object') {\n lines.push(`${spaces} -`);\n lines.push(objectToYaml(item as Record<string, unknown>, indent + 2).replace(/^/gm, ' '));\n } else {\n lines.push(`${spaces} - ${item}`);\n }\n }\n } else if (typeof value === 'object') {\n lines.push(`${spaces}${key}:`);\n lines.push(objectToYaml(value as Record<string, unknown>, indent + 1));\n } else {\n lines.push(`${spaces}${key}: ${value}`);\n }\n }\n \n return lines.join('\\n');\n}\n\nfunction objectToMarkdownList(obj: object, indent = 0): string {\n const spaces = ' '.repeat(indent);\n const lines: string[] = [];\n \n for (const [key, value] of Object.entries(obj)) {\n if (value === undefined || value === null) continue;\n \n if (Array.isArray(value)) {\n lines.push(`${spaces}- **${key}:** ${value.join(', ')}`);\n } else if (typeof value === 'object') {\n lines.push(`${spaces}- **${key}:**`);\n lines.push(objectToMarkdownList(value as Record<string, unknown>, indent + 1));\n } else {\n lines.push(`${spaces}- **${key}:** ${value}`);\n }\n }\n \n return lines.join('\\n');\n}\n\n// ============================================================================\n// FACTORY FUNCTIONS\n// ============================================================================\n\n/**\n * Create a new image prompt builder\n */\nexport function image(): ImagePromptBuilder {\n return new ImagePromptBuilder();\n}\n","/**\n * Video Prompt Builder - Comprehensive video generation prompt builder\n * \n * Based on OpenAI Sora, Runway, and other video generation best practices.\n * \n * @example\n * ```ts\n * import { video } from 'prompts.chat/builder';\n * \n * const prompt = video()\n * .scene(\"A samurai walks through a bamboo forest\")\n * .camera({ movement: \"tracking\", angle: \"low\" })\n * .lighting({ time: \"golden-hour\", type: \"natural\" })\n * .duration(5)\n * .build();\n * ```\n */\n\nimport type {\n CameraAngle, ShotType, LensType, CameraMovement,\n LightingType, TimeOfDay, WeatherLighting,\n ArtStyle, ColorPalette, Mood, VideoTransition, VideoPacing,\n OutputFormat, CameraBrand, CameraModel, SensorFormat,\n LensBrand, LensModel, CameraRig, GimbalModel, FilterType,\n FilmStock, BokehStyle,\n} from './media';\n\n// ============================================================================\n// VIDEO-SPECIFIC TYPES\n// ============================================================================\n\nexport interface VideoScene {\n description: string;\n setting?: string;\n timeOfDay?: TimeOfDay;\n weather?: WeatherLighting;\n atmosphere?: string;\n}\n\nexport interface VideoSubject {\n main: string;\n appearance?: string;\n clothing?: string;\n age?: string;\n gender?: string;\n count?: number | 'single' | 'couple' | 'group' | 'crowd';\n}\n\nexport interface VideoCamera {\n // Framing\n shot?: ShotType;\n angle?: CameraAngle;\n \n // Camera Body\n brand?: CameraBrand;\n model?: CameraModel;\n sensor?: SensorFormat;\n \n // Lens\n lens?: LensType;\n lensModel?: LensModel;\n lensBrand?: LensBrand;\n focalLength?: string;\n anamorphic?: boolean;\n anamorphicRatio?: '1.33x' | '1.5x' | '1.8x' | '2x';\n \n // Focus\n focus?: 'shallow' | 'deep' | 'rack-focus' | 'pull-focus' | 'split-diopter';\n aperture?: string;\n bokeh?: BokehStyle;\n \n // Movement\n movement?: CameraMovement;\n movementSpeed?: 'slow' | 'medium' | 'fast';\n movementDirection?: 'left' | 'right' | 'forward' | 'backward' | 'up' | 'down' | 'arc-left' | 'arc-right';\n \n // Rig & Stabilization\n rig?: CameraRig;\n gimbal?: GimbalModel;\n platform?: 'handheld' | 'steadicam' | 'tripod' | 'drone' | 'crane' | 'gimbal' | 'slider' | 'dolly' | 'technocrane' | 'russian-arm' | 'fpv-drone';\n \n // Technical\n shutterAngle?: number;\n frameRate?: 24 | 25 | 30 | 48 | 60 | 120 | 240;\n slowMotion?: boolean;\n filter?: FilterType | FilterType[];\n \n // Film Look\n filmStock?: FilmStock;\n filmGrain?: 'none' | 'subtle' | 'moderate' | 'heavy';\n halation?: boolean;\n}\n\nexport interface VideoLighting {\n type?: LightingType | LightingType[];\n time?: TimeOfDay;\n weather?: WeatherLighting;\n direction?: 'front' | 'side' | 'back' | 'top' | 'three-quarter';\n intensity?: 'soft' | 'medium' | 'hard' | 'dramatic';\n sources?: string[];\n color?: string;\n}\n\nexport interface VideoAction {\n beat: number;\n action: string;\n duration?: number;\n timing?: 'start' | 'middle' | 'end';\n}\n\nexport interface VideoMotion {\n subject?: string;\n type?: 'walk' | 'run' | 'gesture' | 'turn' | 'look' | 'reach' | 'sit' | 'stand' | 'custom';\n direction?: 'left' | 'right' | 'forward' | 'backward' | 'up' | 'down';\n speed?: 'slow' | 'normal' | 'fast';\n beats?: string[];\n}\n\nexport interface VideoStyle {\n format?: string;\n era?: string;\n filmStock?: string;\n look?: ArtStyle | ArtStyle[];\n grade?: string;\n reference?: string[];\n}\n\nexport interface VideoColor {\n palette?: ColorPalette | ColorPalette[];\n anchors?: string[];\n temperature?: 'warm' | 'neutral' | 'cool';\n grade?: string;\n}\n\nexport interface VideoAudio {\n diegetic?: string[];\n ambient?: string;\n dialogue?: string;\n music?: string;\n soundEffects?: string[];\n mix?: string;\n}\n\nexport interface VideoTechnical {\n duration?: number;\n resolution?: '480p' | '720p' | '1080p' | '4K';\n fps?: 24 | 30 | 60;\n aspectRatio?: '16:9' | '9:16' | '1:1' | '4:3' | '21:9';\n shutterAngle?: number;\n}\n\nexport interface VideoShot {\n timestamp?: string;\n name?: string;\n camera: VideoCamera;\n action?: string;\n purpose?: string;\n}\n\nexport interface BuiltVideoPrompt {\n prompt: string;\n structure: {\n scene?: VideoScene;\n subject?: VideoSubject;\n camera?: VideoCamera;\n lighting?: VideoLighting;\n actions?: VideoAction[];\n motion?: VideoMotion;\n style?: VideoStyle;\n color?: VideoColor;\n audio?: VideoAudio;\n technical?: VideoTechnical;\n shots?: VideoShot[];\n mood?: Mood | Mood[];\n pacing?: VideoPacing;\n transitions?: VideoTransition[];\n };\n}\n\n// ============================================================================\n// VIDEO PROMPT BUILDER\n// ============================================================================\n\nexport class VideoPromptBuilder {\n private _scene?: VideoScene;\n private _subject?: VideoSubject;\n private _camera?: VideoCamera;\n private _lighting?: VideoLighting;\n private _actions: VideoAction[] = [];\n private _motion?: VideoMotion;\n private _style?: VideoStyle;\n private _color?: VideoColor;\n private _audio?: VideoAudio;\n private _technical?: VideoTechnical;\n private _shots: VideoShot[] = [];\n private _mood?: Mood | Mood[];\n private _pacing?: VideoPacing;\n private _transitions: VideoTransition[] = [];\n private _custom: string[] = [];\n\n // --- Scene Methods ---\n\n scene(description: string | VideoScene): this {\n if (typeof description === 'string') {\n this._scene = { ...(this._scene || { description: '' }), description };\n } else {\n this._scene = { ...(this._scene || { description: '' }), ...description };\n }\n return this;\n }\n\n setting(setting: string): this {\n this._scene = { ...(this._scene || { description: '' }), setting };\n return this;\n }\n\n // --- Subject Methods ---\n\n subject(main: string | VideoSubject): this {\n if (typeof main === 'string') {\n this._subject = { ...(this._subject || { main: '' }), main };\n } else {\n this._subject = { ...(this._subject || { main: '' }), ...main };\n }\n return this;\n }\n\n appearance(appearance: string): this {\n this._subject = { ...(this._subject || { main: '' }), appearance };\n return this;\n }\n\n clothing(clothing: string): this {\n this._subject = { ...(this._subject || { main: '' }), clothing };\n return this;\n }\n\n // --- Camera Methods ---\n\n camera(settings: VideoCamera): this {\n this._camera = { ...(this._camera || {}), ...settings };\n return this;\n }\n\n shot(shot: ShotType): this {\n this._camera = { ...(this._camera || {}), shot };\n return this;\n }\n\n angle(angle: CameraAngle): this {\n this._camera = { ...(this._camera || {}), angle };\n return this;\n }\n\n movement(movement: CameraMovement): this {\n this._camera = { ...(this._camera || {}), movement };\n return this;\n }\n\n lens(lens: LensType): this {\n this._camera = { ...(this._camera || {}), lens };\n return this;\n }\n\n platform(platform: VideoCamera['platform']): this {\n this._camera = { ...(this._camera || {}), platform };\n return this;\n }\n\n cameraSpeed(speed: VideoCamera['movementSpeed']): this {\n this._camera = { ...(this._camera || {}), movementSpeed: speed };\n return this;\n }\n\n movementDirection(direction: VideoCamera['movementDirection']): this {\n this._camera = { ...(this._camera || {}), movementDirection: direction };\n return this;\n }\n\n rig(rig: CameraRig): this {\n this._camera = { ...(this._camera || {}), rig };\n return this;\n }\n\n gimbal(gimbal: GimbalModel): this {\n this._camera = { ...(this._camera || {}), gimbal };\n return this;\n }\n\n cameraBrand(brand: CameraBrand): this {\n this._camera = { ...(this._camera || {}), brand };\n return this;\n }\n\n cameraModel(model: CameraModel): this {\n this._camera = { ...(this._camera || {}), model };\n return this;\n }\n\n sensor(sensor: SensorFormat): this {\n this._camera = { ...(this._camera || {}), sensor };\n return this;\n }\n\n lensModel(model: LensModel): this {\n this._camera = { ...(this._camera || {}), lensModel: model };\n return this;\n }\n\n lensBrand(brand: LensBrand): this {\n this._camera = { ...(this._camera || {}), lensBrand: brand };\n return this;\n }\n\n focalLength(length: string): this {\n this._camera = { ...(this._camera || {}), focalLength: length };\n return this;\n }\n\n anamorphic(ratio?: VideoCamera['anamorphicRatio']): this {\n this._camera = { ...(this._camera || {}), anamorphic: true, anamorphicRatio: ratio };\n return this;\n }\n\n aperture(aperture: string): this {\n this._camera = { ...(this._camera || {}), aperture };\n return this;\n }\n\n frameRate(fps: VideoCamera['frameRate']): this {\n this._camera = { ...(this._camera || {}), frameRate: fps };\n return this;\n }\n\n slowMotion(enabled = true): this {\n this._camera = { ...(this._camera || {}), slowMotion: enabled };\n return this;\n }\n\n shutterAngle(angle: number): this {\n this._camera = { ...(this._camera || {}), shutterAngle: angle };\n return this;\n }\n\n filter(filter: FilterType | FilterType[]): this {\n this._camera = { ...(this._camera || {}), filter };\n return this;\n }\n\n filmStock(stock: FilmStock): this {\n this._camera = { ...(this._camera || {}), filmStock: stock };\n return this;\n }\n\n filmGrain(grain: VideoCamera['filmGrain']): this {\n this._camera = { ...(this._camera || {}), filmGrain: grain };\n return this;\n }\n\n halation(enabled = true): this {\n this._camera = { ...(this._camera || {}), halation: enabled };\n return this;\n }\n\n // --- Lighting Methods ---\n\n lighting(settings: VideoLighting): this {\n this._lighting = { ...(this._lighting || {}), ...settings };\n return this;\n }\n\n lightingType(type: LightingType | LightingType[]): this {\n this._lighting = { ...(this._lighting || {}), type };\n return this;\n }\n\n timeOfDay(time: TimeOfDay): this {\n this._lighting = { ...(this._lighting || {}), time };\n this._scene = { ...(this._scene || { description: '' }), timeOfDay: time };\n return this;\n }\n\n weather(weather: WeatherLighting): this {\n this._lighting = { ...(this._lighting || {}), weather };\n this._scene = { ...(this._scene || { description: '' }), weather };\n return this;\n }\n\n // --- Action & Motion Methods ---\n\n action(action: string, options: Partial<Omit<VideoAction, 'action'>> = {}): this {\n this._actions.push({\n beat: this._actions.length + 1,\n action,\n ...options,\n });\n return this;\n }\n\n actions(actions: string[]): this {\n actions.forEach((a, i) => this._actions.push({ beat: i + 1, action: a }));\n return this;\n }\n\n motion(settings: VideoMotion): this {\n this._motion = { ...(this._motion || {}), ...settings };\n return this;\n }\n\n motionBeats(beats: string[]): this {\n this._motion = { ...(this._motion || {}), beats };\n return this;\n }\n\n // --- Style Methods ---\n\n style(settings: VideoStyle): this {\n this._style = { ...(this._style || {}), ...settings };\n return this;\n }\n\n format(format: string): this {\n this._style = { ...(this._style || {}), format };\n return this;\n }\n\n era(era: string): this {\n this._style = { ...(this._style || {}), era };\n return this;\n }\n\n styleFilmStock(stock: string): this {\n this._style = { ...(this._style || {}), filmStock: stock };\n return this;\n }\n\n look(look: ArtStyle | ArtStyle[]): this {\n this._style = { ...(this._style || {}), look };\n return this;\n }\n\n reference(references: string[]): this {\n this._style = { ...(this._style || {}), reference: references };\n return this;\n }\n\n // --- Color Methods ---\n\n color(settings: VideoColor): this {\n this._color = { ...(this._color || {}), ...settings };\n return this;\n }\n\n palette(palette: ColorPalette | ColorPalette[]): this {\n this._color = { ...(this._color || {}), palette };\n return this;\n }\n\n colorAnchors(anchors: string[]): this {\n this._color = { ...(this._color || {}), anchors };\n return this;\n }\n\n colorGrade(grade: string): this {\n this._color = { ...(this._color || {}), grade };\n return this;\n }\n\n // --- Audio Methods ---\n\n audio(settings: VideoAudio): this {\n this._audio = { ...(this._audio || {}), ...settings };\n return this;\n }\n\n dialogue(dialogue: string): this {\n this._audio = { ...(this._audio || {}), dialogue };\n return this;\n }\n\n ambient(ambient: string): this {\n this._audio = { ...(this._audio || {}), ambient };\n return this;\n }\n\n diegetic(sounds: string[]): this {\n this._audio = { ...(this._audio || {}), diegetic: sounds };\n return this;\n }\n\n soundEffects(effects: string[]): this {\n this._audio = { ...(this._audio || {}), soundEffects: effects };\n return this;\n }\n\n music(music: string): this {\n this._audio = { ...(this._audio || {}), music };\n return this;\n }\n\n // --- Technical Methods ---\n\n technical(settings: VideoTechnical): this {\n this._technical = { ...(this._technical || {}), ...settings };\n return this;\n }\n\n duration(seconds: number): this {\n this._technical = { ...(this._technical || {}), duration: seconds };\n return this;\n }\n\n resolution(res: VideoTechnical['resolution']): this {\n this._technical = { ...(this._technical || {}), resolution: res };\n return this;\n }\n\n fps(fps: VideoTechnical['fps']): this {\n this._technical = { ...(this._technical || {}), fps };\n return this;\n }\n\n aspectRatio(ratio: VideoTechnical['aspectRatio']): this {\n this._technical = { ...(this._technical || {}), aspectRatio: ratio };\n return this;\n }\n\n // --- Shot List Methods ---\n\n addShot(shot: VideoShot): this {\n this._shots.push(shot);\n return this;\n }\n\n shotList(shots: VideoShot[]): this {\n this._shots = [...this._shots, ...shots];\n return this;\n }\n\n // --- Mood & Pacing ---\n\n mood(mood: Mood | Mood[]): this {\n this._mood = mood;\n return this;\n }\n\n pacing(pacing: VideoPacing): this {\n this._pacing = pacing;\n return this;\n }\n\n transition(transition: VideoTransition): this {\n this._transitions.push(transition);\n return this;\n }\n\n transitions(transitions: VideoTransition[]): this {\n this._transitions = [...this._transitions, ...transitions];\n return this;\n }\n\n custom(text: string): this {\n this._custom.push(text);\n return this;\n }\n\n // --- Build Methods ---\n\n private buildPromptText(): string {\n const sections: string[] = [];\n\n // Scene description\n if (this._scene) {\n let sceneText = this._scene.description;\n if (this._scene.setting) sceneText = `${this._scene.setting}. ${sceneText}`;\n if (this._scene.atmosphere) sceneText += `, ${this._scene.atmosphere} atmosphere`;\n sections.push(sceneText);\n }\n\n // Subject\n if (this._subject) {\n let subjectText = this._subject.main;\n if (this._subject.appearance) subjectText += `, ${this._subject.appearance}`;\n if (this._subject.clothing) subjectText += `, wearing ${this._subject.clothing}`;\n sections.push(subjectText);\n }\n\n // Camera & Cinematography\n const cinematography: string[] = [];\n if (this._camera) {\n if (this._camera.shot) cinematography.push(`${this._camera.shot} shot`);\n if (this._camera.angle) cinematography.push(this._camera.angle);\n if (this._camera.movement) cinematography.push(`${this._camera.movement} camera`);\n if (this._camera.lens) cinematography.push(`${this._camera.lens} lens`);\n if (this._camera.platform) cinematography.push(this._camera.platform);\n if (this._camera.focus) cinematography.push(`${this._camera.focus} focus`);\n }\n if (cinematography.length) {\n sections.push(`Cinematography: ${cinematography.join(', ')}`);\n }\n\n // Lighting\n if (this._lighting) {\n const lightParts: string[] = [];\n if (this._lighting.type) {\n const types = Array.isArray(this._lighting.type) ? this._lighting.type : [this._lighting.type];\n lightParts.push(`${types.join(' and ')} lighting`);\n }\n if (this._lighting.time) lightParts.push(this._lighting.time);\n if (this._lighting.weather) lightParts.push(`${this._lighting.weather} weather`);\n if (this._lighting.intensity) lightParts.push(`${this._lighting.intensity} light`);\n if (this._lighting.sources?.length) lightParts.push(`light sources: ${this._lighting.sources.join(', ')}`);\n if (lightParts.length) sections.push(`Lighting: ${lightParts.join(', ')}`);\n }\n\n // Actions\n if (this._actions.length) {\n const actionText = this._actions.map(a => `- ${a.action}`).join('\\n');\n sections.push(`Actions:\\n${actionText}`);\n }\n\n // Motion\n if (this._motion?.beats?.length) {\n sections.push(`Motion beats: ${this._motion.beats.join(', ')}`);\n }\n\n // Style\n if (this._style) {\n const styleParts: string[] = [];\n if (this._style.format) styleParts.push(this._style.format);\n if (this._style.era) styleParts.push(this._style.era);\n if (this._style.filmStock) styleParts.push(`shot on ${this._style.filmStock}`);\n if (this._style.look) {\n const looks = Array.isArray(this._style.look) ? this._style.look : [this._style.look];\n styleParts.push(looks.join(', '));\n }\n if (styleParts.length) sections.push(`Style: ${styleParts.join(', ')}`);\n }\n\n // Color\n if (this._color) {\n const colorParts: string[] = [];\n if (this._color.palette) {\n const palettes = Array.isArray(this._color.palette) ? this._color.palette : [this._color.palette];\n colorParts.push(`${palettes.join(' and ')} palette`);\n }\n if (this._color.anchors?.length) colorParts.push(`color anchors: ${this._color.anchors.join(', ')}`);\n if (this._color.grade) colorParts.push(this._color.grade);\n if (colorParts.length) sections.push(`Color: ${colorParts.join(', ')}`);\n }\n\n // Audio\n if (this._audio) {\n const audioParts: string[] = [];\n if (this._audio.dialogue) audioParts.push(`Dialogue: \"${this._audio.dialogue}\"`);\n if (this._audio.ambient) audioParts.push(`Ambient: ${this._audio.ambient}`);\n if (this._audio.diegetic?.length) audioParts.push(`Diegetic sounds: ${this._audio.diegetic.join(', ')}`);\n if (this._audio.music) audioParts.push(`Music: ${this._audio.music}`);\n if (audioParts.length) sections.push(`Audio:\\n${audioParts.join('\\n')}`);\n }\n\n // Mood & Pacing\n if (this._mood) {\n const moods = Array.isArray(this._mood) ? this._mood : [this._mood];\n sections.push(`Mood: ${moods.join(', ')}`);\n }\n if (this._pacing) {\n sections.push(`Pacing: ${this._pacing}`);\n }\n\n // Custom\n if (this._custom.length) {\n sections.push(this._custom.join('\\n'));\n }\n\n return sections.join('\\n\\n');\n }\n\n build(): BuiltVideoPrompt {\n return {\n prompt: this.buildPromptText(),\n structure: {\n scene: this._scene,\n subject: this._subject,\n camera: this._camera,\n lighting: this._lighting,\n actions: this._actions.length ? this._actions : undefined,\n motion: this._motion,\n style: this._style,\n color: this._color,\n audio: this._audio,\n technical: this._technical,\n shots: this._shots.length ? this._shots : undefined,\n mood: this._mood,\n pacing: this._pacing,\n transitions: this._transitions.length ? this._transitions : undefined,\n },\n };\n }\n\n toString(): string {\n return this.build().prompt;\n }\n\n toJSON(): string {\n return JSON.stringify(this.build().structure, null, 2);\n }\n\n toYAML(): string {\n return objectToYaml(this.build().structure);\n }\n\n toMarkdown(): string {\n const built = this.build();\n const sections: string[] = ['# Video Prompt\\n'];\n \n sections.push('## Prompt\\n```\\n' + built.prompt + '\\n```\\n');\n \n if (built.structure.scene) {\n sections.push('## Scene\\n' + objectToMarkdownList(built.structure.scene));\n }\n if (built.structure.subject) {\n sections.push('## Subject\\n' + objectToMarkdownList(built.structure.subject));\n }\n if (built.structure.camera) {\n sections.push('## Camera\\n' + objectToMarkdownList(built.structure.camera));\n }\n if (built.structure.lighting) {\n sections.push('## Lighting\\n' + objectToMarkdownList(built.structure.lighting));\n }\n if (built.structure.actions) {\n sections.push('## Actions\\n' + built.structure.actions.map(a => `- **Beat ${a.beat}:** ${a.action}`).join('\\n'));\n }\n if (built.structure.style) {\n sections.push('## Style\\n' + objectToMarkdownList(built.structure.style));\n }\n if (built.structure.audio) {\n sections.push('## Audio\\n' + objectToMarkdownList(built.structure.audio));\n }\n if (built.structure.technical) {\n sections.push('## Technical\\n' + objectToMarkdownList(built.structure.technical));\n }\n \n return sections.join('\\n');\n }\n\n outputFormat(fmt: OutputFormat): string {\n switch (fmt) {\n case 'json': return this.toJSON();\n case 'yaml': return this.toYAML();\n case 'markdown': return this.toMarkdown();\n default: return this.toString();\n }\n }\n}\n\n// ============================================================================\n// HELPER FUNCTIONS\n// ============================================================================\n\nfunction objectToYaml(obj: object, indent = 0): string {\n const spaces = ' '.repeat(indent);\n const lines: string[] = [];\n \n for (const [key, value] of Object.entries(obj)) {\n if (value === undefined || value === null) continue;\n \n if (Array.isArray(value)) {\n if (value.length === 0) continue;\n lines.push(`${spaces}${key}:`);\n for (const item of value) {\n if (typeof item === 'object') {\n lines.push(`${spaces} -`);\n lines.push(objectToYaml(item, indent + 2).replace(/^/gm, ' '));\n } else {\n lines.push(`${spaces} - ${item}`);\n }\n }\n } else if (typeof value === 'object') {\n lines.push(`${spaces}${key}:`);\n lines.push(objectToYaml(value, indent + 1));\n } else {\n lines.push(`${spaces}${key}: ${value}`);\n }\n }\n \n return lines.join('\\n');\n}\n\nfunction objectToMarkdownList(obj: object, indent = 0): string {\n const spaces = ' '.repeat(indent);\n const lines: string[] = [];\n \n for (const [key, value] of Object.entries(obj)) {\n if (value === undefined || value === null) continue;\n \n if (Array.isArray(value)) {\n lines.push(`${spaces}- **${key}:** ${value.join(', ')}`);\n } else if (typeof value === 'object') {\n lines.push(`${spaces}- **${key}:**`);\n lines.push(objectToMarkdownList(value, indent + 1));\n } else {\n lines.push(`${spaces}- **${key}:** ${value}`);\n }\n }\n \n return lines.join('\\n');\n}\n\n// ============================================================================\n// FACTORY FUNCTION\n// ============================================================================\n\n/**\n * Create a new video prompt builder\n */\nexport function video(): VideoPromptBuilder {\n return new VideoPromptBuilder();\n}\n","/**\n * Audio/Music Prompt Builder - Comprehensive music generation prompt builder\n * \n * Based on Suno, Udio, and other music generation best practices.\n * \n * @example\n * ```ts\n * import { audio } from 'prompts.chat/builder';\n * \n * const prompt = audio()\n * .genre(\"synthwave\")\n * .mood(\"nostalgic\", \"dreamy\")\n * .tempo(110)\n * .instruments([\"synthesizer\", \"drums\", \"bass\"])\n * .structure({ intro: 8, verse: 16, chorus: 16 })\n * .build();\n * ```\n */\n\nimport type { Mood, OutputFormat } from './media';\n\n// ============================================================================\n// AUDIO-SPECIFIC TYPES\n// ============================================================================\n\nexport type MusicGenre = \n | 'pop' | 'rock' | 'jazz' | 'classical' | 'electronic' | 'hip-hop' | 'r&b'\n | 'country' | 'folk' | 'blues' | 'metal' | 'punk' | 'indie' | 'alternative'\n | 'ambient' | 'lo-fi' | 'synthwave' | 'orchestral' | 'cinematic' | 'world'\n | 'latin' | 'reggae' | 'soul' | 'funk' | 'disco' | 'house' | 'techno' | 'edm'\n | 'trap' | 'drill' | 'k-pop' | 'j-pop' | 'bossa-nova' | 'gospel' | 'grunge'\n | 'shoegaze' | 'post-rock' | 'prog-rock' | 'psychedelic' | 'chillwave'\n | 'vaporwave' | 'drum-and-bass' | 'dubstep' | 'trance' | 'hardcore';\n\nexport type Instrument = \n | 'piano' | 'guitar' | 'acoustic-guitar' | 'electric-guitar' | 'bass' | 'drums'\n | 'violin' | 'cello' | 'viola' | 'flute' | 'saxophone' | 'trumpet' | 'trombone'\n | 'synthesizer' | 'organ' | 'harp' | 'percussion' | 'strings' | 'brass' | 'woodwinds'\n | 'choir' | 'vocals' | 'beatbox' | 'turntables' | 'harmonica' | 'banjo' | 'ukulele'\n | 'mandolin' | 'accordion' | 'marimba' | 'vibraphone' | 'xylophone' | 'timpani'\n | 'congas' | 'bongos' | 'djembe' | 'tabla' | 'sitar' | 'erhu' | 'koto'\n | '808' | '909' | 'moog' | 'rhodes' | 'wurlitzer' | 'mellotron' | 'theremin';\n\nexport type VocalStyle = \n | 'male' | 'female' | 'duet' | 'choir' | 'a-cappella' | 'spoken-word' | 'rap'\n | 'falsetto' | 'belting' | 'whisper' | 'growl' | 'melodic' | 'harmonized'\n | 'auto-tuned' | 'operatic' | 'soul' | 'breathy' | 'nasal' | 'raspy' | 'clear';\n\nexport type VocalLanguage =\n | 'english' | 'spanish' | 'french' | 'german' | 'italian' | 'portuguese'\n | 'japanese' | 'korean' | 'chinese' | 'arabic' | 'hindi' | 'russian' | 'turkish'\n | 'instrumental';\n\nexport type TempoMarking = \n | 'largo' | 'adagio' | 'andante' | 'moderato' | 'allegro' | 'vivace' | 'presto';\n\nexport type TimeSignature = '4/4' | '3/4' | '6/8' | '2/4' | '5/4' | '7/8' | '12/8';\n\nexport type MusicalKey = \n | 'C' | 'C#' | 'Db' | 'D' | 'D#' | 'Eb' | 'E' | 'F' | 'F#' | 'Gb' \n | 'G' | 'G#' | 'Ab' | 'A' | 'A#' | 'Bb' | 'B'\n | 'Cm' | 'C#m' | 'Dm' | 'D#m' | 'Ebm' | 'Em' | 'Fm' | 'F#m' \n | 'Gm' | 'G#m' | 'Am' | 'A#m' | 'Bbm' | 'Bm';\n\nexport type SongSection = \n | 'intro' | 'verse' | 'pre-chorus' | 'chorus' | 'bridge' | 'breakdown'\n | 'drop' | 'build-up' | 'outro' | 'solo' | 'interlude' | 'hook';\n\nexport type ProductionStyle =\n | 'lo-fi' | 'hi-fi' | 'vintage' | 'modern' | 'polished' | 'raw' | 'organic'\n | 'synthetic' | 'acoustic' | 'electric' | 'hybrid' | 'minimalist' | 'maximalist'\n | 'layered' | 'sparse' | 'dense' | 'atmospheric' | 'punchy' | 'warm' | 'bright';\n\nexport type Era =\n | '1950s' | '1960s' | '1970s' | '1980s' | '1990s' | '2000s' | '2010s' | '2020s'\n | 'retro' | 'vintage' | 'classic' | 'modern' | 'futuristic';\n\n// ============================================================================\n// AUDIO INTERFACES\n// ============================================================================\n\nexport interface AudioGenre {\n primary: MusicGenre;\n secondary?: MusicGenre[];\n subgenre?: string;\n fusion?: string[];\n}\n\nexport interface AudioMood {\n primary: Mood | string;\n secondary?: (Mood | string)[];\n energy?: 'low' | 'medium' | 'high' | 'building' | 'fluctuating';\n emotion?: string;\n}\n\nexport interface AudioTempo {\n bpm?: number;\n marking?: TempoMarking;\n feel?: 'steady' | 'swung' | 'shuffled' | 'syncopated' | 'rubato' | 'driving';\n variation?: boolean;\n}\n\nexport interface AudioVocals {\n style?: VocalStyle | VocalStyle[];\n language?: VocalLanguage;\n lyrics?: string;\n theme?: string;\n delivery?: string;\n harmonies?: boolean;\n adlibs?: boolean;\n}\n\nexport interface AudioInstrumentation {\n lead?: Instrument | Instrument[];\n rhythm?: Instrument | Instrument[];\n bass?: Instrument;\n percussion?: Instrument | Instrument[];\n pads?: Instrument | Instrument[];\n effects?: string[];\n featured?: Instrument;\n}\n\nexport interface AudioStructure {\n sections?: Array<{\n type: SongSection;\n bars?: number;\n description?: string;\n }>;\n intro?: number;\n verse?: number;\n chorus?: number;\n bridge?: number;\n outro?: number;\n form?: string;\n duration?: number;\n}\n\nexport interface AudioProduction {\n style?: ProductionStyle | ProductionStyle[];\n era?: Era;\n reference?: string[];\n mix?: string;\n mastering?: string;\n effects?: string[];\n texture?: string;\n}\n\nexport interface AudioTechnical {\n key?: MusicalKey;\n timeSignature?: TimeSignature;\n duration?: number;\n format?: 'song' | 'instrumental' | 'jingle' | 'loop' | 'soundtrack';\n}\n\nexport interface BuiltAudioPrompt {\n prompt: string;\n stylePrompt: string;\n lyricsPrompt?: string;\n structure: {\n genre?: AudioGenre;\n mood?: AudioMood;\n tempo?: AudioTempo;\n vocals?: AudioVocals;\n instrumentation?: AudioInstrumentation;\n structure?: AudioStructure;\n production?: AudioProduction;\n technical?: AudioTechnical;\n tags?: string[];\n };\n}\n\n// ============================================================================\n// AUDIO PROMPT BUILDER\n// ============================================================================\n\nexport class AudioPromptBuilder {\n private _genre?: AudioGenre;\n private _mood?: AudioMood;\n private _tempo?: AudioTempo;\n private _vocals?: AudioVocals;\n private _instrumentation?: AudioInstrumentation;\n private _structure?: AudioStructure;\n private _production?: AudioProduction;\n private _technical?: AudioTechnical;\n private _tags: string[] = [];\n private _custom: string[] = [];\n\n // --- Genre Methods ---\n\n genre(primary: MusicGenre | AudioGenre): this {\n if (typeof primary === 'string') {\n this._genre = { ...(this._genre || { primary: 'pop' }), primary };\n } else {\n this._genre = { ...(this._genre || { primary: 'pop' }), ...primary };\n }\n return this;\n }\n\n subgenre(subgenre: string): this {\n this._genre = { ...(this._genre || { primary: 'pop' }), subgenre };\n return this;\n }\n\n fusion(genres: MusicGenre[]): this {\n this._genre = { \n ...(this._genre || { primary: 'pop' }), \n secondary: genres,\n fusion: genres as string[],\n };\n return this;\n }\n\n // --- Mood Methods ---\n\n mood(primary: Mood | string, ...secondary: (Mood | string)[]): this {\n this._mood = { \n primary, \n secondary: secondary.length ? secondary : undefined,\n };\n return this;\n }\n\n energy(level: AudioMood['energy']): this {\n this._mood = { ...(this._mood || { primary: 'energetic' }), energy: level };\n return this;\n }\n\n emotion(emotion: string): this {\n this._mood = { ...(this._mood || { primary: 'emotional' }), emotion };\n return this;\n }\n\n // --- Tempo Methods ---\n\n tempo(bpmOrSettings: number | AudioTempo): this {\n if (typeof bpmOrSettings === 'number') {\n this._tempo = { ...(this._tempo || {}), bpm: bpmOrSettings };\n } else {\n this._tempo = { ...(this._tempo || {}), ...bpmOrSettings };\n }\n return this;\n }\n\n bpm(bpm: number): this {\n this._tempo = { ...(this._tempo || {}), bpm };\n return this;\n }\n\n tempoMarking(marking: TempoMarking): this {\n this._tempo = { ...(this._tempo || {}), marking };\n return this;\n }\n\n tempoFeel(feel: AudioTempo['feel']): this {\n this._tempo = { ...(this._tempo || {}), feel };\n return this;\n }\n\n // --- Vocal Methods ---\n\n vocals(settings: AudioVocals): this {\n this._vocals = { ...(this._vocals || {}), ...settings };\n return this;\n }\n\n vocalStyle(style: VocalStyle | VocalStyle[]): this {\n this._vocals = { ...(this._vocals || {}), style };\n return this;\n }\n\n language(language: VocalLanguage): this {\n this._vocals = { ...(this._vocals || {}), language };\n return this;\n }\n\n lyrics(lyrics: string): this {\n this._vocals = { ...(this._vocals || {}), lyrics };\n return this;\n }\n\n lyricsTheme(theme: string): this {\n this._vocals = { ...(this._vocals || {}), theme };\n return this;\n }\n\n delivery(delivery: string): this {\n this._vocals = { ...(this._vocals || {}), delivery };\n return this;\n }\n\n instrumental(): this {\n this._vocals = { ...(this._vocals || {}), language: 'instrumental' };\n return this;\n }\n\n // --- Instrumentation Methods ---\n\n instruments(instruments: Instrument[]): this {\n this._instrumentation = { \n ...(this._instrumentation || {}), \n lead: instruments,\n };\n return this;\n }\n\n instrumentation(settings: AudioInstrumentation): this {\n this._instrumentation = { ...(this._instrumentation || {}), ...settings };\n return this;\n }\n\n leadInstrument(instrument: Instrument | Instrument[]): this {\n this._instrumentation = { ...(this._instrumentation || {}), lead: instrument };\n return this;\n }\n\n rhythmSection(instruments: Instrument[]): this {\n this._instrumentation = { ...(this._instrumentation || {}), rhythm: instruments };\n return this;\n }\n\n bassInstrument(instrument: Instrument): this {\n this._instrumentation = { ...(this._instrumentation || {}), bass: instrument };\n return this;\n }\n\n percussion(instruments: Instrument | Instrument[]): this {\n this._instrumentation = { ...(this._instrumentation || {}), percussion: instruments };\n return this;\n }\n\n pads(instruments: Instrument | Instrument[]): this {\n this._instrumentation = { ...(this._instrumentation || {}), pads: instruments };\n return this;\n }\n\n featuredInstrument(instrument: Instrument): this {\n this._instrumentation = { ...(this._instrumentation || {}), featured: instrument };\n return this;\n }\n\n // --- Structure Methods ---\n\n structure(settings: AudioStructure | { [key in SongSection]?: number }): this {\n if ('sections' in settings || 'form' in settings || 'duration' in settings) {\n this._structure = { ...(this._structure || {}), ...settings as AudioStructure };\n } else {\n // Convert shorthand to full structure\n const sections: AudioStructure['sections'] = [];\n for (const [type, bars] of Object.entries(settings)) {\n if (typeof bars === 'number') {\n sections.push({ type: type as SongSection, bars });\n }\n }\n this._structure = { ...(this._structure || {}), sections };\n }\n return this;\n }\n\n section(type: SongSection, bars?: number, description?: string): this {\n const sections = this._structure?.sections || [];\n sections.push({ type, bars, description });\n this._structure = { ...(this._structure || {}), sections };\n return this;\n }\n\n form(form: string): this {\n this._structure = { ...(this._structure || {}), form };\n return this;\n }\n\n duration(seconds: number): this {\n this._structure = { ...(this._structure || {}), duration: seconds };\n return this;\n }\n\n // --- Production Methods ---\n\n production(settings: AudioProduction): this {\n this._production = { ...(this._production || {}), ...settings };\n return this;\n }\n\n productionStyle(style: ProductionStyle | ProductionStyle[]): this {\n this._production = { ...(this._production || {}), style };\n return this;\n }\n\n era(era: Era): this {\n this._production = { ...(this._production || {}), era };\n return this;\n }\n\n reference(artists: string[]): this {\n this._production = { ...(this._production || {}), reference: artists };\n return this;\n }\n\n texture(texture: string): this {\n this._production = { ...(this._production || {}), texture };\n return this;\n }\n\n effects(effects: string[]): this {\n this._production = { ...(this._production || {}), effects };\n return this;\n }\n\n // --- Technical Methods ---\n\n technical(settings: AudioTechnical): this {\n this._technical = { ...(this._technical || {}), ...settings };\n return this;\n }\n\n key(key: MusicalKey): this {\n this._technical = { ...(this._technical || {}), key };\n return this;\n }\n\n timeSignature(sig: TimeSignature): this {\n this._technical = { ...(this._technical || {}), timeSignature: sig };\n return this;\n }\n\n formatType(format: AudioTechnical['format']): this {\n this._technical = { ...(this._technical || {}), format };\n return this;\n }\n\n // --- Tags & Custom ---\n\n tag(tag: string): this {\n this._tags.push(tag);\n return this;\n }\n\n tags(tags: string[]): this {\n this._tags = [...this._tags, ...tags];\n return this;\n }\n\n custom(text: string): this {\n this._custom.push(text);\n return this;\n }\n\n // --- Build Methods ---\n\n private buildStylePrompt(): string {\n const parts: string[] = [];\n\n // Genre\n if (this._genre) {\n let genreText: string = this._genre.primary;\n if (this._genre.subgenre) genreText = `${this._genre.subgenre} ${genreText}`;\n if (this._genre.secondary?.length) {\n genreText += ` with ${this._genre.secondary.join(' and ')} influences`;\n }\n parts.push(genreText);\n }\n\n // Mood\n if (this._mood) {\n let moodText = String(this._mood.primary);\n if (this._mood.secondary?.length) {\n moodText += `, ${this._mood.secondary.join(', ')}`;\n }\n if (this._mood.energy) moodText += `, ${this._mood.energy} energy`;\n parts.push(moodText);\n }\n\n // Tempo\n if (this._tempo) {\n const tempoParts: string[] = [];\n if (this._tempo.bpm) tempoParts.push(`${this._tempo.bpm} BPM`);\n if (this._tempo.marking) tempoParts.push(this._tempo.marking);\n if (this._tempo.feel) tempoParts.push(`${this._tempo.feel} feel`);\n if (tempoParts.length) parts.push(tempoParts.join(', '));\n }\n\n // Instrumentation\n if (this._instrumentation) {\n const instrParts: string[] = [];\n if (this._instrumentation.lead) {\n const leads = Array.isArray(this._instrumentation.lead) \n ? this._instrumentation.lead : [this._instrumentation.lead];\n instrParts.push(leads.join(', '));\n }\n if (this._instrumentation.featured) {\n instrParts.push(`featuring ${this._instrumentation.featured}`);\n }\n if (instrParts.length) parts.push(instrParts.join(', '));\n }\n\n // Vocals\n if (this._vocals) {\n const vocalParts: string[] = [];\n if (this._vocals.language === 'instrumental') {\n vocalParts.push('instrumental');\n } else {\n if (this._vocals.style) {\n const styles = Array.isArray(this._vocals.style) \n ? this._vocals.style : [this._vocals.style];\n vocalParts.push(`${styles.join(' and ')} vocals`);\n }\n if (this._vocals.language && this._vocals.language !== 'english') {\n vocalParts.push(`in ${this._vocals.language}`);\n }\n }\n if (vocalParts.length) parts.push(vocalParts.join(' '));\n }\n\n // Production\n if (this._production) {\n const prodParts: string[] = [];\n if (this._production.style) {\n const styles = Array.isArray(this._production.style) \n ? this._production.style : [this._production.style];\n prodParts.push(`${styles.join(', ')} production`);\n }\n if (this._production.era) prodParts.push(`${this._production.era} sound`);\n if (this._production.texture) prodParts.push(this._production.texture);\n if (prodParts.length) parts.push(prodParts.join(', '));\n }\n\n // Technical\n if (this._technical) {\n const techParts: string[] = [];\n if (this._technical.key) techParts.push(`in the key of ${this._technical.key}`);\n if (this._technical.timeSignature && this._technical.timeSignature !== '4/4') {\n techParts.push(`${this._technical.timeSignature} time`);\n }\n if (techParts.length) parts.push(techParts.join(', '));\n }\n\n // Tags\n if (this._tags.length) {\n parts.push(this._tags.join(', '));\n }\n\n // Custom\n if (this._custom.length) {\n parts.push(this._custom.join(', '));\n }\n\n return parts.join(', ');\n }\n\n private buildLyricsPrompt(): string | undefined {\n if (!this._vocals?.lyrics && !this._vocals?.theme) return undefined;\n\n const parts: string[] = [];\n\n if (this._vocals.theme) {\n parts.push(`Theme: ${this._vocals.theme}`);\n }\n\n if (this._vocals.lyrics) {\n parts.push(this._vocals.lyrics);\n }\n\n return parts.join('\\n\\n');\n }\n\n private buildFullPrompt(): string {\n const sections: string[] = [];\n\n sections.push(`Style: ${this.buildStylePrompt()}`);\n\n if (this._structure?.sections?.length) {\n const structureText = this._structure.sections\n .map(s => `[${s.type.toUpperCase()}]${s.description ? ` ${s.description}` : ''}`)\n .join('\\n');\n sections.push(`Structure:\\n${structureText}`);\n }\n\n const lyrics = this.buildLyricsPrompt();\n if (lyrics) {\n sections.push(`Lyrics:\\n${lyrics}`);\n }\n\n return sections.join('\\n\\n');\n }\n\n build(): BuiltAudioPrompt {\n return {\n prompt: this.buildFullPrompt(),\n stylePrompt: this.buildStylePrompt(),\n lyricsPrompt: this.buildLyricsPrompt(),\n structure: {\n genre: this._genre,\n mood: this._mood,\n tempo: this._tempo,\n vocals: this._vocals,\n instrumentation: this._instrumentation,\n structure: this._structure,\n production: this._production,\n technical: this._technical,\n tags: this._tags.length ? this._tags : undefined,\n },\n };\n }\n\n toString(): string {\n return this.build().prompt;\n }\n\n toStyleString(): string {\n return this.build().stylePrompt;\n }\n\n toJSON(): string {\n return JSON.stringify(this.build().structure, null, 2);\n }\n\n toYAML(): string {\n return objectToYaml(this.build().structure);\n }\n\n toMarkdown(): string {\n const built = this.build();\n const sections: string[] = ['# Audio Prompt\\n'];\n \n sections.push('## Style Prompt\\n```\\n' + built.stylePrompt + '\\n```\\n');\n \n if (built.lyricsPrompt) {\n sections.push('## Lyrics\\n```\\n' + built.lyricsPrompt + '\\n```\\n');\n }\n \n if (built.structure.genre) {\n sections.push('## Genre\\n' + objectToMarkdownList(built.structure.genre));\n }\n if (built.structure.mood) {\n sections.push('## Mood\\n' + objectToMarkdownList(built.structure.mood));\n }\n if (built.structure.tempo) {\n sections.push('## Tempo\\n' + objectToMarkdownList(built.structure.tempo));\n }\n if (built.structure.vocals) {\n sections.push('## Vocals\\n' + objectToMarkdownList(built.structure.vocals));\n }\n if (built.structure.instrumentation) {\n sections.push('## Instrumentation\\n' + objectToMarkdownList(built.structure.instrumentation));\n }\n if (built.structure.production) {\n sections.push('## Production\\n' + objectToMarkdownList(built.structure.production));\n }\n \n return sections.join('\\n');\n }\n\n outputFormat(fmt: OutputFormat): string {\n switch (fmt) {\n case 'json': return this.toJSON();\n case 'yaml': return this.toYAML();\n case 'markdown': return this.toMarkdown();\n default: return this.toString();\n }\n }\n}\n\n// ============================================================================\n// HELPER FUNCTIONS\n// ============================================================================\n\nfunction objectToYaml(obj: object, indent = 0): string {\n const spaces = ' '.repeat(indent);\n const lines: string[] = [];\n \n for (const [key, value] of Object.entries(obj)) {\n if (value === undefined || value === null) continue;\n \n if (Array.isArray(value)) {\n if (value.length === 0) continue;\n lines.push(`${spaces}${key}:`);\n for (const item of value) {\n if (typeof item === 'object') {\n lines.push(`${spaces} -`);\n lines.push(objectToYaml(item, indent + 2).replace(/^/gm, ' '));\n } else {\n lines.push(`${spaces} - ${item}`);\n }\n }\n } else if (typeof value === 'object') {\n lines.push(`${spaces}${key}:`);\n lines.push(objectToYaml(value, indent + 1));\n } else {\n lines.push(`${spaces}${key}: ${value}`);\n }\n }\n \n return lines.join('\\n');\n}\n\nfunction objectToMarkdownList(obj: object, indent = 0): string {\n const spaces = ' '.repeat(indent);\n const lines: string[] = [];\n \n for (const [key, value] of Object.entries(obj)) {\n if (value === undefined || value === null) continue;\n \n if (Array.isArray(value)) {\n lines.push(`${spaces}- **${key}:** ${value.join(', ')}`);\n } else if (typeof value === 'object') {\n lines.push(`${spaces}- **${key}:**`);\n lines.push(objectToMarkdownList(value, indent + 1));\n } else {\n lines.push(`${spaces}- **${key}:** ${value}`);\n }\n }\n \n return lines.join('\\n');\n}\n\n// ============================================================================\n// FACTORY FUNCTION\n// ============================================================================\n\n/**\n * Create a new audio/music prompt builder\n */\nexport function audio(): AudioPromptBuilder {\n return new AudioPromptBuilder();\n}\n","/**\n * Chat Prompt Builder - Model-Agnostic Conversation Prompt Builder\n * \n * Build structured prompts for any chat/conversation model.\n * Focus on prompt engineering, not model-specific features.\n * \n * @example\n * ```ts\n * import { chat } from 'prompts.chat/builder';\n * \n * const prompt = chat()\n * .role(\"helpful coding assistant\")\n * .context(\"Building a React application\")\n * .task(\"Explain async/await in JavaScript\")\n * .stepByStep()\n * .detailed()\n * .build();\n * ```\n */\n\n// ============================================================================\n// TYPES & INTERFACES\n// ============================================================================\n\n// --- Message Types ---\nexport type MessageRole = 'system' | 'user' | 'assistant';\n\nexport interface ChatMessage {\n role: MessageRole;\n content: string;\n name?: string;\n}\n\n// --- Response Format Types ---\nexport type ResponseFormatType = 'text' | 'json' | 'markdown' | 'code' | 'table';\n\nexport interface JsonSchema {\n name: string;\n description?: string;\n schema: Record<string, unknown>;\n}\n\nexport interface ResponseFormat {\n type: ResponseFormatType;\n jsonSchema?: JsonSchema;\n language?: string;\n}\n\n// --- Persona Types ---\nexport type PersonaTone = \n | 'professional' | 'casual' | 'formal' | 'friendly' | 'academic'\n | 'technical' | 'creative' | 'empathetic' | 'authoritative' | 'playful'\n | 'concise' | 'detailed' | 'socratic' | 'coaching' | 'analytical'\n | 'encouraging' | 'neutral' | 'humorous' | 'serious';\n\nexport type PersonaExpertise = \n | 'general' | 'coding' | 'writing' | 'analysis' | 'research'\n | 'teaching' | 'counseling' | 'creative' | 'legal' | 'medical'\n | 'financial' | 'scientific' | 'engineering' | 'design' | 'marketing'\n | 'business' | 'philosophy' | 'history' | 'languages' | 'mathematics';\n\n// --- Reasoning Types ---\nexport type ReasoningStyle = \n | 'step-by-step' | 'chain-of-thought' | 'tree-of-thought' \n | 'direct' | 'analytical' | 'comparative' | 'deductive' | 'inductive'\n | 'first-principles' | 'analogical' | 'devil-advocate';\n\n// --- Output Types ---\nexport type OutputLength = 'brief' | 'moderate' | 'detailed' | 'comprehensive' | 'exhaustive';\nexport type OutputStyle = 'prose' | 'bullet-points' | 'numbered-list' | 'table' | 'code' | 'mixed' | 'qa' | 'dialogue';\n\n// ============================================================================\n// INTERFACES\n// ============================================================================\n\nexport interface ChatPersona {\n name?: string;\n role?: string;\n tone?: PersonaTone | PersonaTone[];\n expertise?: PersonaExpertise | PersonaExpertise[];\n personality?: string[];\n background?: string;\n language?: string;\n verbosity?: OutputLength;\n}\n\nexport interface ChatContext {\n background?: string;\n domain?: string;\n audience?: string;\n purpose?: string;\n constraints?: string[];\n assumptions?: string[];\n knowledge?: string[];\n}\n\nexport interface ChatTask {\n instruction: string;\n steps?: string[];\n deliverables?: string[];\n criteria?: string[];\n antiPatterns?: string[];\n priority?: 'accuracy' | 'speed' | 'creativity' | 'thoroughness';\n}\n\nexport interface ChatOutput {\n format?: ResponseFormat;\n length?: OutputLength;\n style?: OutputStyle;\n language?: string;\n includeExplanation?: boolean;\n includeExamples?: boolean;\n includeSources?: boolean;\n includeConfidence?: boolean;\n}\n\nexport interface ChatReasoning {\n style?: ReasoningStyle;\n showWork?: boolean;\n verifyAnswer?: boolean;\n considerAlternatives?: boolean;\n explainAssumptions?: boolean;\n}\n\nexport interface ChatExample {\n input: string;\n output: string;\n explanation?: string;\n}\n\nexport interface ChatMemory {\n summary?: string;\n facts?: string[];\n preferences?: string[];\n history?: ChatMessage[];\n}\n\nexport interface BuiltChatPrompt {\n messages: ChatMessage[];\n systemPrompt: string;\n userPrompt?: string;\n metadata: {\n persona?: ChatPersona;\n context?: ChatContext;\n task?: ChatTask;\n output?: ChatOutput;\n reasoning?: ChatReasoning;\n examples?: ChatExample[];\n };\n}\n\n// ============================================================================\n// CHAT PROMPT BUILDER\n// ============================================================================\n\nexport class ChatPromptBuilder {\n private _messages: ChatMessage[] = [];\n private _persona?: ChatPersona;\n private _context?: ChatContext;\n private _task?: ChatTask;\n private _output?: ChatOutput;\n private _reasoning?: ChatReasoning;\n private _examples: ChatExample[] = [];\n private _memory?: ChatMemory;\n private _customSystemParts: string[] = [];\n\n // --- Message Methods ---\n\n system(content: string): this {\n // Remove existing system message and add new one at beginning\n this._messages = this._messages.filter(m => m.role !== 'system');\n this._messages.unshift({ role: 'system', content });\n return this;\n }\n\n user(content: string, name?: string): this {\n this._messages.push({ role: 'user', content, name });\n return this;\n }\n\n assistant(content: string): this {\n this._messages.push({ role: 'assistant', content });\n return this;\n }\n\n message(role: MessageRole, content: string, name?: string): this {\n this._messages.push({ role, content, name });\n return this;\n }\n\n messages(messages: ChatMessage[]): this {\n this._messages = [...this._messages, ...messages];\n return this;\n }\n\n conversation(turns: Array<{ user: string; assistant?: string }>): this {\n for (const turn of turns) {\n this.user(turn.user);\n if (turn.assistant) {\n this.assistant(turn.assistant);\n }\n }\n return this;\n }\n\n // --- Persona Methods ---\n\n persona(settings: ChatPersona | string): this {\n if (typeof settings === 'string') {\n this._persona = { ...(this._persona || {}), role: settings };\n } else {\n this._persona = { ...(this._persona || {}), ...settings };\n }\n return this;\n }\n\n role(role: string): this {\n this._persona = { ...(this._persona || {}), role };\n return this;\n }\n\n tone(tone: PersonaTone | PersonaTone[]): this {\n this._persona = { ...(this._persona || {}), tone };\n return this;\n }\n\n expertise(expertise: PersonaExpertise | PersonaExpertise[]): this {\n this._persona = { ...(this._persona || {}), expertise };\n return this;\n }\n\n personality(traits: string[]): this {\n this._persona = { ...(this._persona || {}), personality: traits };\n return this;\n }\n\n background(background: string): this {\n this._persona = { ...(this._persona || {}), background };\n return this;\n }\n\n speakAs(name: string): this {\n this._persona = { ...(this._persona || {}), name };\n return this;\n }\n\n responseLanguage(language: string): this {\n this._persona = { ...(this._persona || {}), language };\n return this;\n }\n\n // --- Context Methods ---\n\n context(settings: ChatContext | string): this {\n if (typeof settings === 'string') {\n this._context = { ...(this._context || {}), background: settings };\n } else {\n this._context = { ...(this._context || {}), ...settings };\n }\n return this;\n }\n\n domain(domain: string): this {\n this._context = { ...(this._context || {}), domain };\n return this;\n }\n\n audience(audience: string): this {\n this._context = { ...(this._context || {}), audience };\n return this;\n }\n\n purpose(purpose: string): this {\n this._context = { ...(this._context || {}), purpose };\n return this;\n }\n\n constraints(constraints: string[]): this {\n const existing = this._context?.constraints || [];\n this._context = { ...(this._context || {}), constraints: [...existing, ...constraints] };\n return this;\n }\n\n constraint(constraint: string): this {\n return this.constraints([constraint]);\n }\n\n assumptions(assumptions: string[]): this {\n this._context = { ...(this._context || {}), assumptions };\n return this;\n }\n\n knowledge(facts: string[]): this {\n this._context = { ...(this._context || {}), knowledge: facts };\n return this;\n }\n\n // --- Task Methods ---\n\n task(instruction: string | ChatTask): this {\n if (typeof instruction === 'string') {\n this._task = { ...(this._task || { instruction: '' }), instruction };\n } else {\n this._task = { ...(this._task || { instruction: '' }), ...instruction };\n }\n return this;\n }\n\n instruction(instruction: string): this {\n this._task = { ...(this._task || { instruction: '' }), instruction };\n return this;\n }\n\n steps(steps: string[]): this {\n this._task = { ...(this._task || { instruction: '' }), steps };\n return this;\n }\n\n deliverables(deliverables: string[]): this {\n this._task = { ...(this._task || { instruction: '' }), deliverables };\n return this;\n }\n\n criteria(criteria: string[]): this {\n this._task = { ...(this._task || { instruction: '' }), criteria };\n return this;\n }\n\n avoid(antiPatterns: string[]): this {\n this._task = { ...(this._task || { instruction: '' }), antiPatterns };\n return this;\n }\n\n priority(priority: ChatTask['priority']): this {\n this._task = { ...(this._task || { instruction: '' }), priority };\n return this;\n }\n\n // --- Example Methods ---\n\n example(input: string, output: string, explanation?: string): this {\n this._examples.push({ input, output, explanation });\n return this;\n }\n\n examples(examples: ChatExample[]): this {\n this._examples = [...this._examples, ...examples];\n return this;\n }\n\n fewShot(examples: Array<{ input: string; output: string }>): this {\n for (const ex of examples) {\n this._examples.push(ex);\n }\n return this;\n }\n\n // --- Output Methods ---\n\n output(settings: ChatOutput): this {\n this._output = { ...(this._output || {}), ...settings };\n return this;\n }\n\n outputFormat(format: ResponseFormatType): this {\n this._output = { \n ...(this._output || {}), \n format: { type: format } \n };\n return this;\n }\n\n json(schema?: JsonSchema): this {\n if (schema) {\n this._output = { \n ...(this._output || {}), \n format: { type: 'json', jsonSchema: schema } \n };\n } else {\n this._output = { \n ...(this._output || {}), \n format: { type: 'json' } \n };\n }\n return this;\n }\n\n jsonSchema(name: string, schema: Record<string, unknown>, description?: string): this {\n this._output = { \n ...(this._output || {}), \n format: { \n type: 'json', \n jsonSchema: { name, schema, description } \n } \n };\n return this;\n }\n\n markdown(): this {\n this._output = { ...(this._output || {}), format: { type: 'markdown' } };\n return this;\n }\n\n code(language?: string): this {\n this._output = { ...(this._output || {}), format: { type: 'code', language } };\n return this;\n }\n\n table(): this {\n this._output = { ...(this._output || {}), format: { type: 'table' } };\n return this;\n }\n\n length(length: OutputLength): this {\n this._output = { ...(this._output || {}), length };\n return this;\n }\n\n style(style: OutputStyle): this {\n this._output = { ...(this._output || {}), style };\n return this;\n }\n\n brief(): this {\n return this.length('brief');\n }\n\n moderate(): this {\n return this.length('moderate');\n }\n\n detailed(): this {\n return this.length('detailed');\n }\n\n comprehensive(): this {\n return this.length('comprehensive');\n }\n\n exhaustive(): this {\n return this.length('exhaustive');\n }\n\n withExamples(): this {\n this._output = { ...(this._output || {}), includeExamples: true };\n return this;\n }\n\n withExplanation(): this {\n this._output = { ...(this._output || {}), includeExplanation: true };\n return this;\n }\n\n withSources(): this {\n this._output = { ...(this._output || {}), includeSources: true };\n return this;\n }\n\n withConfidence(): this {\n this._output = { ...(this._output || {}), includeConfidence: true };\n return this;\n }\n\n // --- Reasoning Methods ---\n\n reasoning(settings: ChatReasoning): this {\n this._reasoning = { ...(this._reasoning || {}), ...settings };\n return this;\n }\n\n reasoningStyle(style: ReasoningStyle): this {\n this._reasoning = { ...(this._reasoning || {}), style };\n return this;\n }\n\n stepByStep(): this {\n this._reasoning = { ...(this._reasoning || {}), style: 'step-by-step', showWork: true };\n return this;\n }\n\n chainOfThought(): this {\n this._reasoning = { ...(this._reasoning || {}), style: 'chain-of-thought', showWork: true };\n return this;\n }\n\n treeOfThought(): this {\n this._reasoning = { ...(this._reasoning || {}), style: 'tree-of-thought', showWork: true };\n return this;\n }\n\n firstPrinciples(): this {\n this._reasoning = { ...(this._reasoning || {}), style: 'first-principles', showWork: true };\n return this;\n }\n\n devilsAdvocate(): this {\n this._reasoning = { ...(this._reasoning || {}), style: 'devil-advocate', considerAlternatives: true };\n return this;\n }\n\n showWork(show = true): this {\n this._reasoning = { ...(this._reasoning || {}), showWork: show };\n return this;\n }\n\n verifyAnswer(verify = true): this {\n this._reasoning = { ...(this._reasoning || {}), verifyAnswer: verify };\n return this;\n }\n\n considerAlternatives(consider = true): this {\n this._reasoning = { ...(this._reasoning || {}), considerAlternatives: consider };\n return this;\n }\n\n explainAssumptions(explain = true): this {\n this._reasoning = { ...(this._reasoning || {}), explainAssumptions: explain };\n return this;\n }\n\n // --- Memory Methods ---\n\n memory(memory: ChatMemory): this {\n this._memory = { ...(this._memory || {}), ...memory };\n return this;\n }\n\n remember(facts: string[]): this {\n const existing = this._memory?.facts || [];\n this._memory = { ...(this._memory || {}), facts: [...existing, ...facts] };\n return this;\n }\n\n preferences(prefs: string[]): this {\n this._memory = { ...(this._memory || {}), preferences: prefs };\n return this;\n }\n\n history(messages: ChatMessage[]): this {\n this._memory = { ...(this._memory || {}), history: messages };\n return this;\n }\n\n summarizeHistory(summary: string): this {\n this._memory = { ...(this._memory || {}), summary };\n return this;\n }\n\n // --- Custom System Prompt Parts ---\n\n addSystemPart(part: string): this {\n this._customSystemParts.push(part);\n return this;\n }\n\n raw(content: string): this {\n this._customSystemParts = [content];\n return this;\n }\n\n // --- Build Methods ---\n\n private buildSystemPrompt(): string {\n const parts: string[] = [];\n\n // Persona\n if (this._persona) {\n let personaText = '';\n if (this._persona.name) {\n personaText += `You are ${this._persona.name}`;\n if (this._persona.role) personaText += `, ${this._persona.role}`;\n personaText += '.';\n } else if (this._persona.role) {\n personaText += `You are ${this._persona.role}.`;\n }\n \n if (this._persona.tone) {\n const tones = Array.isArray(this._persona.tone) ? this._persona.tone : [this._persona.tone];\n personaText += ` Your tone is ${tones.join(' and ')}.`;\n }\n \n if (this._persona.expertise) {\n const areas = Array.isArray(this._persona.expertise) ? this._persona.expertise : [this._persona.expertise];\n personaText += ` You have expertise in ${areas.join(', ')}.`;\n }\n \n if (this._persona.personality?.length) {\n personaText += ` You are ${this._persona.personality.join(', ')}.`;\n }\n \n if (this._persona.background) {\n personaText += ` ${this._persona.background}`;\n }\n\n if (this._persona.verbosity) {\n personaText += ` Keep responses ${this._persona.verbosity}.`;\n }\n\n if (this._persona.language) {\n personaText += ` Respond in ${this._persona.language}.`;\n }\n\n if (personaText) parts.push(personaText.trim());\n }\n\n // Context\n if (this._context) {\n const contextParts: string[] = [];\n \n if (this._context.background) {\n contextParts.push(this._context.background);\n }\n if (this._context.domain) {\n contextParts.push(`Domain: ${this._context.domain}`);\n }\n if (this._context.audience) {\n contextParts.push(`Target audience: ${this._context.audience}`);\n }\n if (this._context.purpose) {\n contextParts.push(`Purpose: ${this._context.purpose}`);\n }\n if (this._context.knowledge?.length) {\n contextParts.push(`Known facts:\\n${this._context.knowledge.map(k => `- ${k}`).join('\\n')}`);\n }\n if (this._context.assumptions?.length) {\n contextParts.push(`Assumptions:\\n${this._context.assumptions.map(a => `- ${a}`).join('\\n')}`);\n }\n \n if (contextParts.length) {\n parts.push(`## Context\\n${contextParts.join('\\n')}`);\n }\n }\n\n // Task\n if (this._task) {\n const taskParts: string[] = [];\n \n if (this._task.instruction) {\n taskParts.push(this._task.instruction);\n }\n if (this._task.priority) {\n taskParts.push(`Priority: ${this._task.priority}`);\n }\n if (this._task.steps?.length) {\n taskParts.push(`\\nSteps:\\n${this._task.steps.map((s, i) => `${i + 1}. ${s}`).join('\\n')}`);\n }\n if (this._task.deliverables?.length) {\n taskParts.push(`\\nDeliverables:\\n${this._task.deliverables.map(d => `- ${d}`).join('\\n')}`);\n }\n if (this._task.criteria?.length) {\n taskParts.push(`\\nSuccess criteria:\\n${this._task.criteria.map(c => `- ${c}`).join('\\n')}`);\n }\n if (this._task.antiPatterns?.length) {\n taskParts.push(`\\nAvoid:\\n${this._task.antiPatterns.map(a => `- ${a}`).join('\\n')}`);\n }\n \n if (taskParts.length) {\n parts.push(`## Task\\n${taskParts.join('\\n')}`);\n }\n }\n\n // Constraints\n if (this._context?.constraints?.length) {\n parts.push(`## Constraints\\n${this._context.constraints.map((c, i) => `${i + 1}. ${c}`).join('\\n')}`);\n }\n\n // Examples\n if (this._examples.length) {\n const examplesText = this._examples\n .map((ex, i) => {\n let text = `### Example ${i + 1}\\n**Input:** ${ex.input}\\n**Output:** ${ex.output}`;\n if (ex.explanation) text += `\\n**Explanation:** ${ex.explanation}`;\n return text;\n })\n .join('\\n\\n');\n parts.push(`## Examples\\n${examplesText}`);\n }\n\n // Output format\n if (this._output) {\n const outputParts: string[] = [];\n \n if (this._output.format) {\n switch (this._output.format.type) {\n case 'json':\n if (this._output.format.jsonSchema) {\n outputParts.push(`Respond in valid JSON matching this schema:\\n\\`\\`\\`json\\n${JSON.stringify(this._output.format.jsonSchema.schema, null, 2)}\\n\\`\\`\\``);\n } else {\n outputParts.push('Respond in valid JSON format.');\n }\n break;\n case 'markdown':\n outputParts.push('Format your response using Markdown.');\n break;\n case 'code':\n outputParts.push(`Respond with code${this._output.format.language ? ` in ${this._output.format.language}` : ''}.`);\n break;\n case 'table':\n outputParts.push('Format your response as a table.');\n break;\n }\n }\n if (this._output.length) {\n outputParts.push(`Keep your response ${this._output.length}.`);\n }\n if (this._output.style) {\n const styleMap: Record<OutputStyle, string> = {\n 'prose': 'flowing prose',\n 'bullet-points': 'bullet points',\n 'numbered-list': 'a numbered list',\n 'table': 'a table',\n 'code': 'code',\n 'mixed': 'a mix of prose and lists',\n 'qa': 'Q&A format',\n 'dialogue': 'dialogue format',\n };\n outputParts.push(`Structure as ${styleMap[this._output.style]}.`);\n }\n if (this._output.language) {\n outputParts.push(`Respond in ${this._output.language}.`);\n }\n if (this._output.includeExamples) {\n outputParts.push('Include relevant examples.');\n }\n if (this._output.includeExplanation) {\n outputParts.push('Include clear explanations.');\n }\n if (this._output.includeSources) {\n outputParts.push('Cite your sources.');\n }\n if (this._output.includeConfidence) {\n outputParts.push('Include your confidence level in the answer.');\n }\n \n if (outputParts.length) {\n parts.push(`## Output Format\\n${outputParts.join('\\n')}`);\n }\n }\n\n // Reasoning\n if (this._reasoning) {\n const reasoningParts: string[] = [];\n \n if (this._reasoning.style) {\n const styleInstructions: Record<ReasoningStyle, string> = {\n 'step-by-step': 'Think through this step by step.',\n 'chain-of-thought': 'Use chain-of-thought reasoning to work through the problem.',\n 'tree-of-thought': 'Consider multiple approaches and evaluate each before deciding.',\n 'direct': 'Provide a direct answer.',\n 'analytical': 'Analyze the problem systematically.',\n 'comparative': 'Compare different options or approaches.',\n 'deductive': 'Use deductive reasoning from general principles.',\n 'inductive': 'Use inductive reasoning from specific examples.',\n 'first-principles': 'Reason from first principles, breaking down to fundamental truths.',\n 'analogical': 'Use analogies to explain and reason about the problem.',\n 'devil-advocate': 'Consider and argue against your own conclusions.',\n };\n reasoningParts.push(styleInstructions[this._reasoning.style]);\n }\n if (this._reasoning.showWork) {\n reasoningParts.push('Show your reasoning process.');\n }\n if (this._reasoning.verifyAnswer) {\n reasoningParts.push('Verify your answer before presenting it.');\n }\n if (this._reasoning.considerAlternatives) {\n reasoningParts.push('Consider alternative perspectives and solutions.');\n }\n if (this._reasoning.explainAssumptions) {\n reasoningParts.push('Explicitly state any assumptions you make.');\n }\n \n if (reasoningParts.length) {\n parts.push(`## Reasoning\\n${reasoningParts.join('\\n')}`);\n }\n }\n\n // Memory\n if (this._memory) {\n const memoryParts: string[] = [];\n \n if (this._memory.summary) {\n memoryParts.push(`Previous conversation summary: ${this._memory.summary}`);\n }\n if (this._memory.facts?.length) {\n memoryParts.push(`Known facts:\\n${this._memory.facts.map(f => `- ${f}`).join('\\n')}`);\n }\n if (this._memory.preferences?.length) {\n memoryParts.push(`User preferences:\\n${this._memory.preferences.map(p => `- ${p}`).join('\\n')}`);\n }\n \n if (memoryParts.length) {\n parts.push(`## Memory\\n${memoryParts.join('\\n')}`);\n }\n }\n\n // Custom parts\n if (this._customSystemParts.length) {\n parts.push(...this._customSystemParts);\n }\n\n return parts.join('\\n\\n');\n }\n\n build(): BuiltChatPrompt {\n const systemPrompt = this.buildSystemPrompt();\n \n // Ensure system message is first\n let messages = [...this._messages];\n const hasSystemMessage = messages.some(m => m.role === 'system');\n \n if (systemPrompt && !hasSystemMessage) {\n messages = [{ role: 'system', content: systemPrompt }, ...messages];\n } else if (systemPrompt && hasSystemMessage) {\n // Prepend built system prompt to existing system message\n messages = messages.map(m => \n m.role === 'system' ? { ...m, content: `${systemPrompt}\\n\\n${m.content}` } : m\n );\n }\n\n // Add memory history if present\n if (this._memory?.history) {\n const systemIdx = messages.findIndex(m => m.role === 'system');\n const insertIdx = systemIdx >= 0 ? systemIdx + 1 : 0;\n messages.splice(insertIdx, 0, ...this._memory.history);\n }\n\n // Get user prompt if exists\n const userMessages = messages.filter(m => m.role === 'user');\n const userPrompt = userMessages.length ? userMessages[userMessages.length - 1].content : undefined;\n\n return {\n messages,\n systemPrompt,\n userPrompt,\n metadata: {\n persona: this._persona,\n context: this._context,\n task: this._task,\n output: this._output,\n reasoning: this._reasoning,\n examples: this._examples.length ? this._examples : undefined,\n },\n };\n }\n\n // --- Output Methods ---\n\n toString(): string {\n return this.buildSystemPrompt();\n }\n\n toSystemPrompt(): string {\n return this.buildSystemPrompt();\n }\n\n toMessages(): ChatMessage[] {\n return this.build().messages;\n }\n\n toJSON(): string {\n return JSON.stringify(this.build(), null, 2);\n }\n\n toYAML(): string {\n return objectToYaml(this.build());\n }\n\n toMarkdown(): string {\n const built = this.build();\n const sections: string[] = ['# Chat Prompt\\n'];\n \n sections.push('## System Prompt\\n```\\n' + built.systemPrompt + '\\n```\\n');\n \n if (built.messages.length > 1) {\n sections.push('## Messages\\n');\n for (const msg of built.messages) {\n if (msg.role === 'system') continue;\n sections.push(`**${msg.role.toUpperCase()}${msg.name ? ` (${msg.name})` : ''}:**\\n${msg.content}\\n`);\n }\n }\n \n return sections.join('\\n');\n }\n}\n\n// ============================================================================\n// HELPER FUNCTIONS\n// ============================================================================\n\nfunction objectToYaml(obj: object, indent = 0): string {\n const spaces = ' '.repeat(indent);\n const lines: string[] = [];\n \n for (const [key, value] of Object.entries(obj)) {\n if (value === undefined || value === null) continue;\n \n if (Array.isArray(value)) {\n if (value.length === 0) continue;\n lines.push(`${spaces}${key}:`);\n for (const item of value) {\n if (typeof item === 'object') {\n lines.push(`${spaces} -`);\n lines.push(objectToYaml(item, indent + 2).replace(/^/gm, ' '));\n } else {\n lines.push(`${spaces} - ${item}`);\n }\n }\n } else if (typeof value === 'object') {\n lines.push(`${spaces}${key}:`);\n lines.push(objectToYaml(value, indent + 1));\n } else if (typeof value === 'string' && value.includes('\\n')) {\n lines.push(`${spaces}${key}: |`);\n for (const line of value.split('\\n')) {\n lines.push(`${spaces} ${line}`);\n }\n } else {\n lines.push(`${spaces}${key}: ${value}`);\n }\n }\n \n return lines.join('\\n');\n}\n\n// ============================================================================\n// FACTORY FUNCTION\n// ============================================================================\n\n/**\n * Create a new chat prompt builder\n */\nexport function chat(): ChatPromptBuilder {\n return new ChatPromptBuilder();\n}\n\n// ============================================================================\n// PRESET BUILDERS\n// ============================================================================\n\nexport const chatPresets = {\n /**\n * Code assistant preset\n */\n coder: (language?: string) => {\n const c = chat()\n .role(\"expert software developer\")\n .expertise(\"coding\")\n .tone(\"technical\");\n \n if (language) {\n c.context(`Programming language: ${language}`);\n }\n \n return c;\n },\n\n /**\n * Writing assistant preset\n */\n writer: (style?: 'creative' | 'professional' | 'academic') => {\n const c = chat()\n .role(\"skilled writer and editor\")\n .expertise(\"writing\");\n \n if (style) {\n c.tone(style === 'creative' ? 'creative' : style === 'academic' ? 'academic' : 'professional');\n }\n \n return c;\n },\n\n /**\n * Teacher/tutor preset\n */\n tutor: (subject?: string) => {\n const c = chat()\n .role(\"patient and knowledgeable tutor\")\n .expertise(\"teaching\")\n .tone(['friendly', 'empathetic'])\n .stepByStep()\n .withExamples();\n \n if (subject) {\n c.domain(subject);\n }\n \n return c;\n },\n\n /**\n * Analyst preset\n */\n analyst: () => {\n return chat()\n .role(\"data analyst and researcher\")\n .expertise(\"analysis\")\n .tone(\"analytical\")\n .chainOfThought()\n .detailed()\n .withSources();\n },\n\n /**\n * Socratic dialogue preset\n */\n socratic: () => {\n return chat()\n .role(\"Socratic philosopher and teacher\")\n .tone(\"socratic\")\n .reasoning({ style: 'deductive', showWork: true })\n .avoid([\"Give direct answers\", \"Lecture\", \"Be condescending\"]);\n },\n\n /**\n * Critic preset\n */\n critic: () => {\n return chat()\n .role(\"constructive critic\")\n .tone(['analytical', 'professional'])\n .devilsAdvocate()\n .detailed()\n .avoid([\"Be harsh\", \"Dismiss ideas without explanation\"]);\n },\n\n /**\n * Brainstormer preset\n */\n brainstormer: () => {\n return chat()\n .role(\"creative brainstorming partner\")\n .tone(['creative', 'encouraging'])\n .expertise(\"creative\")\n .considerAlternatives()\n .avoid([\"Dismiss ideas\", \"Be negative\", \"Limit creativity\"]);\n },\n\n /**\n * JSON response preset\n */\n jsonResponder: (schemaName: string, schema: Record<string, unknown>) => {\n return chat()\n .role(\"data processing assistant\")\n .tone(\"concise\")\n .jsonSchema(schemaName, schema)\n .avoid([\"Include markdown\", \"Add explanations outside JSON\", \"Include code fences\"]);\n },\n\n /**\n * Summarizer preset\n */\n summarizer: (length: OutputLength = 'brief') => {\n return chat()\n .role(\"expert summarizer\")\n .expertise(\"analysis\")\n .tone(\"concise\")\n .length(length)\n .task(\"Summarize the provided content, preserving key information\");\n },\n\n /**\n * Translator preset\n */\n translator: (targetLanguage: string) => {\n return chat()\n .role(\"professional translator\")\n .expertise(\"languages\")\n .responseLanguage(targetLanguage)\n .avoid([\"Add commentary\", \"Change meaning\", \"Omit content\"]);\n },\n};\n","/**\n * Prompt Builder - A fluent DSL for creating structured prompts\n * \n * @example\n * ```ts\n * import { builder } from 'prompts.chat';\n * \n * const prompt = builder()\n * .role(\"Senior TypeScript Developer\")\n * .context(\"You are helping review code\")\n * .task(\"Analyze the following code for bugs\")\n * .constraints([\"Be concise\", \"Focus on critical issues\"])\n * .output(\"JSON with { bugs: [], suggestions: [] }\")\n * .variable(\"code\", { required: true })\n * .build();\n * ```\n */\n\nexport interface PromptVariable {\n name: string;\n description?: string;\n required?: boolean;\n defaultValue?: string;\n}\n\nexport interface BuiltPrompt {\n content: string;\n variables: PromptVariable[];\n metadata: {\n role?: string;\n context?: string;\n task?: string;\n constraints?: string[];\n outputFormat?: string;\n examples?: Array<{ input: string; output: string }>;\n };\n}\n\nexport class PromptBuilder {\n private _role?: string;\n private _context?: string;\n private _task?: string;\n private _constraints: string[] = [];\n private _outputFormat?: string;\n private _examples: Array<{ input: string; output: string }> = [];\n private _variables: PromptVariable[] = [];\n private _customSections: Array<{ title: string; content: string }> = [];\n private _rawContent?: string;\n\n /**\n * Set the role/persona for the AI\n */\n role(role: string): this {\n this._role = role;\n return this;\n }\n\n /**\n * Alias for role()\n */\n persona(persona: string): this {\n return this.role(persona);\n }\n\n /**\n * Set the context/background information\n */\n context(context: string): this {\n this._context = context;\n return this;\n }\n\n /**\n * Alias for context()\n */\n background(background: string): this {\n return this.context(background);\n }\n\n /**\n * Set the main task/instruction\n */\n task(task: string): this {\n this._task = task;\n return this;\n }\n\n /**\n * Alias for task()\n */\n instruction(instruction: string): this {\n return this.task(instruction);\n }\n\n /**\n * Add constraints/rules the AI should follow\n */\n constraints(constraints: string[]): this {\n this._constraints = [...this._constraints, ...constraints];\n return this;\n }\n\n /**\n * Add a single constraint\n */\n constraint(constraint: string): this {\n this._constraints.push(constraint);\n return this;\n }\n\n /**\n * Alias for constraints()\n */\n rules(rules: string[]): this {\n return this.constraints(rules);\n }\n\n /**\n * Set the expected output format\n */\n output(format: string): this {\n this._outputFormat = format;\n return this;\n }\n\n /**\n * Alias for output()\n */\n format(format: string): this {\n return this.output(format);\n }\n\n /**\n * Add an example input/output pair\n */\n example(input: string, output: string): this {\n this._examples.push({ input, output });\n return this;\n }\n\n /**\n * Add multiple examples\n */\n examples(examples: Array<{ input: string; output: string }>): this {\n this._examples = [...this._examples, ...examples];\n return this;\n }\n\n /**\n * Define a variable placeholder\n */\n variable(\n name: string, \n options: { description?: string; required?: boolean; defaultValue?: string } = {}\n ): this {\n this._variables.push({\n name,\n description: options.description,\n required: options.required ?? true,\n defaultValue: options.defaultValue,\n });\n return this;\n }\n\n /**\n * Add a custom section\n */\n section(title: string, content: string): this {\n this._customSections.push({ title, content });\n return this;\n }\n\n /**\n * Set raw content (bypasses structured building)\n */\n raw(content: string): this {\n this._rawContent = content;\n return this;\n }\n\n /**\n * Build the final prompt\n */\n build(): BuiltPrompt {\n if (this._rawContent) {\n return {\n content: this._rawContent,\n variables: this._variables,\n metadata: {},\n };\n }\n\n const sections: string[] = [];\n\n // Role section\n if (this._role) {\n sections.push(`You are ${this._role}.`);\n }\n\n // Context section\n if (this._context) {\n sections.push(`\\n## Context\\n${this._context}`);\n }\n\n // Task section\n if (this._task) {\n sections.push(`\\n## Task\\n${this._task}`);\n }\n\n // Constraints section\n if (this._constraints.length > 0) {\n const constraintsList = this._constraints\n .map((c, i) => `${i + 1}. ${c}`)\n .join('\\n');\n sections.push(`\\n## Constraints\\n${constraintsList}`);\n }\n\n // Output format section\n if (this._outputFormat) {\n sections.push(`\\n## Output Format\\n${this._outputFormat}`);\n }\n\n // Examples section\n if (this._examples.length > 0) {\n const examplesText = this._examples\n .map((e, i) => `### Example ${i + 1}\\n**Input:** ${e.input}\\n**Output:** ${e.output}`)\n .join('\\n\\n');\n sections.push(`\\n## Examples\\n${examplesText}`);\n }\n\n // Custom sections\n for (const section of this._customSections) {\n sections.push(`\\n## ${section.title}\\n${section.content}`);\n }\n\n // Variables section (as placeholders info)\n if (this._variables.length > 0) {\n const varsText = this._variables\n .map(v => {\n const placeholder = v.defaultValue \n ? `\\${${v.name}:${v.defaultValue}}`\n : `\\${${v.name}}`;\n const desc = v.description ? ` - ${v.description}` : '';\n const req = v.required ? ' (required)' : ' (optional)';\n return `- ${placeholder}${desc}${req}`;\n })\n .join('\\n');\n sections.push(`\\n## Variables\\n${varsText}`);\n }\n\n return {\n content: sections.join('\\n').trim(),\n variables: this._variables,\n metadata: {\n role: this._role,\n context: this._context,\n task: this._task,\n constraints: this._constraints.length > 0 ? this._constraints : undefined,\n outputFormat: this._outputFormat,\n examples: this._examples.length > 0 ? this._examples : undefined,\n },\n };\n }\n\n /**\n * Build and return only the content string\n */\n toString(): string {\n return this.build().content;\n }\n}\n\n/**\n * Create a new prompt builder\n */\nexport function builder(): PromptBuilder {\n return new PromptBuilder();\n}\n\n/**\n * Create a prompt builder from an existing prompt\n */\nexport function fromPrompt(content: string): PromptBuilder {\n return new PromptBuilder().raw(content);\n}\n\n// Re-export media builders\nexport { image, ImagePromptBuilder } from './media';\nexport type { \n BuiltImagePrompt, \n ImageSubject, \n ImageCamera, \n ImageLighting, \n ImageComposition,\n ImageStyle,\n ImageColor,\n ImageEnvironment,\n ImageTechnical,\n CameraAngle,\n ShotType,\n LensType,\n LightingType,\n TimeOfDay,\n ArtStyle,\n ColorPalette,\n Mood,\n AspectRatio,\n OutputFormat,\n} from './media';\n\nexport { video, VideoPromptBuilder } from './video';\nexport type { \n BuiltVideoPrompt,\n VideoScene,\n VideoSubject,\n VideoCamera,\n VideoLighting,\n VideoAction,\n VideoMotion,\n VideoStyle,\n VideoColor,\n VideoAudio,\n VideoTechnical,\n VideoShot,\n} from './video';\n\nexport { audio, AudioPromptBuilder } from './audio';\nexport type {\n BuiltAudioPrompt,\n AudioGenre,\n AudioMood,\n AudioTempo,\n AudioVocals,\n AudioInstrumentation,\n AudioStructure,\n AudioProduction,\n AudioTechnical,\n MusicGenre,\n Instrument,\n VocalStyle,\n TempoMarking,\n TimeSignature,\n MusicalKey,\n SongSection,\n ProductionStyle,\n} from './audio';\n\n// Re-export chat builder\nexport { chat, ChatPromptBuilder, chatPresets } from './chat';\nexport type {\n BuiltChatPrompt,\n ChatMessage,\n ChatPersona,\n ChatContext,\n ChatTask,\n ChatOutput,\n ChatReasoning,\n ChatMemory,\n ChatExample,\n MessageRole,\n ResponseFormat,\n ResponseFormatType,\n JsonSchema,\n PersonaTone,\n PersonaExpertise,\n ReasoningStyle,\n OutputLength,\n OutputStyle,\n} from './chat';\n\n// Pre-built templates\nexport const templates = {\n /**\n * Create a code review prompt\n */\n codeReview: (options: { language?: string; focus?: string[] } = {}) => {\n const b = builder()\n .role(\"expert code reviewer\")\n .task(\"Review the provided code and identify issues, improvements, and best practices.\")\n .variable(\"code\", { required: true, description: \"The code to review\" });\n\n if (options.language) {\n b.context(`You are reviewing ${options.language} code.`);\n }\n\n if (options.focus && options.focus.length > 0) {\n b.constraints(options.focus.map(f => `Focus on ${f}`));\n }\n\n return b.output(\"Provide a structured review with: issues found, suggestions, and overall assessment.\");\n },\n\n /**\n * Create a translation prompt\n */\n translation: (from: string, to: string) => {\n return builder()\n .role(`professional translator fluent in ${from} and ${to}`)\n .task(`Translate the following text from ${from} to ${to}.`)\n .constraints([\n \"Maintain the original meaning and tone\",\n \"Use natural, idiomatic expressions in the target language\",\n \"Preserve formatting and structure\",\n ])\n .variable(\"text\", { required: true, description: \"Text to translate\" });\n },\n\n /**\n * Create a summarization prompt\n */\n summarize: (options: { maxLength?: number; style?: 'bullet' | 'paragraph' } = {}) => {\n const b = builder()\n .role(\"expert summarizer\")\n .task(\"Summarize the following content concisely while preserving key information.\")\n .variable(\"content\", { required: true, description: \"Content to summarize\" });\n\n if (options.maxLength) {\n b.constraint(`Keep the summary under ${options.maxLength} words`);\n }\n\n if (options.style === 'bullet') {\n b.output(\"Provide the summary as bullet points\");\n }\n\n return b;\n },\n\n /**\n * Create a Q&A prompt\n */\n qa: (context?: string) => {\n const b = builder()\n .role(\"helpful assistant\")\n .task(\"Answer the question based on the provided context.\")\n .variable(\"question\", { required: true, description: \"The question to answer\" });\n\n if (context) {\n b.context(context);\n } else {\n b.variable(\"context\", { required: false, description: \"Additional context\" });\n }\n\n return b.constraints([\n \"Be accurate and concise\",\n \"If you don't know the answer, say so\",\n \"Cite relevant parts of the context if applicable\",\n ]);\n },\n\n /**\n * Create a debugging prompt\n */\n debug: (options: { language?: string; errorType?: string } = {}) => {\n const b = builder()\n .role(\"expert software debugger\")\n .task(\"Analyze the code and error, identify the root cause, and provide a fix.\")\n .variable(\"code\", { required: true, description: \"The code with the bug\" })\n .variable(\"error\", { required: false, description: \"Error message or unexpected behavior\" });\n\n if (options.language) {\n b.context(`Debugging ${options.language} code.`);\n }\n\n if (options.errorType) {\n b.context(`The error appears to be related to: ${options.errorType}`);\n }\n\n return b\n .constraints([\n \"Identify the root cause, not just symptoms\",\n \"Explain why the bug occurs\",\n \"Provide a working fix with explanation\",\n ])\n .output(\"1. Root cause analysis\\n2. Explanation\\n3. Fixed code\\n4. Prevention tips\");\n },\n\n /**\n * Create a writing assistant prompt\n */\n write: (options: { type?: 'blog' | 'email' | 'essay' | 'story' | 'documentation'; tone?: string } = {}) => {\n const typeDescriptions: Record<string, string> = {\n blog: \"engaging blog post\",\n email: \"professional email\",\n essay: \"well-structured essay\",\n story: \"creative story\",\n documentation: \"clear technical documentation\",\n };\n\n const b = builder()\n .role(\"skilled writer\")\n .task(`Write a ${typeDescriptions[options.type || 'blog'] || 'piece of content'} based on the given topic or outline.`)\n .variable(\"topic\", { required: true, description: \"Topic or outline to write about\" });\n\n if (options.tone) {\n b.constraint(`Use a ${options.tone} tone throughout`);\n }\n\n return b.constraints([\n \"Use clear and engaging language\",\n \"Structure content logically\",\n \"Maintain consistent voice and style\",\n ]);\n },\n\n /**\n * Create an explanation/teaching prompt\n */\n explain: (options: { level?: 'beginner' | 'intermediate' | 'expert'; useAnalogies?: boolean } = {}) => {\n const levelDescriptions: Record<string, string> = {\n beginner: \"someone new to the topic with no prior knowledge\",\n intermediate: \"someone with basic understanding who wants to go deeper\",\n expert: \"an expert who wants technical precision and nuance\",\n };\n\n const b = builder()\n .role(\"expert teacher and communicator\")\n .task(\"Explain the concept clearly and thoroughly.\")\n .variable(\"concept\", { required: true, description: \"The concept to explain\" });\n\n if (options.level) {\n b.context(`Target audience: ${levelDescriptions[options.level]}`);\n }\n\n if (options.useAnalogies) {\n b.constraint(\"Use relatable analogies and real-world examples\");\n }\n\n return b.constraints([\n \"Break down complex ideas into digestible parts\",\n \"Build understanding progressively\",\n \"Anticipate and address common misconceptions\",\n ]);\n },\n\n /**\n * Create a data extraction prompt\n */\n extract: (options: { format?: 'json' | 'csv' | 'table'; fields?: string[] } = {}) => {\n const b = builder()\n .role(\"data extraction specialist\")\n .task(\"Extract structured data from the provided text.\")\n .variable(\"text\", { required: true, description: \"Text to extract data from\" });\n\n if (options.fields && options.fields.length > 0) {\n b.context(`Fields to extract: ${options.fields.join(\", \")}`);\n }\n\n if (options.format) {\n b.output(`Return extracted data in ${options.format.toUpperCase()} format`);\n }\n\n return b.constraints([\n \"Extract only factual information present in the text\",\n \"Use null or empty values for missing fields\",\n \"Maintain consistent formatting\",\n ]);\n },\n\n /**\n * Create a brainstorming prompt\n */\n brainstorm: (options: { count?: number; creative?: boolean } = {}) => {\n const b = builder()\n .role(\"creative strategist and ideation expert\")\n .task(\"Generate diverse and innovative ideas based on the given topic or challenge.\")\n .variable(\"topic\", { required: true, description: \"Topic or challenge to brainstorm about\" });\n\n if (options.count) {\n b.constraint(`Generate exactly ${options.count} ideas`);\n }\n\n if (options.creative) {\n b.constraint(\"Include unconventional and out-of-the-box ideas\");\n }\n\n return b\n .constraints([\n \"Ensure ideas are distinct and varied\",\n \"Consider different perspectives and approaches\",\n \"Make ideas actionable when possible\",\n ])\n .output(\"List each idea with a brief description and potential benefits\");\n },\n\n /**\n * Create a code refactoring prompt\n */\n refactor: (options: { goal?: 'readability' | 'performance' | 'maintainability' | 'all'; language?: string } = {}) => {\n const goalDescriptions: Record<string, string> = {\n readability: \"improving code readability and clarity\",\n performance: \"optimizing performance and efficiency\",\n maintainability: \"enhancing maintainability and extensibility\",\n all: \"overall code quality improvement\",\n };\n\n const b = builder()\n .role(\"senior software engineer specializing in code quality\")\n .task(`Refactor the code with focus on ${goalDescriptions[options.goal || 'all']}.`)\n .variable(\"code\", { required: true, description: \"Code to refactor\" });\n\n if (options.language) {\n b.context(`The code is written in ${options.language}.`);\n }\n\n return b\n .constraints([\n \"Preserve existing functionality\",\n \"Follow language best practices and idioms\",\n \"Explain each significant change\",\n ])\n .output(\"1. Refactored code\\n2. List of changes made\\n3. Explanation of improvements\");\n },\n\n /**\n * Create an API documentation prompt\n */\n apiDocs: (options: { style?: 'openapi' | 'markdown' | 'jsdoc'; includeExamples?: boolean } = {}) => {\n const b = builder()\n .role(\"technical documentation writer\")\n .task(\"Generate comprehensive API documentation for the provided code or endpoint.\")\n .variable(\"code\", { required: true, description: \"API code or endpoint definition\" });\n\n if (options.style) {\n b.output(`Format documentation in ${options.style.toUpperCase()} style`);\n }\n\n if (options.includeExamples) {\n b.constraint(\"Include request/response examples for each endpoint\");\n }\n\n return b.constraints([\n \"Document all parameters with types and descriptions\",\n \"Include error responses and status codes\",\n \"Be precise and developer-friendly\",\n ]);\n },\n\n /**\n * Create a unit test generation prompt\n */\n unitTest: (options: { framework?: string; coverage?: 'basic' | 'comprehensive' } = {}) => {\n const b = builder()\n .role(\"test automation engineer\")\n .task(\"Generate unit tests for the provided code.\")\n .variable(\"code\", { required: true, description: \"Code to generate tests for\" });\n\n if (options.framework) {\n b.context(`Use ${options.framework} testing framework.`);\n }\n\n const coverageConstraints = options.coverage === 'comprehensive'\n ? [\"Cover all code paths including edge cases\", \"Test error handling scenarios\", \"Include boundary value tests\"]\n : [\"Cover main functionality\", \"Include basic edge cases\"];\n\n return b\n .constraints([\n ...coverageConstraints,\n \"Write clear, descriptive test names\",\n \"Follow AAA pattern (Arrange, Act, Assert)\",\n ])\n .output(\"Complete, runnable test file\");\n },\n\n /**\n * Create a commit message prompt\n */\n commitMessage: (options: { style?: 'conventional' | 'simple'; includeBody?: boolean } = {}) => {\n const b = builder()\n .role(\"developer with excellent communication skills\")\n .task(\"Generate a clear and descriptive commit message for the provided code changes.\")\n .variable(\"diff\", { required: true, description: \"Git diff or description of changes\" });\n\n if (options.style === 'conventional') {\n b.constraints([\n \"Follow Conventional Commits format (type(scope): description)\",\n \"Use appropriate type: feat, fix, docs, style, refactor, test, chore\",\n ]);\n }\n\n if (options.includeBody) {\n b.constraint(\"Include a detailed body explaining the why behind changes\");\n }\n\n return b.constraints([\n \"Keep subject line under 72 characters\",\n \"Use imperative mood (Add, Fix, Update, not Added, Fixed, Updated)\",\n ]);\n },\n\n /**\n * Create a code review comment prompt\n */\n reviewComment: (options: { tone?: 'constructive' | 'direct'; severity?: boolean } = {}) => {\n const b = builder()\n .role(\"thoughtful code reviewer\")\n .task(\"Write a helpful code review comment for the provided code snippet.\")\n .variable(\"code\", { required: true, description: \"Code to comment on\" })\n .variable(\"issue\", { required: true, description: \"The issue or improvement to address\" });\n\n if (options.tone === 'constructive') {\n b.constraint(\"Frame feedback positively and suggest improvements rather than just pointing out problems\");\n }\n\n if (options.severity) {\n b.constraint(\"Indicate severity level: nitpick, suggestion, important, or blocker\");\n }\n\n return b.constraints([\n \"Be specific and actionable\",\n \"Explain the reasoning behind the suggestion\",\n \"Provide an example of the improved code when helpful\",\n ]);\n },\n\n /**\n * Create a regex generator prompt\n */\n regex: (options: { flavor?: 'javascript' | 'python' | 'pcre' } = {}) => {\n const b = builder()\n .role(\"regex expert\")\n .task(\"Create a regular expression that matches the described pattern.\")\n .variable(\"pattern\", { required: true, description: \"Description of the pattern to match\" })\n .variable(\"examples\", { required: false, description: \"Example strings that should match\" });\n\n if (options.flavor) {\n b.context(`Use ${options.flavor} regex flavor/syntax.`);\n }\n\n return b\n .constraints([\n \"Provide the regex pattern\",\n \"Explain each part of the pattern\",\n \"Include test cases showing matches and non-matches\",\n ])\n .output(\"1. Regex pattern\\n2. Explanation\\n3. Test cases\");\n },\n\n /**\n * Create a SQL query prompt\n */\n sql: (options: { dialect?: 'postgresql' | 'mysql' | 'sqlite' | 'mssql'; optimize?: boolean } = {}) => {\n const b = builder()\n .role(\"database expert\")\n .task(\"Write an SQL query based on the requirements.\")\n .variable(\"requirement\", { required: true, description: \"What the query should accomplish\" })\n .variable(\"schema\", { required: false, description: \"Database schema or table definitions\" });\n\n if (options.dialect) {\n b.context(`Use ${options.dialect.toUpperCase()} syntax.`);\n }\n\n if (options.optimize) {\n b.constraint(\"Optimize for performance and include index recommendations if applicable\");\n }\n\n return b.constraints([\n \"Write clean, readable SQL\",\n \"Use appropriate JOINs and avoid N+1 patterns\",\n \"Include comments explaining complex logic\",\n ]);\n },\n};\n"],"mappings":";;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAgCA,IAAM,WAA4B;AAAA;AAAA,EAEhC;AAAA,IACE,SAAS;AAAA,IACT,OAAO;AAAA,IACP,aAAa,CAAC,MAAM,EAAE,CAAC,EAAE,KAAK;AAAA,IAC9B,gBAAgB,CAAC,MAAM,EAAE,CAAC,GAAG,KAAK;AAAA,EACpC;AAAA;AAAA,EAEA;AAAA,IACE,SAAS;AAAA,IACT,OAAO;AAAA,IACP,aAAa,CAAC,MAAM,EAAE,CAAC,EAAE,KAAK;AAAA,IAC9B,gBAAgB,CAAC,MAAM,EAAE,CAAC,GAAG,KAAK;AAAA,EACpC;AAAA;AAAA,EAEA;AAAA,IACE,SAAS;AAAA,IACT,OAAO;AAAA,IACP,aAAa,CAAC,MAAM,EAAE,CAAC,EAAE,KAAK;AAAA,EAChC;AAAA;AAAA,EAEA;AAAA,IACE,SAAS;AAAA,IACT,OAAO;AAAA,IACP,aAAa,CAAC,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