From e371c07ec5f55d288ca60d4466c678484603dab4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fatih=20Kadir=20Ak=C4=B1n?= Date: Fri, 26 Dec 2025 23:13:13 +0300 Subject: [PATCH] chore(messages): update IDE labels to "Prompt Builder" across multiple languages --- messages/ar.json | 6 +- messages/de.json | 6 +- messages/el.json | 6 +- messages/en.json | 6 +- messages/es.json | 6 +- messages/fr.json | 6 +- messages/he.json | 6 +- messages/it.json | 6 +- messages/ja.json | 6 +- messages/ko.json | 6 +- messages/pt.json | 6 +- messages/ru.json | 6 +- messages/tr.json | 6 +- messages/zh.json | 6 +- next.config.ts | 8 + package.json | 1 + packages/prompts.chat/API.md | 5240 +++++++++++++++++ packages/prompts.chat/README.md | 2 +- packages/prompts.chat/package.json | 4 +- .../prompts.chat/scripts/generate-docs.ts | 1138 ++++ scripts/generate-examples.ts | 34 + .../page.tsx | 0 src/components/ide/api-details-popup.tsx | 103 + src/components/ide/api-docs-sidebar.tsx | 138 + src/components/ide/examples/audio.ts | 64 + src/components/ide/examples/chat.ts | 24 + src/components/ide/examples/default.ts | 21 + src/components/ide/examples/generated.ts | 273 + src/components/ide/examples/image.ts | 80 + src/components/ide/examples/index.ts | 8 + src/components/ide/examples/video.ts | 72 + src/components/ide/prompt-ide.tsx | 1473 +---- src/components/ide/types.ts | 0 src/components/ide/utils.ts | 43 + src/components/layout/header.tsx | 2 +- src/data/api-docs.ts | 3129 ++++++++++ src/data/method-options.ts | 72 + src/data/type-definitions.ts | 928 +++ 38 files changed, 11520 insertions(+), 1421 deletions(-) create mode 100644 packages/prompts.chat/API.md create mode 100644 packages/prompts.chat/scripts/generate-docs.ts create mode 100644 scripts/generate-examples.ts rename src/app/{typed-prompts-editor => builder}/page.tsx (100%) create mode 100644 src/components/ide/api-details-popup.tsx create mode 100644 src/components/ide/api-docs-sidebar.tsx create mode 100644 src/components/ide/examples/audio.ts create mode 100644 src/components/ide/examples/chat.ts create mode 100644 src/components/ide/examples/default.ts create mode 100644 src/components/ide/examples/generated.ts create mode 100644 src/components/ide/examples/image.ts create mode 100644 src/components/ide/examples/index.ts create mode 100644 src/components/ide/examples/video.ts create mode 100644 src/components/ide/types.ts create mode 100644 src/components/ide/utils.ts create mode 100644 src/data/api-docs.ts create mode 100644 src/data/method-options.ts create mode 100644 src/data/type-definitions.ts diff --git a/messages/ar.json b/messages/ar.json index 0b06330a..68854042 100644 --- a/messages/ar.json +++ b/messages/ar.json @@ -45,7 +45,7 @@ "login": "تسجيل الدخول", "register": "إنشاء حساب", "logout": "تسجيل الخروج", - "ide": "الأوامر المكتوبة" + "ide": "Prompt Builder" }, "brand": { "copyLogoSvg": "نسخ شعار SVG", @@ -1164,7 +1164,7 @@ } }, "ide": { - "title": "الأوامر المكتوبة", + "title": "Prompt Builder", "subtitle": "بناء أوامر منظمة وآمنة النوع", "editor": "المحرر", "preview": "معاينة", @@ -1173,7 +1173,7 @@ "copied": "تم النسخ إلى الحافظة", "runToPreview": "انقر على تشغيل لمشاهدة معاينة الأمر", "desktopOnly": "للحاسوب فقط", - "desktopOnlyDescription": "يتطلب محرر الأوامر المكتوبة شاشة أكبر ليعمل بشكل صحيح. يرجى فتح هذه الصفحة على جهاز كمبيوتر مكتبي أو محمول.", + "desktopOnlyDescription": "يتطلب منشئ الأوامر شاشة أكبر ليعمل بشكل صحيح. يرجى فتح هذه الصفحة على جهاز كمبيوتر مكتبي أو محمول.", "browsePrompts": "تصفح الأوامر" } } diff --git a/messages/de.json b/messages/de.json index 63225c66..bc28c1d8 100644 --- a/messages/de.json +++ b/messages/de.json @@ -45,7 +45,7 @@ "login": "Anmelden", "register": "Registrieren", "logout": "Abmelden", - "ide": "Typisierte Prompts" + "ide": "Prompt Builder" }, "brand": { "copyLogoSvg": "Logo SVG kopieren", @@ -1164,7 +1164,7 @@ } }, "ide": { - "title": "Typisierte Prompts", + "title": "Prompt Builder", "subtitle": "Typsichere, strukturierte Prompt-Erstellung", "editor": "Editor", "preview": "Vorschau", @@ -1173,7 +1173,7 @@ "copied": "In die Zwischenablage kopiert", "runToPreview": "Klicken Sie auf Ausführen, um die Prompt-Vorschau anzuzeigen", "desktopOnly": "Nur für Desktop", - "desktopOnlyDescription": "Der Editor für Typisierte Prompts benötigt einen größeren Bildschirm. Bitte öffnen Sie diese Seite auf einem Desktop- oder Laptop-Computer.", + "desktopOnlyDescription": "Der Prompt Builder benötigt einen größeren Bildschirm. Bitte öffnen Sie diese Seite auf einem Desktop- oder Laptop-Computer.", "browsePrompts": "Prompts durchsuchen" } } diff --git a/messages/el.json b/messages/el.json index 1d2fbda4..6c25740c 100644 --- a/messages/el.json +++ b/messages/el.json @@ -45,7 +45,7 @@ "login": "Σύνδεση", "register": "Εγγραφή", "logout": "Αποσύνδεση", - "ide": "Τυποποιημένα Prompts" + "ide": "Prompt Builder" }, "brand": { "copyLogoSvg": "Αντιγραφή Logo SVG", @@ -1164,7 +1164,7 @@ } }, "ide": { - "title": "Τυποποιημένα Prompts", + "title": "Prompt Builder", "subtitle": "Δομημένη δημιουργία prompts με ασφάλεια τύπων", "editor": "Επεξεργαστής", "preview": "Προεπισκόπηση", @@ -1173,7 +1173,7 @@ "copied": "Αντιγράφηκε στο πρόχειρο", "runToPreview": "Κάντε κλικ στο Εκτέλεση για να δείτε την προεπισκόπηση", "desktopOnly": "Μόνο για υπολογιστή", - "desktopOnlyDescription": "Ο επεξεργαστής Τυποποιημένων Prompts απαιτεί μεγαλύτερη οθόνη για να λειτουργήσει σωστά. Παρακαλώ ανοίξτε αυτή τη σελίδα σε επιτραπέζιο ή φορητό υπολογιστή.", + "desktopOnlyDescription": "Ο Prompt Builder απαιτεί μεγαλύτερη οθόνη για να λειτουργήσει σωστά. Παρακαλώ ανοίξτε αυτή τη σελίδα σε επιτραπέζιο ή φορητό υπολογιστή.", "browsePrompts": "Περιήγηση Prompts" } } diff --git a/messages/en.json b/messages/en.json index 0f84a83e..cd85b9ad 100644 --- a/messages/en.json +++ b/messages/en.json @@ -45,7 +45,7 @@ "login": "Login", "register": "Register", "logout": "Logout", - "ide": "Typed Prompts" + "ide": "Prompt Builder" }, "brand": { "copyLogoSvg": "Copy Logo SVG", @@ -1164,7 +1164,7 @@ } }, "ide": { - "title": "Typed Prompts", + "title": "Prompt Builder", "subtitle": "Type-safe, structured prompt building", "editor": "Editor", "preview": "Preview", @@ -1173,7 +1173,7 @@ "copied": "Copied to clipboard", "runToPreview": "Click Run to see the prompt preview", "desktopOnly": "Desktop Only", - "desktopOnlyDescription": "The Typed Prompts editor requires a larger screen to work properly. Please open this page on a desktop or laptop computer.", + "desktopOnlyDescription": "The Prompt Builder requires a larger screen to work properly. Please open this page on a desktop or laptop computer.", "browsePrompts": "Browse Prompts" } } diff --git a/messages/es.json b/messages/es.json index 6a4fe92d..8d61d09a 100644 --- a/messages/es.json +++ b/messages/es.json @@ -45,7 +45,7 @@ "login": "Iniciar sesión", "register": "Registrarse", "logout": "Cerrar sesión", - "ide": "Prompts Tipados" + "ide": "Prompt Builder" }, "brand": { "copyLogoSvg": "Copiar Logo SVG", @@ -1164,7 +1164,7 @@ } }, "ide": { - "title": "Prompts Tipados", + "title": "Prompt Builder", "subtitle": "Construcción de prompts estructurada y con tipado seguro", "editor": "Editor", "preview": "Vista previa", @@ -1173,7 +1173,7 @@ "copied": "Copiado al portapapeles", "runToPreview": "Haz clic en Ejecutar para ver la vista previa del prompt", "desktopOnly": "Solo escritorio", - "desktopOnlyDescription": "El editor de Prompts Tipados requiere una pantalla más grande para funcionar correctamente. Por favor, abre esta página en una computadora de escritorio o portátil.", + "desktopOnlyDescription": "El Constructor de Prompts requiere una pantalla más grande para funcionar correctamente. Por favor, abre esta página en una computadora de escritorio o portátil.", "browsePrompts": "Explorar Prompts" } } diff --git a/messages/fr.json b/messages/fr.json index 5fe3cfa5..7b18b20a 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -45,7 +45,7 @@ "login": "Connexion", "register": "Inscription", "logout": "Déconnexion", - "ide": "Prompts Typés" + "ide": "Prompt Builder" }, "brand": { "copyLogoSvg": "Copier le logo SVG", @@ -1164,7 +1164,7 @@ } }, "ide": { - "title": "Prompts Typés", + "title": "Prompt Builder", "subtitle": "Construction de prompts structurée et typée", "editor": "Éditeur", "preview": "Aperçu", @@ -1173,7 +1173,7 @@ "copied": "Copié dans le presse-papiers", "runToPreview": "Cliquez sur Exécuter pour voir l'aperçu du prompt", "desktopOnly": "Bureau uniquement", - "desktopOnlyDescription": "L'éditeur de Prompts Typés nécessite un écran plus grand pour fonctionner correctement. Veuillez ouvrir cette page sur un ordinateur de bureau ou portable.", + "desktopOnlyDescription": "Le Prompt Builder nécessite un écran plus grand pour fonctionner correctement. Veuillez ouvrir cette page sur un ordinateur de bureau ou portable.", "browsePrompts": "Parcourir les Prompts" } } diff --git a/messages/he.json b/messages/he.json index 238cf612..970bcb61 100644 --- a/messages/he.json +++ b/messages/he.json @@ -45,7 +45,7 @@ "login": "התחברות", "register": "הרשמה", "logout": "התנתקות", - "ide": "פרומפטים מוקלדים" + "ide": "Prompt Builder" }, "brand": { "copyLogoSvg": "העתק לוגו SVG", @@ -1164,7 +1164,7 @@ } }, "ide": { - "title": "פרומפטים מוקלדים", + "title": "Prompt Builder", "subtitle": "בניית פרומפטים מובנית ובטוחת טיפוסים", "editor": "עורך", "preview": "תצוגה מקדימה", @@ -1173,7 +1173,7 @@ "copied": "הועתק ללוח", "runToPreview": "לחץ על הפעל כדי לראות תצוגה מקדימה", "desktopOnly": "למחשב בלבד", - "desktopOnlyDescription": "עורך הפרומפטים המוקלדים דורש מסך גדול יותר כדי לפעול כראוי. אנא פתח דף זה במחשב שולחני או נייד.", + "desktopOnlyDescription": "בונה הפרומפטים דורש מסך גדול יותר כדי לפעול כראוי. אנא פתח דף זה במחשב שולחני או נייד.", "browsePrompts": "עיין בפרומפטים" } } diff --git a/messages/it.json b/messages/it.json index fb6151c9..856d4aab 100644 --- a/messages/it.json +++ b/messages/it.json @@ -45,7 +45,7 @@ "login": "Accedi", "register": "Registrati", "logout": "Esci", - "ide": "Prompt Tipizzati" + "ide": "Prompt Builder" }, "brand": { "copyLogoSvg": "Copia Logo SVG", @@ -1164,7 +1164,7 @@ } }, "ide": { - "title": "Prompt Tipizzati", + "title": "Prompt Builder", "subtitle": "Costruzione di prompt strutturata e type-safe", "editor": "Editor", "preview": "Anteprima", @@ -1173,7 +1173,7 @@ "copied": "Copiato negli appunti", "runToPreview": "Clicca su Esegui per vedere l'anteprima del prompt", "desktopOnly": "Solo Desktop", - "desktopOnlyDescription": "L'editor di Prompt Tipizzati richiede uno schermo più grande per funzionare correttamente. Si prega di aprire questa pagina su un computer desktop o laptop.", + "desktopOnlyDescription": "Il Prompt Builder richiede uno schermo più grande per funzionare correttamente. Si prega di aprire questa pagina su un computer desktop o laptop.", "browsePrompts": "Esplora Prompt" } } diff --git a/messages/ja.json b/messages/ja.json index bab42c79..8e7575b3 100644 --- a/messages/ja.json +++ b/messages/ja.json @@ -45,7 +45,7 @@ "login": "ログイン", "register": "登録", "logout": "ログアウト", - "ide": "型付きプロンプト" + "ide": "Prompt Builder" }, "brand": { "copyLogoSvg": "ロゴSVGをコピー", @@ -1164,7 +1164,7 @@ } }, "ide": { - "title": "型付きプロンプト", + "title": "Prompt Builder", "subtitle": "型安全で構造化されたプロンプト構築", "editor": "エディタ", "preview": "プレビュー", @@ -1173,7 +1173,7 @@ "copied": "クリップボードにコピーしました", "runToPreview": "実行をクリックしてプロンプトのプレビューを表示", "desktopOnly": "デスクトップ専用", - "desktopOnlyDescription": "型付きプロンプトエディタは、正常に動作するために大きな画面が必要です。デスクトップまたはラップトップコンピュータでこのページを開いてください。", + "desktopOnlyDescription": "プロンプトビルダーは、正常に動作するために大きな画面が必要です。デスクトップまたはラップトップコンピュータでこのページを開いてください。", "browsePrompts": "プロンプトを閲覧" } } diff --git a/messages/ko.json b/messages/ko.json index 3f162072..deca6956 100644 --- a/messages/ko.json +++ b/messages/ko.json @@ -45,7 +45,7 @@ "login": "로그인", "register": "회원가입", "logout": "로그아웃", - "ide": "타입 프롬프트" + "ide": "Prompt Builder" }, "brand": { "copyLogoSvg": "로고 SVG 복사", @@ -1164,7 +1164,7 @@ } }, "ide": { - "title": "타입 프롬프트", + "title": "Prompt Builder", "subtitle": "타입 안전하고 구조화된 프롬프트 빌딩", "editor": "에디터", "preview": "미리보기", @@ -1173,7 +1173,7 @@ "copied": "클립보드에 복사됨", "runToPreview": "실행을 클릭하여 프롬프트 미리보기 표시", "desktopOnly": "데스크톱 전용", - "desktopOnlyDescription": "타입 프롬프트 에디터는 제대로 작동하려면 더 큰 화면이 필요합니다. 데스크톱이나 노트북 컴퓨터에서 이 페이지를 열어주세요.", + "desktopOnlyDescription": "프롬프트 빌더는 제대로 작동하려면 더 큰 화면이 필요합니다. 데스크톱이나 노트북 컴퓨터에서 이 페이지를 열어주세요.", "browsePrompts": "프롬프트 둘러보기" } } diff --git a/messages/pt.json b/messages/pt.json index c6967688..9fde6f97 100644 --- a/messages/pt.json +++ b/messages/pt.json @@ -45,7 +45,7 @@ "login": "Entrar", "register": "Cadastrar", "logout": "Sair", - "ide": "Prompts Tipados" + "ide": "Prompt Builder" }, "brand": { "copyLogoSvg": "Copiar Logo SVG", @@ -1164,7 +1164,7 @@ } }, "ide": { - "title": "Prompts Tipados", + "title": "Prompt Builder", "subtitle": "Construção de prompts estruturada e type-safe", "editor": "Editor", "preview": "Pré-visualização", @@ -1173,7 +1173,7 @@ "copied": "Copiado para a área de transferência", "runToPreview": "Clique em Executar para ver a pré-visualização do prompt", "desktopOnly": "Apenas Desktop", - "desktopOnlyDescription": "O editor de Prompts Tipados requer uma tela maior para funcionar corretamente. Por favor, abra esta página em um computador desktop ou laptop.", + "desktopOnlyDescription": "O Prompt Builder requer uma tela maior para funcionar corretamente. Por favor, abra esta página em um computador desktop ou laptop.", "browsePrompts": "Explorar Prompts" } } diff --git a/messages/ru.json b/messages/ru.json index 638ca4f6..8b72520b 100644 --- a/messages/ru.json +++ b/messages/ru.json @@ -45,7 +45,7 @@ "login": "Войти", "register": "Регистрация", "logout": "Выйти", - "ide": "Типизированные промпты" + "ide": "Prompt Builder" }, "brand": { "copyLogoSvg": "Скопировать логотип SVG", @@ -1164,7 +1164,7 @@ } }, "ide": { - "title": "Типизированные промпты", + "title": "Prompt Builder", "subtitle": "Типобезопасное структурированное построение промптов", "editor": "Редактор", "preview": "Предпросмотр", @@ -1173,7 +1173,7 @@ "copied": "Скопировано в буфер обмена", "runToPreview": "Нажмите Запустить, чтобы увидеть предпросмотр промпта", "desktopOnly": "Только для ПК", - "desktopOnlyDescription": "Редактор типизированных промптов требует большего экрана для корректной работы. Пожалуйста, откройте эту страницу на настольном компьютере или ноутбуке.", + "desktopOnlyDescription": "Конструктор промптов требует большего экрана для корректной работы. Пожалуйста, откройте эту страницу на настольном компьютере или ноутбуке.", "browsePrompts": "Просмотреть промпты" } } diff --git a/messages/tr.json b/messages/tr.json index 480b3533..2640ae29 100644 --- a/messages/tr.json +++ b/messages/tr.json @@ -45,7 +45,7 @@ "login": "Giriş Yap", "register": "Kayıt Ol", "logout": "Çıkış Yap", - "ide": "Tipli Promptlar" + "ide": "Prompt Builder" }, "brand": { "copyLogoSvg": "Logo SVG'sini Kopyala", @@ -1164,7 +1164,7 @@ } }, "ide": { - "title": "Tipli Promptlar", + "title": "Prompt Builder", "subtitle": "Tip güvenli, yapılandırılmış prompt oluşturma", "editor": "Editör", "preview": "Önizleme", @@ -1173,7 +1173,7 @@ "copied": "Panoya kopyalandı", "runToPreview": "Prompt önizlemesini görmek için Çalıştır'a tıklayın", "desktopOnly": "Yalnızca Masaüstü", - "desktopOnlyDescription": "Tipli Promptlar editörü düzgün çalışması için daha büyük bir ekran gerektirir. Lütfen bu sayfayı bir masaüstü veya dizüstü bilgisayarda açın.", + "desktopOnlyDescription": "Prompt Oluşturucu düzgün çalışması için daha büyük bir ekran gerektirir. Lütfen bu sayfayı bir masaüstü veya dizüstü bilgisayarda açın.", "browsePrompts": "Promptlara Göz At" } } diff --git a/messages/zh.json b/messages/zh.json index 8650032e..93c16199 100644 --- a/messages/zh.json +++ b/messages/zh.json @@ -45,7 +45,7 @@ "login": "登录", "register": "注册", "logout": "退出登录", - "ide": "类型化提示词" + "ide": "Prompt Builder" }, "brand": { "copyLogoSvg": "复制Logo SVG", @@ -1164,7 +1164,7 @@ } }, "ide": { - "title": "类型化提示词", + "title": "Prompt Builder", "subtitle": "类型安全的结构化提示词构建", "editor": "编辑器", "preview": "预览", @@ -1173,7 +1173,7 @@ "copied": "已复制到剪贴板", "runToPreview": "点击运行查看提示词预览", "desktopOnly": "仅限桌面端", - "desktopOnlyDescription": "类型化提示词编辑器需要更大的屏幕才能正常工作。请在台式电脑或笔记本电脑上打开此页面。", + "desktopOnlyDescription": "提示词构建器需要更大的屏幕才能正常工作。请在台式电脑或笔记本电脑上打开此页面。", "browsePrompts": "浏览提示词" } } diff --git a/next.config.ts b/next.config.ts index 58d29f8d..fa23a8ee 100644 --- a/next.config.ts +++ b/next.config.ts @@ -5,6 +5,14 @@ const withNextIntl = createNextIntlPlugin("./src/i18n/request.ts"); const nextConfig: NextConfig = { reactCompiler: true, + // Configure webpack for raw imports + webpack: (config) => { + config.module.rules.push({ + resourceQuery: /raw/, + type: 'asset/source', + }); + return config; + }, // Enable standalone output for Docker // output: "standalone", // Experimental features diff --git a/package.json b/package.json index 72534c7e..482f8f8b 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,7 @@ "db:studio": "prisma studio", "db:seed": "prisma db seed", "setup": "node scripts/setup.js", + "generate:examples": "npx tsx scripts/generate-examples.ts", "postinstall": "prisma generate" }, "dependencies": { diff --git a/packages/prompts.chat/API.md b/packages/prompts.chat/API.md new file mode 100644 index 00000000..1168b206 --- /dev/null +++ b/packages/prompts.chat/API.md @@ -0,0 +1,5240 @@ +# API Reference + +> Auto-generated from TypeScript source files + +## Table of Contents + +- [variables/index](#variables/index) + - [detectVariables](#detectvariables) + - [convertToSupportedFormat](#converttosupportedformat) + - [convertAllVariables](#convertallvariables) + - [getPatternDescription](#getpatterndescription) + - [extractVariables](#extractvariables) + - [compile](#compile) +- [similarity/index](#similarity/index) + - [normalizeContent](#normalizecontent) + - [calculateSimilarity](#calculatesimilarity) + - [isSimilarContent](#issimilarcontent) + - [getContentFingerprint](#getcontentfingerprint) + - [findDuplicates](#findduplicates) + - [deduplicate](#deduplicate) +- [quality/index](#quality/index) + - [check](#check) + - [validate](#validate) + - [isValid](#isvalid) + - [getSuggestions](#getsuggestions) +- [parser/index](#parser/index) + - [parse](#parse) + - [toYaml](#toyaml) + - [toJson](#tojson) + - [getSystemPrompt](#getsystemprompt) + - [interpolate](#interpolate) +- [builder/index](#builder/index) + - [PromptBuilder](#promptbuilder) + - [builder](#builder) + - [fromPrompt](#fromprompt) +- [builder/chat](#builder/chat) + - [ChatPromptBuilder](#chatpromptbuilder) + - [chat](#chat) +- [builder/media](#builder/media) + - [ImagePromptBuilder](#imagepromptbuilder) + - [image](#image) +- [builder/video](#builder/video) + - [VideoPromptBuilder](#videopromptbuilder) + - [video](#video) +- [builder/audio](#builder/audio) + - [AudioPromptBuilder](#audiopromptbuilder) + - [audio](#audio) + +--- + +## variables/index + +Variable Detection Utility +Detects common variable-like patterns in text that could be converted +to our supported format: ${variableName} or ${variableName:default} + +### Types + +#### `VariablePattern` + +```typescript +type VariablePattern = | "double_bracket" // [[name]] or [[ name ]] + | "double_curly" // {{name}} or {{ name }} + | "single_bracket" // [NAME] or [name] + | "single_curly" // {NAME} or {name} + | "angle_bracket" // or + | "percent" // %NAME% or %name% + | "dollar_curly" +``` + +### Interfaces + +#### `DetectedVariable` + +Variable Detection Utility +Detects common variable-like patterns in text that could be converted +to our supported format: ${variableName} or ${variableName:default} + +| Property | Type | Description | +|----------|------|-------------| +| `original` | `string` | - | +| `name` | `string` | - | +| `defaultValue` | `string` | - | +| `pattern` | `VariablePattern` | - | +| `startIndex` | `number` | - | +| `endIndex` | `number` | - | + +### Functions + +#### `detectVariables()` + +Detect variable-like patterns in text +Returns detected variables that are NOT in our supported format + +```typescript +detectVariables(text: string): DetectedVariable[] +``` + +**Parameters:** + +- `text`: `string` + +**Returns:** `DetectedVariable[]` + +#### `convertToSupportedFormat()` + +Convert a detected variable to our supported format + +```typescript +convertToSupportedFormat(variable: DetectedVariable): string +``` + +**Parameters:** + +- `variable`: `DetectedVariable` + +**Returns:** `string` + +#### `convertAllVariables()` + +Convert all detected variables in text to our supported format + +```typescript +convertAllVariables(text: string): string +``` + +**Parameters:** + +- `text`: `string` + +**Returns:** `string` + +#### `getPatternDescription()` + +Get a human-readable pattern description + +```typescript +getPatternDescription(pattern: VariablePattern): string +``` + +**Parameters:** + +- `pattern`: `VariablePattern` + +**Returns:** `string` + +#### `extractVariables()` + +Extract variables from our supported ${var} or ${var:default} format + +```typescript +extractVariables(text: string): Array<{ name: string; defaultValue?: string }> +``` + +**Parameters:** + +- `text`: `string` + +**Returns:** `Array<{ name: string; defaultValue?: string }>` + +#### `compile()` + +Compile a prompt template with variable values + +```typescript +compile(template: string, values: Record, options?: { useDefaults?: boolean }): string +``` + +**Parameters:** + +- `template`: `string` +- `values`: `Record` +- `options`: `{ useDefaults?: boolean }` (optional) = `{}` + +**Returns:** `string` + +### Constants + +#### `normalize` + +Alias for convertAllVariables - normalizes all variable formats to ${var} + +```typescript +normalize = convertAllVariables +``` + +#### `detect` + +Alias for detectVariables + +```typescript +detect = detectVariables +``` + +--- + +## similarity/index + +Content similarity utilities for duplicate detection + +### Functions + +#### `normalizeContent()` + +Content similarity utilities for duplicate detection + +```typescript +normalizeContent(content: string): string +``` + +**Parameters:** + +- `content`: `string` + +**Returns:** `string` + +#### `calculateSimilarity()` + +Combined similarity score using multiple algorithms +Returns a value between 0 (completely different) and 1 (identical) + +```typescript +calculateSimilarity(content1: string, content2: string): number +``` + +**Parameters:** + +- `content1`: `string` +- `content2`: `string` + +**Returns:** `number` + +#### `isSimilarContent()` + +Check if two contents are similar enough to be considered duplicates +Default threshold is 0.85 (85% similar) + +```typescript +isSimilarContent(content1: string, content2: string, threshold?: number): boolean +``` + +**Parameters:** + +- `content1`: `string` +- `content2`: `string` +- `threshold`: `number` (optional) = `0.85` + +**Returns:** `boolean` + +#### `getContentFingerprint()` + +Get normalized content hash for database indexing/comparison +This is a simple hash for quick lookups before full similarity check + +```typescript +getContentFingerprint(content: string): string +``` + +**Parameters:** + +- `content`: `string` + +**Returns:** `string` + +#### `findDuplicates()` + +Find duplicates in an array of prompts +Returns groups of similar prompts + +```typescript +findDuplicates(prompts: T[], threshold?: number): T[][] +``` + +**Parameters:** + +- `prompts`: `T[]` +- `threshold`: `number` (optional) = `0.85` + +**Returns:** `T[][]` + +#### `deduplicate()` + +Deduplicate an array of prompts, keeping the first occurrence + +```typescript +deduplicate(prompts: T[], threshold?: number): T[] +``` + +**Parameters:** + +- `prompts`: `T[]` +- `threshold`: `number` (optional) = `0.85` + +**Returns:** `T[]` + +### Constants + +#### `calculate` + +Alias for calculateSimilarity + +```typescript +calculate = calculateSimilarity +``` + +#### `isDuplicate` + +Alias for isSimilarContent + +```typescript +isDuplicate = isSimilarContent +``` + +--- + +## quality/index + +Prompt Quality Checker - Local validation for prompt quality + +@example +```ts +import { quality } from 'prompts.chat'; + +const result = quality.check("Act as a developer..."); +console.log(result.score); // 0.85 +console.log(result.issues); // [] +``` + +### Interfaces + +#### `QualityIssue` + +Prompt Quality Checker - Local validation for prompt quality + +| Property | Type | Description | +|----------|------|-------------| +| `type` | `'error' | 'warning' | 'suggestion'` | - | +| `code` | `string` | - | +| `message` | `string` | - | +| `position` | `{ start: number; end: number }` | - | + +#### `QualityResult` + +| Property | Type | Description | +|----------|------|-------------| +| `valid` | `boolean` | - | +| `score` | `number` | - | +| `issues` | `QualityIssue[]` | - | +| `stats` | `unknown` | - | + +### Functions + +#### `check()` + +Check prompt quality locally (no API needed) + +```typescript +check(prompt: string): QualityResult +``` + +**Parameters:** + +- `prompt`: `string` + +**Returns:** `QualityResult` + +#### `validate()` + +Validate a prompt and throw if invalid + +```typescript +validate(prompt: string): void +``` + +**Parameters:** + +- `prompt`: `string` + +#### `isValid()` + +Check if a prompt is valid + +```typescript +isValid(prompt: string): boolean +``` + +**Parameters:** + +- `prompt`: `string` + +**Returns:** `boolean` + +#### `getSuggestions()` + +Get suggestions for improving a prompt + +```typescript +getSuggestions(prompt: string): string[] +``` + +**Parameters:** + +- `prompt`: `string` + +**Returns:** `string[]` + +--- + +## parser/index + +Prompt Parser - Parse and load prompt files in various formats + +Supports: +- .prompt.yml / .prompt.yaml (YAML format) +- .prompt.json (JSON format) +- .prompt.md (Markdown with frontmatter) +- .txt (Plain text) + +@example +```ts +import { parser } from 'prompts.chat'; + +const prompt = parser.parse(` +name: Code Review +messages: + - role: system + content: You are a code reviewer. +`); +``` + +### Interfaces + +#### `PromptMessage` + +Prompt Parser - Parse and load prompt files in various formats + +Supports: +- .prompt.yml / .prompt.yaml (YAML format) +- .prompt.json (JSON format) +- .prompt.md (Markdown with frontmatter) +- .txt (Plain text) + +| Property | Type | Description | +|----------|------|-------------| +| `role` | `'system' | 'user' | 'assistant'` | - | +| `content` | `string` | - | + +#### `ParsedPrompt` + +| Property | Type | Description | +|----------|------|-------------| +| `name` | `string` | - | +| `description` | `string` | - | +| `model` | `string` | - | +| `modelParameters` | `unknown` | - | +| `messages` | `PromptMessage[]` | - | +| `variables` | `unknown` | - | +| `metadata` | `Record` | - | + +### Functions + +#### `parse()` + +Parse prompt content in various formats + +```typescript +parse(content: string, format?: 'yaml' | 'json' | 'markdown' | 'text'): ParsedPrompt +``` + +**Parameters:** + +- `content`: `string` +- `format`: `'yaml' | 'json' | 'markdown' | 'text'` (optional) + +**Returns:** `ParsedPrompt` + +#### `toYaml()` + +Serialize a ParsedPrompt to YAML format + +```typescript +toYaml(prompt: ParsedPrompt): string +``` + +**Parameters:** + +- `prompt`: `ParsedPrompt` + +**Returns:** `string` + +#### `toJson()` + +Serialize a ParsedPrompt to JSON format + +```typescript +toJson(prompt: ParsedPrompt, pretty?: boolean): string +``` + +**Parameters:** + +- `prompt`: `ParsedPrompt` +- `pretty`: `boolean` (optional) = `true` + +**Returns:** `string` + +#### `getSystemPrompt()` + +Get the system message content from a parsed prompt + +```typescript +getSystemPrompt(prompt: ParsedPrompt): string +``` + +**Parameters:** + +- `prompt`: `ParsedPrompt` + +**Returns:** `string` + +#### `interpolate()` + +Interpolate variables in a prompt + +```typescript +interpolate(prompt: ParsedPrompt, values: Record): ParsedPrompt +``` + +**Parameters:** + +- `prompt`: `ParsedPrompt` +- `values`: `Record` + +**Returns:** `ParsedPrompt` + +--- + +## builder/index + +Prompt Builder - A fluent DSL for creating structured prompts + +@example +```ts +import { builder } from 'prompts.chat'; + +const prompt = builder() + .role("Senior TypeScript Developer") + .context("You are helping review code") + .task("Analyze the following code for bugs") + .constraints(["Be concise", "Focus on critical issues"]) + .output("JSON with { bugs: [], suggestions: [] }") + .variable("code", { required: true }) + .build(); +``` + +### Interfaces + +#### `PromptVariable` + +Prompt Builder - A fluent DSL for creating structured prompts + +| Property | Type | Description | +|----------|------|-------------| +| `name` | `string` | - | +| `description` | `string` | - | +| `required` | `boolean` | - | +| `defaultValue` | `string` | - | + +#### `BuiltPrompt` + +| Property | Type | Description | +|----------|------|-------------| +| `content` | `string` | - | +| `variables` | `PromptVariable[]` | - | +| `metadata` | `unknown` | - | + +### Classes + +#### `PromptBuilder` + +**Methods:** + +| Method | Description | +|--------|-------------| +| `role(role: string): this` | Set the role/persona for the AI | +| `persona(persona: string): this` | Alias for role() | +| `context(context: string): this` | Set the context/background information | +| `background(background: string): this` | Alias for context() | +| `task(task: string): this` | Set the main task/instruction | +| `instruction(instruction: string): this` | Alias for task() | +| `constraints(constraints: string[]): this` | Add constraints/rules the AI should follow | +| `constraint(constraint: string): this` | Add a single constraint | +| `rules(rules: string[]): this` | Alias for constraints() | +| `output(format: string): this` | Set the expected output format | +| `format(format: string): this` | Alias for output() | +| `example(input: string, output: string): this` | Add an example input/output pair | +| `examples(examples: Array<{ input: string; output: string }>): this` | Add multiple examples | +| `variable(name: string, options?: { description?: string; required?: boolean; defaultValue?: string }): this` | Define a variable placeholder | +| `section(title: string, content: string): this` | Add a custom section | +| `raw(content: string): this` | Set raw content (bypasses structured building) | +| `build(): BuiltPrompt` | Build the final prompt | +| `toString(): string` | Build and return only the content string | + +##### `role()` + +Set the role/persona for the AI + +```typescript +role(role: string): this +``` + +**Parameters:** + +- `role`: `string` + +**Returns:** `this` + +##### `persona()` + +Alias for role() + +```typescript +persona(persona: string): this +``` + +**Parameters:** + +- `persona`: `string` + +**Returns:** `this` + +##### `context()` + +Set the context/background information + +```typescript +context(context: string): this +``` + +**Parameters:** + +- `context`: `string` + +**Returns:** `this` + +##### `background()` + +Alias for context() + +```typescript +background(background: string): this +``` + +**Parameters:** + +- `background`: `string` + +**Returns:** `this` + +##### `task()` + +Set the main task/instruction + +```typescript +task(task: string): this +``` + +**Parameters:** + +- `task`: `string` + +**Returns:** `this` + +##### `instruction()` + +Alias for task() + +```typescript +instruction(instruction: string): this +``` + +**Parameters:** + +- `instruction`: `string` + +**Returns:** `this` + +##### `constraints()` + +Add constraints/rules the AI should follow + +```typescript +constraints(constraints: string[]): this +``` + +**Parameters:** + +- `constraints`: `string[]` + +**Returns:** `this` + +##### `constraint()` + +Add a single constraint + +```typescript +constraint(constraint: string): this +``` + +**Parameters:** + +- `constraint`: `string` + +**Returns:** `this` + +##### `rules()` + +Alias for constraints() + +```typescript +rules(rules: string[]): this +``` + +**Parameters:** + +- `rules`: `string[]` + +**Returns:** `this` + +##### `output()` + +Set the expected output format + +```typescript +output(format: string): this +``` + +**Parameters:** + +- `format`: `string` + +**Returns:** `this` + +##### `format()` + +Alias for output() + +```typescript +format(format: string): this +``` + +**Parameters:** + +- `format`: `string` + +**Returns:** `this` + +##### `example()` + +Add an example input/output pair + +```typescript +example(input: string, output: string): this +``` + +**Parameters:** + +- `input`: `string` +- `output`: `string` + +**Returns:** `this` + +##### `examples()` + +Add multiple examples + +```typescript +examples(examples: Array<{ input: string; output: string }>): this +``` + +**Parameters:** + +- `examples`: `Array<{ input: string; output: string }>` + +**Returns:** `this` + +##### `variable()` + +Define a variable placeholder + +```typescript +variable(name: string, options?: { description?: string; required?: boolean; defaultValue?: string }): this +``` + +**Parameters:** + +- `name`: `string` +- `options`: `{ description?: string; required?: boolean; defaultValue?: string }` (optional) = `{}` + +**Returns:** `this` + +##### `section()` + +Add a custom section + +```typescript +section(title: string, content: string): this +``` + +**Parameters:** + +- `title`: `string` +- `content`: `string` + +**Returns:** `this` + +##### `raw()` + +Set raw content (bypasses structured building) + +```typescript +raw(content: string): this +``` + +**Parameters:** + +- `content`: `string` + +**Returns:** `this` + +##### `build()` + +Build the final prompt + +```typescript +build(): BuiltPrompt +``` + +**Returns:** `BuiltPrompt` + +##### `toString()` + +Build and return only the content string + +```typescript +toString(): string +``` + +**Returns:** `string` + +### Functions + +#### `builder()` + +Create a new prompt builder + +```typescript +builder(): PromptBuilder +``` + +**Returns:** `PromptBuilder` + +#### `fromPrompt()` + +Create a prompt builder from an existing prompt + +```typescript +fromPrompt(content: string): PromptBuilder +``` + +**Parameters:** + +- `content`: `string` + +**Returns:** `PromptBuilder` + +### Constants + +#### `templates` + +```typescript +templates +``` + +--- + +## builder/chat + +Chat Prompt Builder - Model-Agnostic Conversation Prompt Builder + +Build structured prompts for any chat/conversation model. +Focus on prompt engineering, not model-specific features. + +@example +```ts +import { chat } from 'prompts.chat/builder'; + +const prompt = chat() + .role("helpful coding assistant") + .context("Building a React application") + .task("Explain async/await in JavaScript") + .stepByStep() + .detailed() + .build(); +``` + +### Types + +#### `MessageRole` + +Chat Prompt Builder - Model-Agnostic Conversation Prompt Builder + +Build structured prompts for any chat/conversation model. +Focus on prompt engineering, not model-specific features. + +```typescript +type MessageRole = 'system' | 'user' | 'assistant' +``` + +#### `ResponseFormatType` + +```typescript +type ResponseFormatType = 'text' | 'json' | 'markdown' | 'code' | 'table' +``` + +#### `PersonaTone` + +```typescript +type PersonaTone = | 'professional' | 'casual' | 'formal' | 'friendly' | 'academic' + | 'technical' | 'creative' | 'empathetic' | 'authoritative' | 'playful' + | 'concise' | 'detailed' | 'socratic' | 'coaching' | 'analytical' + | 'encouraging' | 'neutral' | 'humorous' | 'serious' +``` + +#### `PersonaExpertise` + +```typescript +type PersonaExpertise = | 'general' | 'coding' | 'writing' | 'analysis' | 'research' + | 'teaching' | 'counseling' | 'creative' | 'legal' | 'medical' + | 'financial' | 'scientific' | 'engineering' | 'design' | 'marketing' + | 'business' | 'philosophy' | 'history' | 'languages' | 'mathematics' +``` + +#### `ReasoningStyle` + +```typescript +type ReasoningStyle = | 'step-by-step' | 'chain-of-thought' | 'tree-of-thought' + | 'direct' | 'analytical' | 'comparative' | 'deductive' | 'inductive' + | 'first-principles' | 'analogical' | 'devil-advocate' +``` + +#### `OutputLength` + +```typescript +type OutputLength = 'brief' | 'moderate' | 'detailed' | 'comprehensive' | 'exhaustive' +``` + +#### `OutputStyle` + +```typescript +type OutputStyle = 'prose' | 'bullet-points' | 'numbered-list' | 'table' | 'code' | 'mixed' | 'qa' | 'dialogue' +``` + +### Interfaces + +#### `ChatMessage` + +| Property | Type | Description | +|----------|------|-------------| +| `role` | `MessageRole` | - | +| `content` | `string` | - | +| `name` | `string` | - | + +#### `JsonSchema` + +| Property | Type | Description | +|----------|------|-------------| +| `name` | `string` | - | +| `description` | `string` | - | +| `schema` | `Record` | - | + +#### `ResponseFormat` + +| Property | Type | Description | +|----------|------|-------------| +| `type` | `ResponseFormatType` | - | +| `jsonSchema` | `JsonSchema` | - | +| `language` | `string` | - | + +#### `ChatPersona` + +| Property | Type | Description | +|----------|------|-------------| +| `name` | `string` | - | +| `role` | `string` | - | +| `tone` | `PersonaTone | PersonaTone[]` | - | +| `expertise` | `PersonaExpertise | PersonaExpertise[]` | - | +| `personality` | `string[]` | - | +| `background` | `string` | - | +| `language` | `string` | - | +| `verbosity` | `OutputLength` | - | + +#### `ChatContext` + +| Property | Type | Description | +|----------|------|-------------| +| `background` | `string` | - | +| `domain` | `string` | - | +| `audience` | `string` | - | +| `purpose` | `string` | - | +| `constraints` | `string[]` | - | +| `assumptions` | `string[]` | - | +| `knowledge` | `string[]` | - | + +#### `ChatTask` + +| Property | Type | Description | +|----------|------|-------------| +| `instruction` | `string` | - | +| `steps` | `string[]` | - | +| `deliverables` | `string[]` | - | +| `criteria` | `string[]` | - | +| `antiPatterns` | `string[]` | - | +| `priority` | `'accuracy' | 'speed' | 'creativity' | 'thoroughness'` | - | + +#### `ChatOutput` + +| Property | Type | Description | +|----------|------|-------------| +| `format` | `ResponseFormat` | - | +| `length` | `OutputLength` | - | +| `style` | `OutputStyle` | - | +| `language` | `string` | - | +| `includeExplanation` | `boolean` | - | +| `includeExamples` | `boolean` | - | +| `includeSources` | `boolean` | - | +| `includeConfidence` | `boolean` | - | + +#### `ChatReasoning` + +| Property | Type | Description | +|----------|------|-------------| +| `style` | `ReasoningStyle` | - | +| `showWork` | `boolean` | - | +| `verifyAnswer` | `boolean` | - | +| `considerAlternatives` | `boolean` | - | +| `explainAssumptions` | `boolean` | - | + +#### `ChatExample` + +| Property | Type | Description | +|----------|------|-------------| +| `input` | `string` | - | +| `output` | `string` | - | +| `explanation` | `string` | - | + +#### `ChatMemory` + +| Property | Type | Description | +|----------|------|-------------| +| `summary` | `string` | - | +| `facts` | `string[]` | - | +| `preferences` | `string[]` | - | +| `history` | `ChatMessage[]` | - | + +#### `BuiltChatPrompt` + +| Property | Type | Description | +|----------|------|-------------| +| `messages` | `ChatMessage[]` | - | +| `systemPrompt` | `string` | - | +| `userPrompt` | `string` | - | +| `metadata` | `unknown` | - | + +### Classes + +#### `ChatPromptBuilder` + +**Methods:** + +| Method | Description | +|--------|-------------| +| `system(content: string): this` | - | +| `user(content: string, name?: string): this` | - | +| `assistant(content: string): this` | - | +| `message(role: MessageRole, content: string, name?: string): this` | - | +| `messages(messages: ChatMessage[]): this` | - | +| `conversation(turns: Array<{ user: string; assistant?: string }>): this` | - | +| `persona(settings: ChatPersona | string): this` | - | +| `role(role: string): this` | - | +| `tone(tone: PersonaTone | PersonaTone[]): this` | - | +| `expertise(expertise: PersonaExpertise | PersonaExpertise[]): this` | - | +| `personality(traits: string[]): this` | - | +| `background(background: string): this` | - | +| `speakAs(name: string): this` | - | +| `responseLanguage(language: string): this` | - | +| `context(settings: ChatContext | string): this` | - | +| `domain(domain: string): this` | - | +| `audience(audience: string): this` | - | +| `purpose(purpose: string): this` | - | +| `constraints(constraints: string[]): this` | - | +| `constraint(constraint: string): this` | - | +| `assumptions(assumptions: string[]): this` | - | +| `knowledge(facts: string[]): this` | - | +| `task(instruction: string | ChatTask): this` | - | +| `instruction(instruction: string): this` | - | +| `steps(steps: string[]): this` | - | +| `deliverables(deliverables: string[]): this` | - | +| `criteria(criteria: string[]): this` | - | +| `avoid(antiPatterns: string[]): this` | - | +| `priority(priority: ChatTask['priority']): this` | - | +| `example(input: string, output: string, explanation?: string): this` | - | +| `examples(examples: ChatExample[]): this` | - | +| `fewShot(examples: Array<{ input: string; output: string }>): this` | - | +| `output(settings: ChatOutput): this` | - | +| `outputFormat(format: ResponseFormatType): this` | - | +| `json(schema?: JsonSchema): this` | - | +| `jsonSchema(name: string, schema: Record, description?: string): this` | - | +| `markdown(): this` | - | +| `code(language?: string): this` | - | +| `table(): this` | - | +| `length(length: OutputLength): this` | - | +| `style(style: OutputStyle): this` | - | +| `brief(): this` | - | +| `moderate(): this` | - | +| `detailed(): this` | - | +| `comprehensive(): this` | - | +| `exhaustive(): this` | - | +| `withExamples(): this` | - | +| `withExplanation(): this` | - | +| `withSources(): this` | - | +| `withConfidence(): this` | - | +| `reasoning(settings: ChatReasoning): this` | - | +| `reasoningStyle(style: ReasoningStyle): this` | - | +| `stepByStep(): this` | - | +| `chainOfThought(): this` | - | +| `treeOfThought(): this` | - | +| `firstPrinciples(): this` | - | +| `devilsAdvocate(): this` | - | +| `showWork(show?: any): this` | - | +| `verifyAnswer(verify?: any): this` | - | +| `considerAlternatives(consider?: any): this` | - | +| `explainAssumptions(explain?: any): this` | - | +| `memory(memory: ChatMemory): this` | - | +| `remember(facts: string[]): this` | - | +| `preferences(prefs: string[]): this` | - | +| `history(messages: ChatMessage[]): this` | - | +| `summarizeHistory(summary: string): this` | - | +| `addSystemPart(part: string): this` | - | +| `raw(content: string): this` | - | +| `build(): BuiltChatPrompt` | - | +| `toString(): string` | - | +| `toSystemPrompt(): string` | - | +| `toMessages(): ChatMessage[]` | - | +| `toJSON(): string` | - | +| `toYAML(): string` | - | +| `toMarkdown(): string` | - | + +##### `system()` + +```typescript +system(content: string): this +``` + +**Parameters:** + +- `content`: `string` + +**Returns:** `this` + +##### `user()` + +```typescript +user(content: string, name?: string): this +``` + +**Parameters:** + +- `content`: `string` +- `name`: `string` (optional) + +**Returns:** `this` + +##### `assistant()` + +```typescript +assistant(content: string): this +``` + +**Parameters:** + +- `content`: `string` + +**Returns:** `this` + +##### `message()` + +```typescript +message(role: MessageRole, content: string, name?: string): this +``` + +**Parameters:** + +- `role`: `MessageRole` +- `content`: `string` +- `name`: `string` (optional) + +**Returns:** `this` + +##### `messages()` + +```typescript +messages(messages: ChatMessage[]): this +``` + +**Parameters:** + +- `messages`: `ChatMessage[]` + +**Returns:** `this` + +##### `conversation()` + +```typescript +conversation(turns: Array<{ user: string; assistant?: string }>): this +``` + +**Parameters:** + +- `turns`: `Array<{ user: string; assistant?: string }>` + +**Returns:** `this` + +##### `persona()` + +```typescript +persona(settings: ChatPersona | string): this +``` + +**Parameters:** + +- `settings`: `ChatPersona | string` + +**Returns:** `this` + +##### `role()` + +```typescript +role(role: string): this +``` + +**Parameters:** + +- `role`: `string` + +**Returns:** `this` + +##### `tone()` + +```typescript +tone(tone: PersonaTone | PersonaTone[]): this +``` + +**Parameters:** + +- `tone`: `PersonaTone | PersonaTone[]` + +**Returns:** `this` + +##### `expertise()` + +```typescript +expertise(expertise: PersonaExpertise | PersonaExpertise[]): this +``` + +**Parameters:** + +- `expertise`: `PersonaExpertise | PersonaExpertise[]` + +**Returns:** `this` + +##### `personality()` + +```typescript +personality(traits: string[]): this +``` + +**Parameters:** + +- `traits`: `string[]` + +**Returns:** `this` + +##### `background()` + +```typescript +background(background: string): this +``` + +**Parameters:** + +- `background`: `string` + +**Returns:** `this` + +##### `speakAs()` + +```typescript +speakAs(name: string): this +``` + +**Parameters:** + +- `name`: `string` + +**Returns:** `this` + +##### `responseLanguage()` + +```typescript +responseLanguage(language: string): this +``` + +**Parameters:** + +- `language`: `string` + +**Returns:** `this` + +##### `context()` + +```typescript +context(settings: ChatContext | string): this +``` + +**Parameters:** + +- `settings`: `ChatContext | string` + +**Returns:** `this` + +##### `domain()` + +```typescript +domain(domain: string): this +``` + +**Parameters:** + +- `domain`: `string` + +**Returns:** `this` + +##### `audience()` + +```typescript +audience(audience: string): this +``` + +**Parameters:** + +- `audience`: `string` + +**Returns:** `this` + +##### `purpose()` + +```typescript +purpose(purpose: string): this +``` + +**Parameters:** + +- `purpose`: `string` + +**Returns:** `this` + +##### `constraints()` + +```typescript +constraints(constraints: string[]): this +``` + +**Parameters:** + +- `constraints`: `string[]` + +**Returns:** `this` + +##### `constraint()` + +```typescript +constraint(constraint: string): this +``` + +**Parameters:** + +- `constraint`: `string` + +**Returns:** `this` + +##### `assumptions()` + +```typescript +assumptions(assumptions: string[]): this +``` + +**Parameters:** + +- `assumptions`: `string[]` + +**Returns:** `this` + +##### `knowledge()` + +```typescript +knowledge(facts: string[]): this +``` + +**Parameters:** + +- `facts`: `string[]` + +**Returns:** `this` + +##### `task()` + +```typescript +task(instruction: string | ChatTask): this +``` + +**Parameters:** + +- `instruction`: `string | ChatTask` + +**Returns:** `this` + +##### `instruction()` + +```typescript +instruction(instruction: string): this +``` + +**Parameters:** + +- `instruction`: `string` + +**Returns:** `this` + +##### `steps()` + +```typescript +steps(steps: string[]): this +``` + +**Parameters:** + +- `steps`: `string[]` + +**Returns:** `this` + +##### `deliverables()` + +```typescript +deliverables(deliverables: string[]): this +``` + +**Parameters:** + +- `deliverables`: `string[]` + +**Returns:** `this` + +##### `criteria()` + +```typescript +criteria(criteria: string[]): this +``` + +**Parameters:** + +- `criteria`: `string[]` + +**Returns:** `this` + +##### `avoid()` + +```typescript +avoid(antiPatterns: string[]): this +``` + +**Parameters:** + +- `antiPatterns`: `string[]` + +**Returns:** `this` + +##### `priority()` + +```typescript +priority(priority: ChatTask['priority']): this +``` + +**Parameters:** + +- `priority`: `ChatTask['priority']` + +**Returns:** `this` + +##### `example()` + +```typescript +example(input: string, output: string, explanation?: string): this +``` + +**Parameters:** + +- `input`: `string` +- `output`: `string` +- `explanation`: `string` (optional) + +**Returns:** `this` + +##### `examples()` + +```typescript +examples(examples: ChatExample[]): this +``` + +**Parameters:** + +- `examples`: `ChatExample[]` + +**Returns:** `this` + +##### `fewShot()` + +```typescript +fewShot(examples: Array<{ input: string; output: string }>): this +``` + +**Parameters:** + +- `examples`: `Array<{ input: string; output: string }>` + +**Returns:** `this` + +##### `output()` + +```typescript +output(settings: ChatOutput): this +``` + +**Parameters:** + +- `settings`: `ChatOutput` + +**Returns:** `this` + +##### `outputFormat()` + +```typescript +outputFormat(format: ResponseFormatType): this +``` + +**Parameters:** + +- `format`: `ResponseFormatType` + +**Returns:** `this` + +##### `json()` + +```typescript +json(schema?: JsonSchema): this +``` + +**Parameters:** + +- `schema`: `JsonSchema` (optional) + +**Returns:** `this` + +##### `jsonSchema()` + +```typescript +jsonSchema(name: string, schema: Record, description?: string): this +``` + +**Parameters:** + +- `name`: `string` +- `schema`: `Record` +- `description`: `string` (optional) + +**Returns:** `this` + +##### `markdown()` + +```typescript +markdown(): this +``` + +**Returns:** `this` + +##### `code()` + +```typescript +code(language?: string): this +``` + +**Parameters:** + +- `language`: `string` (optional) + +**Returns:** `this` + +##### `table()` + +```typescript +table(): this +``` + +**Returns:** `this` + +##### `length()` + +```typescript +length(length: OutputLength): this +``` + +**Parameters:** + +- `length`: `OutputLength` + +**Returns:** `this` + +##### `style()` + +```typescript +style(style: OutputStyle): this +``` + +**Parameters:** + +- `style`: `OutputStyle` + +**Returns:** `this` + +##### `brief()` + +```typescript +brief(): this +``` + +**Returns:** `this` + +##### `moderate()` + +```typescript +moderate(): this +``` + +**Returns:** `this` + +##### `detailed()` + +```typescript +detailed(): this +``` + +**Returns:** `this` + +##### `comprehensive()` + +```typescript +comprehensive(): this +``` + +**Returns:** `this` + +##### `exhaustive()` + +```typescript +exhaustive(): this +``` + +**Returns:** `this` + +##### `withExamples()` + +```typescript +withExamples(): this +``` + +**Returns:** `this` + +##### `withExplanation()` + +```typescript +withExplanation(): this +``` + +**Returns:** `this` + +##### `withSources()` + +```typescript +withSources(): this +``` + +**Returns:** `this` + +##### `withConfidence()` + +```typescript +withConfidence(): this +``` + +**Returns:** `this` + +##### `reasoning()` + +```typescript +reasoning(settings: ChatReasoning): this +``` + +**Parameters:** + +- `settings`: `ChatReasoning` + +**Returns:** `this` + +##### `reasoningStyle()` + +```typescript +reasoningStyle(style: ReasoningStyle): this +``` + +**Parameters:** + +- `style`: `ReasoningStyle` + +**Returns:** `this` + +##### `stepByStep()` + +```typescript +stepByStep(): this +``` + +**Returns:** `this` + +##### `chainOfThought()` + +```typescript +chainOfThought(): this +``` + +**Returns:** `this` + +##### `treeOfThought()` + +```typescript +treeOfThought(): this +``` + +**Returns:** `this` + +##### `firstPrinciples()` + +```typescript +firstPrinciples(): this +``` + +**Returns:** `this` + +##### `devilsAdvocate()` + +```typescript +devilsAdvocate(): this +``` + +**Returns:** `this` + +##### `showWork()` + +```typescript +showWork(show?: any): this +``` + +**Parameters:** + +- `show`: `any` (optional) = `true` + +**Returns:** `this` + +##### `verifyAnswer()` + +```typescript +verifyAnswer(verify?: any): this +``` + +**Parameters:** + +- `verify`: `any` (optional) = `true` + +**Returns:** `this` + +##### `considerAlternatives()` + +```typescript +considerAlternatives(consider?: any): this +``` + +**Parameters:** + +- `consider`: `any` (optional) = `true` + +**Returns:** `this` + +##### `explainAssumptions()` + +```typescript +explainAssumptions(explain?: any): this +``` + +**Parameters:** + +- `explain`: `any` (optional) = `true` + +**Returns:** `this` + +##### `memory()` + +```typescript +memory(memory: ChatMemory): this +``` + +**Parameters:** + +- `memory`: `ChatMemory` + +**Returns:** `this` + +##### `remember()` + +```typescript +remember(facts: string[]): this +``` + +**Parameters:** + +- `facts`: `string[]` + +**Returns:** `this` + +##### `preferences()` + +```typescript +preferences(prefs: string[]): this +``` + +**Parameters:** + +- `prefs`: `string[]` + +**Returns:** `this` + +##### `history()` + +```typescript +history(messages: ChatMessage[]): this +``` + +**Parameters:** + +- `messages`: `ChatMessage[]` + +**Returns:** `this` + +##### `summarizeHistory()` + +```typescript +summarizeHistory(summary: string): this +``` + +**Parameters:** + +- `summary`: `string` + +**Returns:** `this` + +##### `addSystemPart()` + +```typescript +addSystemPart(part: string): this +``` + +**Parameters:** + +- `part`: `string` + +**Returns:** `this` + +##### `raw()` + +```typescript +raw(content: string): this +``` + +**Parameters:** + +- `content`: `string` + +**Returns:** `this` + +##### `build()` + +```typescript +build(): BuiltChatPrompt +``` + +**Returns:** `BuiltChatPrompt` + +##### `toString()` + +```typescript +toString(): string +``` + +**Returns:** `string` + +##### `toSystemPrompt()` + +```typescript +toSystemPrompt(): string +``` + +**Returns:** `string` + +##### `toMessages()` + +```typescript +toMessages(): ChatMessage[] +``` + +**Returns:** `ChatMessage[]` + +##### `toJSON()` + +```typescript +toJSON(): string +``` + +**Returns:** `string` + +##### `toYAML()` + +```typescript +toYAML(): string +``` + +**Returns:** `string` + +##### `toMarkdown()` + +```typescript +toMarkdown(): string +``` + +**Returns:** `string` + +### Functions + +#### `chat()` + +Create a new chat prompt builder + +```typescript +chat(): ChatPromptBuilder +``` + +**Returns:** `ChatPromptBuilder` + +### Constants + +#### `chatPresets` + +```typescript +chatPresets +``` + +--- + +## builder/media + +Media Prompt Builders - The D3.js of Prompt Building + +Comprehensive, structured builders for Image, Video, and Audio generation prompts. +Every attribute a professional would consider is available as a chainable method. + +@example +```ts +import { image, video, audio } from 'prompts.chat/builder'; + +const imagePrompt = image() + .subject("a lone samurai") + .environment("bamboo forest at dawn") + .camera({ angle: "low", shot: "wide", lens: "35mm" }) + .lighting({ type: "rim", time: "golden-hour" }) + .style({ artist: "Akira Kurosawa", medium: "cinematic" }) + .build(); +``` + +### Types + +#### `OutputFormat` + +Media Prompt Builders - The D3.js of Prompt Building + +Comprehensive, structured builders for Image, Video, and Audio generation prompts. +Every attribute a professional would consider is available as a chainable method. + +```typescript +type OutputFormat = 'text' | 'json' | 'yaml' | 'markdown' +``` + +#### `CameraBrand` + +```typescript +type CameraBrand = | 'sony' | 'canon' | 'nikon' | 'fujifilm' | 'leica' | 'hasselblad' | 'phase-one' + | 'panasonic' | 'olympus' | 'pentax' | 'red' | 'arri' | 'blackmagic' | 'panavision' +``` + +#### `CameraModel` + +```typescript +type CameraModel = | 'sony-a7iv' | 'sony-a7riv' | 'sony-a7siii' | 'sony-a1' | 'sony-fx3' | 'sony-fx6' + | 'sony-venice' | 'sony-venice-2' | 'sony-a9ii' | 'sony-zv-e1' + // Canon + | 'canon-r5' | 'canon-r6' | 'canon-r3' | 'canon-r8' | 'canon-c70' | 'canon-c300-iii' + | 'canon-c500-ii' | 'canon-5d-iv' | 'canon-1dx-iii' | 'canon-eos-r5c' + // Nikon + | 'nikon-z9' | 'nikon-z8' | 'nikon-z6-iii' | 'nikon-z7-ii' | 'nikon-d850' | 'nikon-d6' + // Fujifilm + | 'fujifilm-x-t5' | 'fujifilm-x-h2s' | 'fujifilm-x100vi' | 'fujifilm-gfx100s' + | 'fujifilm-gfx100-ii' | 'fujifilm-x-pro3' + // Leica + | 'leica-m11' | 'leica-sl2' | 'leica-sl2-s' | 'leica-q3' | 'leica-m10-r' + // Hasselblad + | 'hasselblad-x2d' | 'hasselblad-907x' | 'hasselblad-h6d-100c' + // Cinema Cameras + | 'arri-alexa-35' | 'arri-alexa-mini-lf' | 'arri-alexa-65' | 'arri-amira' + | 'red-v-raptor' | 'red-komodo' | 'red-gemini' | 'red-monstro' + | 'blackmagic-ursa-mini-pro' | 'blackmagic-pocket-6k' | 'blackmagic-pocket-4k' + | 'panavision-dxl2' | 'panavision-millennium-xl2' +``` + +#### `SensorFormat` + +```typescript +type SensorFormat = | 'full-frame' | 'aps-c' | 'micro-four-thirds' | 'medium-format' | 'large-format' + | 'super-35' | 'vista-vision' | 'imax' | '65mm' | '35mm-film' | '16mm-film' | '8mm-film' +``` + +#### `FilmFormat` + +```typescript +type FilmFormat = | '35mm' | '120-medium-format' | '4x5-large-format' | '8x10-large-format' + | '110-film' | 'instant-film' | 'super-8' | '16mm' | '65mm-imax' +``` + +#### `CameraAngle` + +```typescript +type CameraAngle = | 'eye-level' | 'low-angle' | 'high-angle' | 'dutch-angle' | 'birds-eye' + | 'worms-eye' | 'over-the-shoulder' | 'point-of-view' | 'aerial' | 'drone' + | 'canted' | 'oblique' | 'hip-level' | 'knee-level' | 'ground-level' +``` + +#### `ShotType` + +```typescript +type ShotType = | 'extreme-close-up' | 'close-up' | 'medium-close-up' | 'medium' | 'medium-wide' + | 'wide' | 'extreme-wide' | 'establishing' | 'full-body' | 'portrait' | 'headshot' +``` + +#### `LensType` + +```typescript +type LensType = | 'wide-angle' | 'ultra-wide' | 'standard' | 'telephoto' | 'macro' | 'fisheye' + | '14mm' | '24mm' | '35mm' | '50mm' | '85mm' | '100mm' | '135mm' | '200mm' | '400mm' + | '600mm' | '800mm' | 'tilt-shift' | 'anamorphic' | 'spherical' | 'prime' | 'zoom' +``` + +#### `LensBrand` + +```typescript +type LensBrand = | 'zeiss' | 'leica' | 'canon' | 'nikon' | 'sony' | 'sigma' | 'tamron' | 'voigtlander' + | 'fujifilm' | 'samyang' | 'rokinon' | 'tokina' | 'cooke' | 'arri' | 'panavision' + | 'angenieux' | 'red' | 'atlas' | 'sirui' +``` + +#### `LensModel` + +```typescript +type LensModel = | 'zeiss-otus-55' | 'zeiss-batis-85' | 'zeiss-milvus-35' | 'zeiss-supreme-prime' + // Leica + | 'leica-summilux-50' | 'leica-summicron-35' | 'leica-noctilux-50' | 'leica-apo-summicron' + // Canon + | 'canon-rf-50-1.2' | 'canon-rf-85-1.2' | 'canon-rf-28-70-f2' | 'canon-rf-100-500' + // Sony + | 'sony-gm-24-70' | 'sony-gm-70-200' | 'sony-gm-50-1.2' | 'sony-gm-85-1.4' + // Sigma Art + | 'sigma-art-35' | 'sigma-art-50' | 'sigma-art-85' | 'sigma-art-105-macro' + // Cinema + | 'cooke-s7i' | 'cooke-anamorphic' | 'arri-signature-prime' | 'arri-ultra-prime' + | 'panavision-primo' | 'panavision-anamorphic' | 'atlas-orion-anamorphic' + // Vintage + | 'helios-44-2' | 'canon-fd-55' | 'minolta-rokkor-58' | 'pentax-takumar-50' +``` + +#### `FocusType` + +```typescript +type FocusType = | 'shallow' | 'deep' | 'soft-focus' | 'tilt-shift' | 'rack-focus' | 'split-diopter' + | 'zone-focus' | 'hyperfocal' | 'selective' | 'bokeh-heavy' | 'tack-sharp' +``` + +#### `BokehStyle` + +```typescript +type BokehStyle = | 'smooth' | 'creamy' | 'swirly' | 'busy' | 'soap-bubble' | 'cat-eye' | 'oval-anamorphic' +``` + +#### `FilterType` + +```typescript +type FilterType = | 'uv' | 'polarizer' | 'nd' | 'nd-graduated' | 'black-pro-mist' | 'white-pro-mist' + | 'glimmer-glass' | 'classic-soft' | 'streak' | 'starburst' | 'diffusion' + | 'infrared' | 'color-gel' | 'warming' | 'cooling' | 'vintage-look' +``` + +#### `CameraMovement` + +```typescript +type CameraMovement = | 'static' | 'pan' | 'tilt' | 'dolly' | 'truck' | 'pedestal' | 'zoom' + | 'handheld' | 'steadicam' | 'crane' | 'drone' | 'tracking' | 'arc' | 'whip-pan' + | 'roll' | 'boom' | 'jib' | 'cable-cam' | 'motion-control' | 'snorricam' + | 'dutch-roll' | 'vertigo-effect' | 'crash-zoom' | 'slow-push' | 'slow-pull' +``` + +#### `CameraRig` + +```typescript +type CameraRig = | 'tripod' | 'monopod' | 'gimbal' | 'steadicam' | 'easyrig' | 'shoulder-rig' + | 'slider' | 'dolly' | 'jib' | 'crane' | 'technocrane' | 'russian-arm' + | 'cable-cam' | 'drone' | 'fpv-drone' | 'motion-control' | 'handheld' +``` + +#### `GimbalModel` + +```typescript +type GimbalModel = | 'dji-ronin-4d' | 'dji-ronin-rs3-pro' | 'dji-ronin-rs4' | 'moza-air-2' + | 'zhiyun-crane-3s' | 'freefly-movi-pro' | 'tilta-gravity-g2x' +``` + +#### `LightingType` + +```typescript +type LightingType = | 'natural' | 'studio' | 'dramatic' | 'soft' | 'hard' | 'diffused' + | 'key' | 'fill' | 'rim' | 'backlit' | 'silhouette' | 'rembrandt' + | 'split' | 'butterfly' | 'loop' | 'broad' | 'short' | 'chiaroscuro' + | 'high-key' | 'low-key' | 'three-point' | 'practical' | 'motivated' +``` + +#### `TimeOfDay` + +```typescript +type TimeOfDay = | 'dawn' | 'sunrise' | 'golden-hour' | 'morning' | 'midday' | 'afternoon' + | 'blue-hour' | 'sunset' | 'dusk' | 'twilight' | 'night' | 'midnight' +``` + +#### `WeatherLighting` + +```typescript +type WeatherLighting = | 'sunny' | 'cloudy' | 'overcast' | 'foggy' | 'misty' | 'rainy' + | 'stormy' | 'snowy' | 'hazy' +``` + +#### `ArtStyle` + +```typescript +type ArtStyle = | 'photorealistic' | 'hyperrealistic' | 'cinematic' | 'documentary' + | 'editorial' | 'fashion' | 'portrait' | 'landscape' | 'street' + | 'fine-art' | 'conceptual' | 'surreal' | 'abstract' | 'minimalist' + | 'maximalist' | 'vintage' | 'retro' | 'noir' | 'gothic' | 'romantic' + | 'impressionist' | 'expressionist' | 'pop-art' | 'art-nouveau' | 'art-deco' + | 'cyberpunk' | 'steampunk' | 'fantasy' | 'sci-fi' | 'anime' | 'manga' + | 'comic-book' | 'illustration' | 'digital-art' | 'oil-painting' | 'watercolor' + | 'sketch' | 'pencil-drawing' | 'charcoal' | 'pastel' | '3d-render' +``` + +#### `FilmStock` + +```typescript +type FilmStock = | 'kodak-portra-160' | 'kodak-portra-400' | 'kodak-portra-800' + | 'kodak-ektar-100' | 'kodak-gold-200' | 'kodak-ultramax-400' | 'kodak-colorplus-200' + // Kodak Black & White + | 'kodak-tri-x-400' | 'kodak-tmax-100' | 'kodak-tmax-400' | 'kodak-tmax-3200' + // Kodak Slide + | 'kodak-ektachrome-e100' | 'kodachrome-64' | 'kodachrome-200' + // Kodak Cinema + | 'kodak-vision3-50d' | 'kodak-vision3-200t' | 'kodak-vision3-250d' | 'kodak-vision3-500t' + // Fujifilm + | 'fujifilm-pro-400h' | 'fujifilm-superia-400' | 'fujifilm-c200' + | 'fujifilm-velvia-50' | 'fujifilm-velvia-100' | 'fujifilm-provia-100f' + | 'fujifilm-acros-100' | 'fujifilm-neopan-400' | 'fujifilm-eterna-500t' + // Ilford + | 'ilford-hp5-plus' | 'ilford-delta-100' | 'ilford-delta-400' | 'ilford-delta-3200' + | 'ilford-fp4-plus' | 'ilford-pan-f-plus' | 'ilford-xp2-super' + // CineStill + | 'cinestill-50d' | 'cinestill-800t' | 'cinestill-400d' | 'cinestill-bwxx' + // Lomography + | 'lomography-100' | 'lomography-400' | 'lomography-800' + | 'lomochrome-purple' | 'lomochrome-metropolis' | 'lomochrome-turquoise' + // Instant + | 'polaroid-sx-70' | 'polaroid-600' | 'polaroid-i-type' | 'polaroid-spectra' + | 'instax-mini' | 'instax-wide' | 'instax-square' + // Vintage/Discontinued + | 'agfa-vista-400' | 'agfa-apx-100' | 'fomapan-100' | 'fomapan-400' + | 'bergger-pancro-400' | 'jch-streetpan-400' +``` + +#### `AspectRatio` + +```typescript +type AspectRatio = | '1:1' | '4:3' | '3:2' | '16:9' | '21:9' | '9:16' | '2:3' | '4:5' | '5:4' +``` + +#### `ColorPalette` + +```typescript +type ColorPalette = | 'warm' | 'cool' | 'neutral' | 'vibrant' | 'muted' | 'pastel' | 'neon' + | 'monochrome' | 'sepia' | 'desaturated' | 'high-contrast' | 'low-contrast' + | 'earthy' | 'oceanic' | 'forest' | 'sunset' | 'midnight' | 'golden' +``` + +#### `Mood` + +```typescript +type Mood = | 'serene' | 'peaceful' | 'melancholic' | 'dramatic' | 'tense' | 'mysterious' + | 'romantic' | 'nostalgic' | 'hopeful' | 'joyful' | 'energetic' | 'chaotic' + | 'ethereal' | 'dark' | 'light' | 'whimsical' | 'eerie' | 'epic' | 'intimate' +``` + +#### `VideoTransition` + +```typescript +type VideoTransition = | 'cut' | 'fade' | 'dissolve' | 'wipe' | 'morph' | 'match-cut' | 'jump-cut' + | 'cross-dissolve' | 'iris' | 'push' | 'slide' +``` + +#### `VideoPacing` + +```typescript +type VideoPacing = | 'slow' | 'medium' | 'fast' | 'variable' | 'building' | 'frenetic' | 'contemplative' +``` + +#### `MusicGenre` + +```typescript +type MusicGenre = | 'pop' | 'rock' | 'jazz' | 'classical' | 'electronic' | 'hip-hop' | 'r&b' + | 'country' | 'folk' | 'blues' | 'metal' | 'punk' | 'indie' | 'alternative' + | 'ambient' | 'lo-fi' | 'synthwave' | 'orchestral' | 'cinematic' | 'world' + | 'latin' | 'reggae' | 'soul' | 'funk' | 'disco' | 'house' | 'techno' | 'edm' +``` + +#### `Instrument` + +```typescript +type Instrument = | 'piano' | 'guitar' | 'acoustic-guitar' | 'electric-guitar' | 'bass' | 'drums' + | 'violin' | 'cello' | 'viola' | 'flute' | 'saxophone' | 'trumpet' | 'trombone' + | 'synthesizer' | 'organ' | 'harp' | 'percussion' | 'strings' | 'brass' | 'woodwinds' + | 'choir' | 'vocals' | 'beatbox' | 'turntables' | 'harmonica' | 'banjo' | 'ukulele' +``` + +#### `VocalStyle` + +```typescript +type VocalStyle = | 'male' | 'female' | 'duet' | 'choir' | 'a-cappella' | 'spoken-word' | 'rap' + | 'falsetto' | 'belting' | 'whisper' | 'growl' | 'melodic' | 'harmonized' +``` + +#### `Tempo` + +```typescript +type Tempo = | 'largo' | 'adagio' | 'andante' | 'moderato' | 'allegro' | 'vivace' | 'presto' + | number +``` + +### Interfaces + +#### `ImageSubject` + +| Property | Type | Description | +|----------|------|-------------| +| `main` | `string` | - | +| `details` | `string[]` | - | +| `expression` | `string` | - | +| `pose` | `string` | - | +| `action` | `string` | - | +| `clothing` | `string` | - | +| `accessories` | `string[]` | - | +| `age` | `string` | - | +| `ethnicity` | `string` | - | +| `gender` | `string` | - | +| `count` | `number | 'single' | 'couple' | 'group' | 'crowd'` | - | + +#### `ImageCamera` + +| Property | Type | Description | +|----------|------|-------------| +| `angle` | `CameraAngle` | - | +| `shot` | `ShotType` | - | +| `brand` | `CameraBrand` | - | +| `model` | `CameraModel` | - | +| `sensor` | `SensorFormat` | - | +| `lens` | `LensType` | - | +| `lensModel` | `LensModel` | - | +| `lensBrand` | `LensBrand` | - | +| `focalLength` | `string` | - | +| `focus` | `FocusType` | - | +| `aperture` | `string` | - | +| `bokeh` | `BokehStyle` | - | +| `focusDistance` | `string` | - | +| `iso` | `number` | - | +| `shutterSpeed` | `string` | - | +| `exposureCompensation` | `string` | - | +| `filmStock` | `FilmStock` | - | +| `filmFormat` | `FilmFormat` | - | +| `filter` | `FilterType | FilterType[]` | - | +| `whiteBalance` | `'daylight' | 'cloudy' | 'tungsten' | 'fluorescent' | 'flash' | 'custom'` | - | +| `colorProfile` | `string` | - | +| `pictureProfile` | `string` | - | + +#### `ImageLighting` + +| Property | Type | Description | +|----------|------|-------------| +| `type` | `LightingType | LightingType[]` | - | +| `time` | `TimeOfDay` | - | +| `weather` | `WeatherLighting` | - | +| `direction` | `'front' | 'side' | 'back' | 'top' | 'bottom' | 'three-quarter'` | - | +| `intensity` | `'soft' | 'medium' | 'hard' | 'dramatic'` | - | +| `color` | `string` | - | +| `sources` | `string[]` | - | + +#### `ImageComposition` + +| Property | Type | Description | +|----------|------|-------------| +| `ruleOfThirds` | `boolean` | - | +| `goldenRatio` | `boolean` | - | +| `symmetry` | `'none' | 'horizontal' | 'vertical' | 'radial'` | - | +| `leadingLines` | `boolean` | - | +| `framing` | `string` | - | +| `negativeSpace` | `boolean` | - | +| `layers` | `string[]` | - | +| `foreground` | `string` | - | +| `midground` | `string` | - | +| `background` | `string` | - | + +#### `ImageStyle` + +| Property | Type | Description | +|----------|------|-------------| +| `medium` | `ArtStyle | ArtStyle[]` | - | +| `artist` | `string | string[]` | - | +| `era` | `string` | - | +| `influence` | `string[]` | - | +| `quality` | `string[]` | - | +| `render` | `string` | - | + +#### `ImageColor` + +| Property | Type | Description | +|----------|------|-------------| +| `palette` | `ColorPalette | ColorPalette[]` | - | +| `primary` | `string[]` | - | +| `accent` | `string[]` | - | +| `grade` | `string` | - | +| `temperature` | `'warm' | 'neutral' | 'cool'` | - | +| `saturation` | `'desaturated' | 'natural' | 'vibrant' | 'hyper-saturated'` | - | +| `contrast` | `'low' | 'medium' | 'high'` | - | + +#### `ImageEnvironment` + +| Property | Type | Description | +|----------|------|-------------| +| `setting` | `string` | - | +| `location` | `string` | - | +| `terrain` | `string` | - | +| `architecture` | `string` | - | +| `props` | `string[]` | - | +| `atmosphere` | `string` | - | +| `season` | `'spring' | 'summer' | 'autumn' | 'winter'` | - | +| `era` | `string` | - | + +#### `ImageTechnical` + +| Property | Type | Description | +|----------|------|-------------| +| `aspectRatio` | `AspectRatio` | - | +| `resolution` | `string` | - | +| `quality` | `'draft' | 'standard' | 'high' | 'ultra' | 'masterpiece'` | - | +| `detail` | `'low' | 'medium' | 'high' | 'extreme'` | - | +| `noise` | `'none' | 'subtle' | 'filmic' | 'grainy'` | - | +| `sharpness` | `'soft' | 'natural' | 'sharp' | 'crisp'` | - | + +#### `BuiltImagePrompt` + +| Property | Type | Description | +|----------|------|-------------| +| `prompt` | `string` | - | +| `structure` | `unknown` | - | + +### Classes + +#### `ImagePromptBuilder` + +**Methods:** + +| Method | Description | +|--------|-------------| +| `subject(main: string | ImageSubject): this` | - | +| `subjectDetails(details: string[]): this` | - | +| `expression(expression: string): this` | - | +| `pose(pose: string): this` | - | +| `action(action: string): this` | - | +| `clothing(clothing: string): this` | - | +| `accessories(accessories: string[]): this` | - | +| `subjectCount(count: ImageSubject['count']): this` | - | +| `camera(settings: ImageCamera): this` | - | +| `angle(angle: CameraAngle): this` | - | +| `shot(shot: ShotType): this` | - | +| `lens(lens: LensType): this` | - | +| `focus(focus: FocusType): this` | - | +| `aperture(aperture: string): this` | - | +| `filmStock(filmStock: FilmStock): this` | - | +| `filmFormat(format: FilmFormat): this` | - | +| `cameraBrand(brand: CameraBrand): this` | - | +| `cameraModel(model: CameraModel): this` | - | +| `sensor(sensor: SensorFormat): this` | - | +| `lensModel(model: LensModel): this` | - | +| `lensBrand(brand: LensBrand): this` | - | +| `focalLength(length: string): this` | - | +| `bokeh(style: BokehStyle): this` | - | +| `filter(filter: FilterType | FilterType[]): this` | - | +| `iso(iso: number): this` | - | +| `shutterSpeed(speed: string): this` | - | +| `whiteBalance(wb: ImageCamera['whiteBalance']): this` | - | +| `colorProfile(profile: string): this` | - | +| `lighting(settings: ImageLighting): this` | - | +| `lightingType(type: LightingType | LightingType[]): this` | - | +| `timeOfDay(time: TimeOfDay): this` | - | +| `weather(weather: WeatherLighting): this` | - | +| `lightDirection(direction: ImageLighting['direction']): this` | - | +| `lightIntensity(intensity: ImageLighting['intensity']): this` | - | +| `composition(settings: ImageComposition): this` | - | +| `ruleOfThirds(): this` | - | +| `goldenRatio(): this` | - | +| `symmetry(type: ImageComposition['symmetry']): this` | - | +| `foreground(fg: string): this` | - | +| `midground(mg: string): this` | - | +| `background(bg: string): this` | - | +| `environment(setting: string | ImageEnvironment): this` | - | +| `location(location: string): this` | - | +| `props(props: string[]): this` | - | +| `atmosphere(atmosphere: string): this` | - | +| `season(season: ImageEnvironment['season']): this` | - | +| `style(settings: ImageStyle): this` | - | +| `medium(medium: ArtStyle | ArtStyle[]): this` | - | +| `artist(artist: string | string[]): this` | - | +| `influence(influences: string[]): this` | - | +| `color(settings: ImageColor): this` | - | +| `palette(palette: ColorPalette | ColorPalette[]): this` | - | +| `primaryColors(colors: string[]): this` | - | +| `accentColors(colors: string[]): this` | - | +| `colorGrade(grade: string): this` | - | +| `technical(settings: ImageTechnical): this` | - | +| `aspectRatio(ratio: AspectRatio): this` | - | +| `resolution(resolution: string): this` | - | +| `quality(quality: ImageTechnical['quality']): this` | - | +| `mood(mood: Mood | Mood[]): this` | - | +| `negative(items: string[]): this` | - | +| `custom(text: string): this` | - | +| `build(): BuiltImagePrompt` | - | +| `toString(): string` | - | +| `toJSON(): string` | - | +| `toYAML(): string` | - | +| `toMarkdown(): string` | - | +| `format(fmt: OutputFormat): string` | - | + +##### `subject()` + +```typescript +subject(main: string | ImageSubject): this +``` + +**Parameters:** + +- `main`: `string | ImageSubject` + +**Returns:** `this` + +##### `subjectDetails()` + +```typescript +subjectDetails(details: string[]): this +``` + +**Parameters:** + +- `details`: `string[]` + +**Returns:** `this` + +##### `expression()` + +```typescript +expression(expression: string): this +``` + +**Parameters:** + +- `expression`: `string` + +**Returns:** `this` + +##### `pose()` + +```typescript +pose(pose: string): this +``` + +**Parameters:** + +- `pose`: `string` + +**Returns:** `this` + +##### `action()` + +```typescript +action(action: string): this +``` + +**Parameters:** + +- `action`: `string` + +**Returns:** `this` + +##### `clothing()` + +```typescript +clothing(clothing: string): this +``` + +**Parameters:** + +- `clothing`: `string` + +**Returns:** `this` + +##### `accessories()` + +```typescript +accessories(accessories: string[]): this +``` + +**Parameters:** + +- `accessories`: `string[]` + +**Returns:** `this` + +##### `subjectCount()` + +```typescript +subjectCount(count: ImageSubject['count']): this +``` + +**Parameters:** + +- `count`: `ImageSubject['count']` + +**Returns:** `this` + +##### `camera()` + +```typescript +camera(settings: ImageCamera): this +``` + +**Parameters:** + +- `settings`: `ImageCamera` + +**Returns:** `this` + +##### `angle()` + +```typescript +angle(angle: CameraAngle): this +``` + +**Parameters:** + +- `angle`: `CameraAngle` + +**Returns:** `this` + +##### `shot()` + +```typescript +shot(shot: ShotType): this +``` + +**Parameters:** + +- `shot`: `ShotType` + +**Returns:** `this` + +##### `lens()` + +```typescript +lens(lens: LensType): this +``` + +**Parameters:** + +- `lens`: `LensType` + +**Returns:** `this` + +##### `focus()` + +```typescript +focus(focus: FocusType): this +``` + +**Parameters:** + +- `focus`: `FocusType` + +**Returns:** `this` + +##### `aperture()` + +```typescript +aperture(aperture: string): this +``` + +**Parameters:** + +- `aperture`: `string` + +**Returns:** `this` + +##### `filmStock()` + +```typescript +filmStock(filmStock: FilmStock): this +``` + +**Parameters:** + +- `filmStock`: `FilmStock` + +**Returns:** `this` + +##### `filmFormat()` + +```typescript +filmFormat(format: FilmFormat): this +``` + +**Parameters:** + +- `format`: `FilmFormat` + +**Returns:** `this` + +##### `cameraBrand()` + +```typescript +cameraBrand(brand: CameraBrand): this +``` + +**Parameters:** + +- `brand`: `CameraBrand` + +**Returns:** `this` + +##### `cameraModel()` + +```typescript +cameraModel(model: CameraModel): this +``` + +**Parameters:** + +- `model`: `CameraModel` + +**Returns:** `this` + +##### `sensor()` + +```typescript +sensor(sensor: SensorFormat): this +``` + +**Parameters:** + +- `sensor`: `SensorFormat` + +**Returns:** `this` + +##### `lensModel()` + +```typescript +lensModel(model: LensModel): this +``` + +**Parameters:** + +- `model`: `LensModel` + +**Returns:** `this` + +##### `lensBrand()` + +```typescript +lensBrand(brand: LensBrand): this +``` + +**Parameters:** + +- `brand`: `LensBrand` + +**Returns:** `this` + +##### `focalLength()` + +```typescript +focalLength(length: string): this +``` + +**Parameters:** + +- `length`: `string` + +**Returns:** `this` + +##### `bokeh()` + +```typescript +bokeh(style: BokehStyle): this +``` + +**Parameters:** + +- `style`: `BokehStyle` + +**Returns:** `this` + +##### `filter()` + +```typescript +filter(filter: FilterType | FilterType[]): this +``` + +**Parameters:** + +- `filter`: `FilterType | FilterType[]` + +**Returns:** `this` + +##### `iso()` + +```typescript +iso(iso: number): this +``` + +**Parameters:** + +- `iso`: `number` + +**Returns:** `this` + +##### `shutterSpeed()` + +```typescript +shutterSpeed(speed: string): this +``` + +**Parameters:** + +- `speed`: `string` + +**Returns:** `this` + +##### `whiteBalance()` + +```typescript +whiteBalance(wb: ImageCamera['whiteBalance']): this +``` + +**Parameters:** + +- `wb`: `ImageCamera['whiteBalance']` + +**Returns:** `this` + +##### `colorProfile()` + +```typescript +colorProfile(profile: string): this +``` + +**Parameters:** + +- `profile`: `string` + +**Returns:** `this` + +##### `lighting()` + +```typescript +lighting(settings: ImageLighting): this +``` + +**Parameters:** + +- `settings`: `ImageLighting` + +**Returns:** `this` + +##### `lightingType()` + +```typescript +lightingType(type: LightingType | LightingType[]): this +``` + +**Parameters:** + +- `type`: `LightingType | LightingType[]` + +**Returns:** `this` + +##### `timeOfDay()` + +```typescript +timeOfDay(time: TimeOfDay): this +``` + +**Parameters:** + +- `time`: `TimeOfDay` + +**Returns:** `this` + +##### `weather()` + +```typescript +weather(weather: WeatherLighting): this +``` + +**Parameters:** + +- `weather`: `WeatherLighting` + +**Returns:** `this` + +##### `lightDirection()` + +```typescript +lightDirection(direction: ImageLighting['direction']): this +``` + +**Parameters:** + +- `direction`: `ImageLighting['direction']` + +**Returns:** `this` + +##### `lightIntensity()` + +```typescript +lightIntensity(intensity: ImageLighting['intensity']): this +``` + +**Parameters:** + +- `intensity`: `ImageLighting['intensity']` + +**Returns:** `this` + +##### `composition()` + +```typescript +composition(settings: ImageComposition): this +``` + +**Parameters:** + +- `settings`: `ImageComposition` + +**Returns:** `this` + +##### `ruleOfThirds()` + +```typescript +ruleOfThirds(): this +``` + +**Returns:** `this` + +##### `goldenRatio()` + +```typescript +goldenRatio(): this +``` + +**Returns:** `this` + +##### `symmetry()` + +```typescript +symmetry(type: ImageComposition['symmetry']): this +``` + +**Parameters:** + +- `type`: `ImageComposition['symmetry']` + +**Returns:** `this` + +##### `foreground()` + +```typescript +foreground(fg: string): this +``` + +**Parameters:** + +- `fg`: `string` + +**Returns:** `this` + +##### `midground()` + +```typescript +midground(mg: string): this +``` + +**Parameters:** + +- `mg`: `string` + +**Returns:** `this` + +##### `background()` + +```typescript +background(bg: string): this +``` + +**Parameters:** + +- `bg`: `string` + +**Returns:** `this` + +##### `environment()` + +```typescript +environment(setting: string | ImageEnvironment): this +``` + +**Parameters:** + +- `setting`: `string | ImageEnvironment` + +**Returns:** `this` + +##### `location()` + +```typescript +location(location: string): this +``` + +**Parameters:** + +- `location`: `string` + +**Returns:** `this` + +##### `props()` + +```typescript +props(props: string[]): this +``` + +**Parameters:** + +- `props`: `string[]` + +**Returns:** `this` + +##### `atmosphere()` + +```typescript +atmosphere(atmosphere: string): this +``` + +**Parameters:** + +- `atmosphere`: `string` + +**Returns:** `this` + +##### `season()` + +```typescript +season(season: ImageEnvironment['season']): this +``` + +**Parameters:** + +- `season`: `ImageEnvironment['season']` + +**Returns:** `this` + +##### `style()` + +```typescript +style(settings: ImageStyle): this +``` + +**Parameters:** + +- `settings`: `ImageStyle` + +**Returns:** `this` + +##### `medium()` + +```typescript +medium(medium: ArtStyle | ArtStyle[]): this +``` + +**Parameters:** + +- `medium`: `ArtStyle | ArtStyle[]` + +**Returns:** `this` + +##### `artist()` + +```typescript +artist(artist: string | string[]): this +``` + +**Parameters:** + +- `artist`: `string | string[]` + +**Returns:** `this` + +##### `influence()` + +```typescript +influence(influences: string[]): this +``` + +**Parameters:** + +- `influences`: `string[]` + +**Returns:** `this` + +##### `color()` + +```typescript +color(settings: ImageColor): this +``` + +**Parameters:** + +- `settings`: `ImageColor` + +**Returns:** `this` + +##### `palette()` + +```typescript +palette(palette: ColorPalette | ColorPalette[]): this +``` + +**Parameters:** + +- `palette`: `ColorPalette | ColorPalette[]` + +**Returns:** `this` + +##### `primaryColors()` + +```typescript +primaryColors(colors: string[]): this +``` + +**Parameters:** + +- `colors`: `string[]` + +**Returns:** `this` + +##### `accentColors()` + +```typescript +accentColors(colors: string[]): this +``` + +**Parameters:** + +- `colors`: `string[]` + +**Returns:** `this` + +##### `colorGrade()` + +```typescript +colorGrade(grade: string): this +``` + +**Parameters:** + +- `grade`: `string` + +**Returns:** `this` + +##### `technical()` + +```typescript +technical(settings: ImageTechnical): this +``` + +**Parameters:** + +- `settings`: `ImageTechnical` + +**Returns:** `this` + +##### `aspectRatio()` + +```typescript +aspectRatio(ratio: AspectRatio): this +``` + +**Parameters:** + +- `ratio`: `AspectRatio` + +**Returns:** `this` + +##### `resolution()` + +```typescript +resolution(resolution: string): this +``` + +**Parameters:** + +- `resolution`: `string` + +**Returns:** `this` + +##### `quality()` + +```typescript +quality(quality: ImageTechnical['quality']): this +``` + +**Parameters:** + +- `quality`: `ImageTechnical['quality']` + +**Returns:** `this` + +##### `mood()` + +```typescript +mood(mood: Mood | Mood[]): this +``` + +**Parameters:** + +- `mood`: `Mood | Mood[]` + +**Returns:** `this` + +##### `negative()` + +```typescript +negative(items: string[]): this +``` + +**Parameters:** + +- `items`: `string[]` + +**Returns:** `this` + +##### `custom()` + +```typescript +custom(text: string): this +``` + +**Parameters:** + +- `text`: `string` + +**Returns:** `this` + +##### `build()` + +```typescript +build(): BuiltImagePrompt +``` + +**Returns:** `BuiltImagePrompt` + +##### `toString()` + +```typescript +toString(): string +``` + +**Returns:** `string` + +##### `toJSON()` + +```typescript +toJSON(): string +``` + +**Returns:** `string` + +##### `toYAML()` + +```typescript +toYAML(): string +``` + +**Returns:** `string` + +##### `toMarkdown()` + +```typescript +toMarkdown(): string +``` + +**Returns:** `string` + +##### `format()` + +```typescript +format(fmt: OutputFormat): string +``` + +**Parameters:** + +- `fmt`: `OutputFormat` + +**Returns:** `string` + +### Functions + +#### `image()` + +Create a new image prompt builder + +```typescript +image(): ImagePromptBuilder +``` + +**Returns:** `ImagePromptBuilder` + +--- + +## builder/video + +Video Prompt Builder - Comprehensive video generation prompt builder + +Based on OpenAI Sora, Runway, and other video generation best practices. + +@example +```ts +import { video } from 'prompts.chat/builder'; + +const prompt = video() + .scene("A samurai walks through a bamboo forest") + .camera({ movement: "tracking", angle: "low" }) + .lighting({ time: "golden-hour", type: "natural" }) + .duration(5) + .build(); +``` + +### Interfaces + +#### `VideoScene` + +| Property | Type | Description | +|----------|------|-------------| +| `description` | `string` | - | +| `setting` | `string` | - | +| `timeOfDay` | `TimeOfDay` | - | +| `weather` | `WeatherLighting` | - | +| `atmosphere` | `string` | - | + +#### `VideoSubject` + +| Property | Type | Description | +|----------|------|-------------| +| `main` | `string` | - | +| `appearance` | `string` | - | +| `clothing` | `string` | - | +| `age` | `string` | - | +| `gender` | `string` | - | +| `count` | `number | 'single' | 'couple' | 'group' | 'crowd'` | - | + +#### `VideoCamera` + +| Property | Type | Description | +|----------|------|-------------| +| `shot` | `ShotType` | - | +| `angle` | `CameraAngle` | - | +| `brand` | `CameraBrand` | - | +| `model` | `CameraModel` | - | +| `sensor` | `SensorFormat` | - | +| `lens` | `LensType` | - | +| `lensModel` | `LensModel` | - | +| `lensBrand` | `LensBrand` | - | +| `focalLength` | `string` | - | +| `anamorphic` | `boolean` | - | +| `anamorphicRatio` | `'1.33x' | '1.5x' | '1.8x' | '2x'` | - | +| `focus` | `'shallow' | 'deep' | 'rack-focus' | 'pull-focus' | 'split-diopter'` | - | +| `aperture` | `string` | - | +| `bokeh` | `BokehStyle` | - | +| `movement` | `CameraMovement` | - | +| `movementSpeed` | `'slow' | 'medium' | 'fast'` | - | +| `movementDirection` | `'left' | 'right' | 'forward' | 'backward' | 'up' | 'down' | 'arc-left' | 'arc-right'` | - | +| `rig` | `CameraRig` | - | +| `gimbal` | `GimbalModel` | - | +| `platform` | `'handheld' | 'steadicam' | 'tripod' | 'drone' | 'crane' | 'gimbal' | 'slider' | 'dolly' | 'technocrane' | 'russian-arm' | 'fpv-drone'` | - | +| `shutterAngle` | `number` | - | +| `frameRate` | `24 | 25 | 30 | 48 | 60 | 120 | 240` | - | +| `slowMotion` | `boolean` | - | +| `filter` | `FilterType | FilterType[]` | - | +| `filmStock` | `FilmStock` | - | +| `filmGrain` | `'none' | 'subtle' | 'moderate' | 'heavy'` | - | +| `halation` | `boolean` | - | + +#### `VideoLighting` + +| Property | Type | Description | +|----------|------|-------------| +| `type` | `LightingType | LightingType[]` | - | +| `time` | `TimeOfDay` | - | +| `weather` | `WeatherLighting` | - | +| `direction` | `'front' | 'side' | 'back' | 'top' | 'three-quarter'` | - | +| `intensity` | `'soft' | 'medium' | 'hard' | 'dramatic'` | - | +| `sources` | `string[]` | - | +| `color` | `string` | - | + +#### `VideoAction` + +| Property | Type | Description | +|----------|------|-------------| +| `beat` | `number` | - | +| `action` | `string` | - | +| `duration` | `number` | - | +| `timing` | `'start' | 'middle' | 'end'` | - | + +#### `VideoMotion` + +| Property | Type | Description | +|----------|------|-------------| +| `subject` | `string` | - | +| `type` | `'walk' | 'run' | 'gesture' | 'turn' | 'look' | 'reach' | 'sit' | 'stand' | 'custom'` | - | +| `direction` | `'left' | 'right' | 'forward' | 'backward' | 'up' | 'down'` | - | +| `speed` | `'slow' | 'normal' | 'fast'` | - | +| `beats` | `string[]` | - | + +#### `VideoStyle` + +| Property | Type | Description | +|----------|------|-------------| +| `format` | `string` | - | +| `era` | `string` | - | +| `filmStock` | `string` | - | +| `look` | `ArtStyle | ArtStyle[]` | - | +| `grade` | `string` | - | +| `reference` | `string[]` | - | + +#### `VideoColor` + +| Property | Type | Description | +|----------|------|-------------| +| `palette` | `ColorPalette | ColorPalette[]` | - | +| `anchors` | `string[]` | - | +| `temperature` | `'warm' | 'neutral' | 'cool'` | - | +| `grade` | `string` | - | + +#### `VideoAudio` + +| Property | Type | Description | +|----------|------|-------------| +| `diegetic` | `string[]` | - | +| `ambient` | `string` | - | +| `dialogue` | `string` | - | +| `music` | `string` | - | +| `soundEffects` | `string[]` | - | +| `mix` | `string` | - | + +#### `VideoTechnical` + +| Property | Type | Description | +|----------|------|-------------| +| `duration` | `number` | - | +| `resolution` | `'480p' | '720p' | '1080p' | '4K'` | - | +| `fps` | `24 | 30 | 60` | - | +| `aspectRatio` | `'16:9' | '9:16' | '1:1' | '4:3' | '21:9'` | - | +| `shutterAngle` | `number` | - | + +#### `VideoShot` + +| Property | Type | Description | +|----------|------|-------------| +| `timestamp` | `string` | - | +| `name` | `string` | - | +| `camera` | `VideoCamera` | - | +| `action` | `string` | - | +| `purpose` | `string` | - | + +#### `BuiltVideoPrompt` + +| Property | Type | Description | +|----------|------|-------------| +| `prompt` | `string` | - | +| `structure` | `unknown` | - | + +### Classes + +#### `VideoPromptBuilder` + +**Methods:** + +| Method | Description | +|--------|-------------| +| `scene(description: string | VideoScene): this` | - | +| `setting(setting: string): this` | - | +| `subject(main: string | VideoSubject): this` | - | +| `appearance(appearance: string): this` | - | +| `clothing(clothing: string): this` | - | +| `camera(settings: VideoCamera): this` | - | +| `shot(shot: ShotType): this` | - | +| `angle(angle: CameraAngle): this` | - | +| `movement(movement: CameraMovement): this` | - | +| `lens(lens: LensType): this` | - | +| `platform(platform: VideoCamera['platform']): this` | - | +| `cameraSpeed(speed: VideoCamera['movementSpeed']): this` | - | +| `movementDirection(direction: VideoCamera['movementDirection']): this` | - | +| `rig(rig: CameraRig): this` | - | +| `gimbal(gimbal: GimbalModel): this` | - | +| `cameraBrand(brand: CameraBrand): this` | - | +| `cameraModel(model: CameraModel): this` | - | +| `sensor(sensor: SensorFormat): this` | - | +| `lensModel(model: LensModel): this` | - | +| `lensBrand(brand: LensBrand): this` | - | +| `focalLength(length: string): this` | - | +| `anamorphic(ratio?: VideoCamera['anamorphicRatio']): this` | - | +| `aperture(aperture: string): this` | - | +| `frameRate(fps: VideoCamera['frameRate']): this` | - | +| `slowMotion(enabled?: any): this` | - | +| `shutterAngle(angle: number): this` | - | +| `filter(filter: FilterType | FilterType[]): this` | - | +| `filmStock(stock: FilmStock): this` | - | +| `filmGrain(grain: VideoCamera['filmGrain']): this` | - | +| `halation(enabled?: any): this` | - | +| `lighting(settings: VideoLighting): this` | - | +| `lightingType(type: LightingType | LightingType[]): this` | - | +| `timeOfDay(time: TimeOfDay): this` | - | +| `weather(weather: WeatherLighting): this` | - | +| `action(action: string, options?: Partial>): this` | - | +| `actions(actions: string[]): this` | - | +| `motion(settings: VideoMotion): this` | - | +| `motionBeats(beats: string[]): this` | - | +| `style(settings: VideoStyle): this` | - | +| `format(format: string): this` | - | +| `era(era: string): this` | - | +| `styleFilmStock(stock: string): this` | - | +| `look(look: ArtStyle | ArtStyle[]): this` | - | +| `reference(references: string[]): this` | - | +| `color(settings: VideoColor): this` | - | +| `palette(palette: ColorPalette | ColorPalette[]): this` | - | +| `colorAnchors(anchors: string[]): this` | - | +| `colorGrade(grade: string): this` | - | +| `audio(settings: VideoAudio): this` | - | +| `dialogue(dialogue: string): this` | - | +| `ambient(ambient: string): this` | - | +| `diegetic(sounds: string[]): this` | - | +| `soundEffects(effects: string[]): this` | - | +| `music(music: string): this` | - | +| `technical(settings: VideoTechnical): this` | - | +| `duration(seconds: number): this` | - | +| `resolution(res: VideoTechnical['resolution']): this` | - | +| `fps(fps: VideoTechnical['fps']): this` | - | +| `aspectRatio(ratio: VideoTechnical['aspectRatio']): this` | - | +| `addShot(shot: VideoShot): this` | - | +| `shotList(shots: VideoShot[]): this` | - | +| `mood(mood: Mood | Mood[]): this` | - | +| `pacing(pacing: VideoPacing): this` | - | +| `transition(transition: VideoTransition): this` | - | +| `transitions(transitions: VideoTransition[]): this` | - | +| `custom(text: string): this` | - | +| `build(): BuiltVideoPrompt` | - | +| `toString(): string` | - | +| `toJSON(): string` | - | +| `toYAML(): string` | - | +| `toMarkdown(): string` | - | +| `outputFormat(fmt: OutputFormat): string` | - | + +##### `scene()` + +```typescript +scene(description: string | VideoScene): this +``` + +**Parameters:** + +- `description`: `string | VideoScene` + +**Returns:** `this` + +##### `setting()` + +```typescript +setting(setting: string): this +``` + +**Parameters:** + +- `setting`: `string` + +**Returns:** `this` + +##### `subject()` + +```typescript +subject(main: string | VideoSubject): this +``` + +**Parameters:** + +- `main`: `string | VideoSubject` + +**Returns:** `this` + +##### `appearance()` + +```typescript +appearance(appearance: string): this +``` + +**Parameters:** + +- `appearance`: `string` + +**Returns:** `this` + +##### `clothing()` + +```typescript +clothing(clothing: string): this +``` + +**Parameters:** + +- `clothing`: `string` + +**Returns:** `this` + +##### `camera()` + +```typescript +camera(settings: VideoCamera): this +``` + +**Parameters:** + +- `settings`: `VideoCamera` + +**Returns:** `this` + +##### `shot()` + +```typescript +shot(shot: ShotType): this +``` + +**Parameters:** + +- `shot`: `ShotType` + +**Returns:** `this` + +##### `angle()` + +```typescript +angle(angle: CameraAngle): this +``` + +**Parameters:** + +- `angle`: `CameraAngle` + +**Returns:** `this` + +##### `movement()` + +```typescript +movement(movement: CameraMovement): this +``` + +**Parameters:** + +- `movement`: `CameraMovement` + +**Returns:** `this` + +##### `lens()` + +```typescript +lens(lens: LensType): this +``` + +**Parameters:** + +- `lens`: `LensType` + +**Returns:** `this` + +##### `platform()` + +```typescript +platform(platform: VideoCamera['platform']): this +``` + +**Parameters:** + +- `platform`: `VideoCamera['platform']` + +**Returns:** `this` + +##### `cameraSpeed()` + +```typescript +cameraSpeed(speed: VideoCamera['movementSpeed']): this +``` + +**Parameters:** + +- `speed`: `VideoCamera['movementSpeed']` + +**Returns:** `this` + +##### `movementDirection()` + +```typescript +movementDirection(direction: VideoCamera['movementDirection']): this +``` + +**Parameters:** + +- `direction`: `VideoCamera['movementDirection']` + +**Returns:** `this` + +##### `rig()` + +```typescript +rig(rig: CameraRig): this +``` + +**Parameters:** + +- `rig`: `CameraRig` + +**Returns:** `this` + +##### `gimbal()` + +```typescript +gimbal(gimbal: GimbalModel): this +``` + +**Parameters:** + +- `gimbal`: `GimbalModel` + +**Returns:** `this` + +##### `cameraBrand()` + +```typescript +cameraBrand(brand: CameraBrand): this +``` + +**Parameters:** + +- `brand`: `CameraBrand` + +**Returns:** `this` + +##### `cameraModel()` + +```typescript +cameraModel(model: CameraModel): this +``` + +**Parameters:** + +- `model`: `CameraModel` + +**Returns:** `this` + +##### `sensor()` + +```typescript +sensor(sensor: SensorFormat): this +``` + +**Parameters:** + +- `sensor`: `SensorFormat` + +**Returns:** `this` + +##### `lensModel()` + +```typescript +lensModel(model: LensModel): this +``` + +**Parameters:** + +- `model`: `LensModel` + +**Returns:** `this` + +##### `lensBrand()` + +```typescript +lensBrand(brand: LensBrand): this +``` + +**Parameters:** + +- `brand`: `LensBrand` + +**Returns:** `this` + +##### `focalLength()` + +```typescript +focalLength(length: string): this +``` + +**Parameters:** + +- `length`: `string` + +**Returns:** `this` + +##### `anamorphic()` + +```typescript +anamorphic(ratio?: VideoCamera['anamorphicRatio']): this +``` + +**Parameters:** + +- `ratio`: `VideoCamera['anamorphicRatio']` (optional) + +**Returns:** `this` + +##### `aperture()` + +```typescript +aperture(aperture: string): this +``` + +**Parameters:** + +- `aperture`: `string` + +**Returns:** `this` + +##### `frameRate()` + +```typescript +frameRate(fps: VideoCamera['frameRate']): this +``` + +**Parameters:** + +- `fps`: `VideoCamera['frameRate']` + +**Returns:** `this` + +##### `slowMotion()` + +```typescript +slowMotion(enabled?: any): this +``` + +**Parameters:** + +- `enabled`: `any` (optional) = `true` + +**Returns:** `this` + +##### `shutterAngle()` + +```typescript +shutterAngle(angle: number): this +``` + +**Parameters:** + +- `angle`: `number` + +**Returns:** `this` + +##### `filter()` + +```typescript +filter(filter: FilterType | FilterType[]): this +``` + +**Parameters:** + +- `filter`: `FilterType | FilterType[]` + +**Returns:** `this` + +##### `filmStock()` + +```typescript +filmStock(stock: FilmStock): this +``` + +**Parameters:** + +- `stock`: `FilmStock` + +**Returns:** `this` + +##### `filmGrain()` + +```typescript +filmGrain(grain: VideoCamera['filmGrain']): this +``` + +**Parameters:** + +- `grain`: `VideoCamera['filmGrain']` + +**Returns:** `this` + +##### `halation()` + +```typescript +halation(enabled?: any): this +``` + +**Parameters:** + +- `enabled`: `any` (optional) = `true` + +**Returns:** `this` + +##### `lighting()` + +```typescript +lighting(settings: VideoLighting): this +``` + +**Parameters:** + +- `settings`: `VideoLighting` + +**Returns:** `this` + +##### `lightingType()` + +```typescript +lightingType(type: LightingType | LightingType[]): this +``` + +**Parameters:** + +- `type`: `LightingType | LightingType[]` + +**Returns:** `this` + +##### `timeOfDay()` + +```typescript +timeOfDay(time: TimeOfDay): this +``` + +**Parameters:** + +- `time`: `TimeOfDay` + +**Returns:** `this` + +##### `weather()` + +```typescript +weather(weather: WeatherLighting): this +``` + +**Parameters:** + +- `weather`: `WeatherLighting` + +**Returns:** `this` + +##### `action()` + +```typescript +action(action: string, options?: Partial>): this +``` + +**Parameters:** + +- `action`: `string` +- `options`: `Partial>` (optional) = `{}` + +**Returns:** `this` + +##### `actions()` + +```typescript +actions(actions: string[]): this +``` + +**Parameters:** + +- `actions`: `string[]` + +**Returns:** `this` + +##### `motion()` + +```typescript +motion(settings: VideoMotion): this +``` + +**Parameters:** + +- `settings`: `VideoMotion` + +**Returns:** `this` + +##### `motionBeats()` + +```typescript +motionBeats(beats: string[]): this +``` + +**Parameters:** + +- `beats`: `string[]` + +**Returns:** `this` + +##### `style()` + +```typescript +style(settings: VideoStyle): this +``` + +**Parameters:** + +- `settings`: `VideoStyle` + +**Returns:** `this` + +##### `format()` + +```typescript +format(format: string): this +``` + +**Parameters:** + +- `format`: `string` + +**Returns:** `this` + +##### `era()` + +```typescript +era(era: string): this +``` + +**Parameters:** + +- `era`: `string` + +**Returns:** `this` + +##### `styleFilmStock()` + +```typescript +styleFilmStock(stock: string): this +``` + +**Parameters:** + +- `stock`: `string` + +**Returns:** `this` + +##### `look()` + +```typescript +look(look: ArtStyle | ArtStyle[]): this +``` + +**Parameters:** + +- `look`: `ArtStyle | ArtStyle[]` + +**Returns:** `this` + +##### `reference()` + +```typescript +reference(references: string[]): this +``` + +**Parameters:** + +- `references`: `string[]` + +**Returns:** `this` + +##### `color()` + +```typescript +color(settings: VideoColor): this +``` + +**Parameters:** + +- `settings`: `VideoColor` + +**Returns:** `this` + +##### `palette()` + +```typescript +palette(palette: ColorPalette | ColorPalette[]): this +``` + +**Parameters:** + +- `palette`: `ColorPalette | ColorPalette[]` + +**Returns:** `this` + +##### `colorAnchors()` + +```typescript +colorAnchors(anchors: string[]): this +``` + +**Parameters:** + +- `anchors`: `string[]` + +**Returns:** `this` + +##### `colorGrade()` + +```typescript +colorGrade(grade: string): this +``` + +**Parameters:** + +- `grade`: `string` + +**Returns:** `this` + +##### `audio()` + +```typescript +audio(settings: VideoAudio): this +``` + +**Parameters:** + +- `settings`: `VideoAudio` + +**Returns:** `this` + +##### `dialogue()` + +```typescript +dialogue(dialogue: string): this +``` + +**Parameters:** + +- `dialogue`: `string` + +**Returns:** `this` + +##### `ambient()` + +```typescript +ambient(ambient: string): this +``` + +**Parameters:** + +- `ambient`: `string` + +**Returns:** `this` + +##### `diegetic()` + +```typescript +diegetic(sounds: string[]): this +``` + +**Parameters:** + +- `sounds`: `string[]` + +**Returns:** `this` + +##### `soundEffects()` + +```typescript +soundEffects(effects: string[]): this +``` + +**Parameters:** + +- `effects`: `string[]` + +**Returns:** `this` + +##### `music()` + +```typescript +music(music: string): this +``` + +**Parameters:** + +- `music`: `string` + +**Returns:** `this` + +##### `technical()` + +```typescript +technical(settings: VideoTechnical): this +``` + +**Parameters:** + +- `settings`: `VideoTechnical` + +**Returns:** `this` + +##### `duration()` + +```typescript +duration(seconds: number): this +``` + +**Parameters:** + +- `seconds`: `number` + +**Returns:** `this` + +##### `resolution()` + +```typescript +resolution(res: VideoTechnical['resolution']): this +``` + +**Parameters:** + +- `res`: `VideoTechnical['resolution']` + +**Returns:** `this` + +##### `fps()` + +```typescript +fps(fps: VideoTechnical['fps']): this +``` + +**Parameters:** + +- `fps`: `VideoTechnical['fps']` + +**Returns:** `this` + +##### `aspectRatio()` + +```typescript +aspectRatio(ratio: VideoTechnical['aspectRatio']): this +``` + +**Parameters:** + +- `ratio`: `VideoTechnical['aspectRatio']` + +**Returns:** `this` + +##### `addShot()` + +```typescript +addShot(shot: VideoShot): this +``` + +**Parameters:** + +- `shot`: `VideoShot` + +**Returns:** `this` + +##### `shotList()` + +```typescript +shotList(shots: VideoShot[]): this +``` + +**Parameters:** + +- `shots`: `VideoShot[]` + +**Returns:** `this` + +##### `mood()` + +```typescript +mood(mood: Mood | Mood[]): this +``` + +**Parameters:** + +- `mood`: `Mood | Mood[]` + +**Returns:** `this` + +##### `pacing()` + +```typescript +pacing(pacing: VideoPacing): this +``` + +**Parameters:** + +- `pacing`: `VideoPacing` + +**Returns:** `this` + +##### `transition()` + +```typescript +transition(transition: VideoTransition): this +``` + +**Parameters:** + +- `transition`: `VideoTransition` + +**Returns:** `this` + +##### `transitions()` + +```typescript +transitions(transitions: VideoTransition[]): this +``` + +**Parameters:** + +- `transitions`: `VideoTransition[]` + +**Returns:** `this` + +##### `custom()` + +```typescript +custom(text: string): this +``` + +**Parameters:** + +- `text`: `string` + +**Returns:** `this` + +##### `build()` + +```typescript +build(): BuiltVideoPrompt +``` + +**Returns:** `BuiltVideoPrompt` + +##### `toString()` + +```typescript +toString(): string +``` + +**Returns:** `string` + +##### `toJSON()` + +```typescript +toJSON(): string +``` + +**Returns:** `string` + +##### `toYAML()` + +```typescript +toYAML(): string +``` + +**Returns:** `string` + +##### `toMarkdown()` + +```typescript +toMarkdown(): string +``` + +**Returns:** `string` + +##### `outputFormat()` + +```typescript +outputFormat(fmt: OutputFormat): string +``` + +**Parameters:** + +- `fmt`: `OutputFormat` + +**Returns:** `string` + +### Functions + +#### `video()` + +Create a new video prompt builder + +```typescript +video(): VideoPromptBuilder +``` + +**Returns:** `VideoPromptBuilder` + +--- + +## builder/audio + +Audio/Music Prompt Builder - Comprehensive music generation prompt builder + +Based on Suno, Udio, and other music generation best practices. + +@example +```ts +import { audio } from 'prompts.chat/builder'; + +const prompt = audio() + .genre("synthwave") + .mood("nostalgic", "dreamy") + .tempo(110) + .instruments(["synthesizer", "drums", "bass"]) + .structure({ intro: 8, verse: 16, chorus: 16 }) + .build(); +``` + +### Types + +#### `MusicGenre` + +```typescript +type MusicGenre = | 'pop' | 'rock' | 'jazz' | 'classical' | 'electronic' | 'hip-hop' | 'r&b' + | 'country' | 'folk' | 'blues' | 'metal' | 'punk' | 'indie' | 'alternative' + | 'ambient' | 'lo-fi' | 'synthwave' | 'orchestral' | 'cinematic' | 'world' + | 'latin' | 'reggae' | 'soul' | 'funk' | 'disco' | 'house' | 'techno' | 'edm' + | 'trap' | 'drill' | 'k-pop' | 'j-pop' | 'bossa-nova' | 'gospel' | 'grunge' + | 'shoegaze' | 'post-rock' | 'prog-rock' | 'psychedelic' | 'chillwave' + | 'vaporwave' | 'drum-and-bass' | 'dubstep' | 'trance' | 'hardcore' +``` + +#### `Instrument` + +```typescript +type Instrument = | 'piano' | 'guitar' | 'acoustic-guitar' | 'electric-guitar' | 'bass' | 'drums' + | 'violin' | 'cello' | 'viola' | 'flute' | 'saxophone' | 'trumpet' | 'trombone' + | 'synthesizer' | 'organ' | 'harp' | 'percussion' | 'strings' | 'brass' | 'woodwinds' + | 'choir' | 'vocals' | 'beatbox' | 'turntables' | 'harmonica' | 'banjo' | 'ukulele' + | 'mandolin' | 'accordion' | 'marimba' | 'vibraphone' | 'xylophone' | 'timpani' + | 'congas' | 'bongos' | 'djembe' | 'tabla' | 'sitar' | 'erhu' | 'koto' + | '808' | '909' | 'moog' | 'rhodes' | 'wurlitzer' | 'mellotron' | 'theremin' +``` + +#### `VocalStyle` + +```typescript +type VocalStyle = | 'male' | 'female' | 'duet' | 'choir' | 'a-cappella' | 'spoken-word' | 'rap' + | 'falsetto' | 'belting' | 'whisper' | 'growl' | 'melodic' | 'harmonized' + | 'auto-tuned' | 'operatic' | 'soul' | 'breathy' | 'nasal' | 'raspy' | 'clear' +``` + +#### `VocalLanguage` + +```typescript +type VocalLanguage = | 'english' | 'spanish' | 'french' | 'german' | 'italian' | 'portuguese' + | 'japanese' | 'korean' | 'chinese' | 'arabic' | 'hindi' | 'russian' | 'turkish' + | 'instrumental' +``` + +#### `TempoMarking` + +```typescript +type TempoMarking = | 'largo' | 'adagio' | 'andante' | 'moderato' | 'allegro' | 'vivace' | 'presto' +``` + +#### `TimeSignature` + +```typescript +type TimeSignature = '4/4' | '3/4' | '6/8' | '2/4' | '5/4' | '7/8' | '12/8' +``` + +#### `MusicalKey` + +```typescript +type MusicalKey = | 'C' | 'C#' | 'Db' | 'D' | 'D#' | 'Eb' | 'E' | 'F' | 'F#' | 'Gb' + | 'G' | 'G#' | 'Ab' | 'A' | 'A#' | 'Bb' | 'B' + | 'Cm' | 'C#m' | 'Dm' | 'D#m' | 'Ebm' | 'Em' | 'Fm' | 'F#m' + | 'Gm' | 'G#m' | 'Am' | 'A#m' | 'Bbm' | 'Bm' +``` + +#### `SongSection` + +```typescript +type SongSection = | 'intro' | 'verse' | 'pre-chorus' | 'chorus' | 'bridge' | 'breakdown' + | 'drop' | 'build-up' | 'outro' | 'solo' | 'interlude' | 'hook' +``` + +#### `ProductionStyle` + +```typescript +type ProductionStyle = | 'lo-fi' | 'hi-fi' | 'vintage' | 'modern' | 'polished' | 'raw' | 'organic' + | 'synthetic' | 'acoustic' | 'electric' | 'hybrid' | 'minimalist' | 'maximalist' + | 'layered' | 'sparse' | 'dense' | 'atmospheric' | 'punchy' | 'warm' | 'bright' +``` + +#### `Era` + +```typescript +type Era = | '1950s' | '1960s' | '1970s' | '1980s' | '1990s' | '2000s' | '2010s' | '2020s' + | 'retro' | 'vintage' | 'classic' | 'modern' | 'futuristic' +``` + +### Interfaces + +#### `AudioGenre` + +| Property | Type | Description | +|----------|------|-------------| +| `primary` | `MusicGenre` | - | +| `secondary` | `MusicGenre[]` | - | +| `subgenre` | `string` | - | +| `fusion` | `string[]` | - | + +#### `AudioMood` + +| Property | Type | Description | +|----------|------|-------------| +| `primary` | `Mood | string` | - | +| `secondary` | `(Mood | string)[]` | - | +| `energy` | `'low' | 'medium' | 'high' | 'building' | 'fluctuating'` | - | +| `emotion` | `string` | - | + +#### `AudioTempo` + +| Property | Type | Description | +|----------|------|-------------| +| `bpm` | `number` | - | +| `marking` | `TempoMarking` | - | +| `feel` | `'steady' | 'swung' | 'shuffled' | 'syncopated' | 'rubato' | 'driving'` | - | +| `variation` | `boolean` | - | + +#### `AudioVocals` + +| Property | Type | Description | +|----------|------|-------------| +| `style` | `VocalStyle | VocalStyle[]` | - | +| `language` | `VocalLanguage` | - | +| `lyrics` | `string` | - | +| `theme` | `string` | - | +| `delivery` | `string` | - | +| `harmonies` | `boolean` | - | +| `adlibs` | `boolean` | - | + +#### `AudioInstrumentation` + +| Property | Type | Description | +|----------|------|-------------| +| `lead` | `Instrument | Instrument[]` | - | +| `rhythm` | `Instrument | Instrument[]` | - | +| `bass` | `Instrument` | - | +| `percussion` | `Instrument | Instrument[]` | - | +| `pads` | `Instrument | Instrument[]` | - | +| `effects` | `string[]` | - | +| `featured` | `Instrument` | - | + +#### `AudioStructure` + +| Property | Type | Description | +|----------|------|-------------| +| `sections` | `unknown` | - | +| `intro` | `number` | - | +| `verse` | `number` | - | +| `chorus` | `number` | - | +| `bridge` | `number` | - | +| `outro` | `number` | - | +| `form` | `string` | - | +| `duration` | `number` | - | + +#### `AudioProduction` + +| Property | Type | Description | +|----------|------|-------------| +| `style` | `ProductionStyle | ProductionStyle[]` | - | +| `era` | `Era` | - | +| `reference` | `string[]` | - | +| `mix` | `string` | - | +| `mastering` | `string` | - | +| `effects` | `string[]` | - | +| `texture` | `string` | - | + +#### `AudioTechnical` + +| Property | Type | Description | +|----------|------|-------------| +| `key` | `MusicalKey` | - | +| `timeSignature` | `TimeSignature` | - | +| `duration` | `number` | - | +| `format` | `'song' | 'instrumental' | 'jingle' | 'loop' | 'soundtrack'` | - | + +#### `BuiltAudioPrompt` + +| Property | Type | Description | +|----------|------|-------------| +| `prompt` | `string` | - | +| `stylePrompt` | `string` | - | +| `lyricsPrompt` | `string` | - | +| `structure` | `unknown` | - | + +### Classes + +#### `AudioPromptBuilder` + +**Methods:** + +| Method | Description | +|--------|-------------| +| `genre(primary: MusicGenre | AudioGenre): this` | - | +| `subgenre(subgenre: string): this` | - | +| `fusion(genres: MusicGenre[]): this` | - | +| `mood(primary: Mood | string, ...secondary: (Mood | string)[]): this` | - | +| `energy(level: AudioMood['energy']): this` | - | +| `emotion(emotion: string): this` | - | +| `tempo(bpmOrSettings: number | AudioTempo): this` | - | +| `bpm(bpm: number): this` | - | +| `tempoMarking(marking: TempoMarking): this` | - | +| `tempoFeel(feel: AudioTempo['feel']): this` | - | +| `vocals(settings: AudioVocals): this` | - | +| `vocalStyle(style: VocalStyle | VocalStyle[]): this` | - | +| `language(language: VocalLanguage): this` | - | +| `lyrics(lyrics: string): this` | - | +| `lyricsTheme(theme: string): this` | - | +| `delivery(delivery: string): this` | - | +| `instrumental(): this` | - | +| `instruments(instruments: Instrument[]): this` | - | +| `instrumentation(settings: AudioInstrumentation): this` | - | +| `leadInstrument(instrument: Instrument | Instrument[]): this` | - | +| `rhythmSection(instruments: Instrument[]): this` | - | +| `bassInstrument(instrument: Instrument): this` | - | +| `percussion(instruments: Instrument | Instrument[]): this` | - | +| `pads(instruments: Instrument | Instrument[]): this` | - | +| `featuredInstrument(instrument: Instrument): this` | - | +| `structure(settings: AudioStructure | { [key in SongSection]?: number }): this` | - | +| `section(type: SongSection, bars?: number, description?: string): this` | - | +| `form(form: string): this` | - | +| `duration(seconds: number): this` | - | +| `production(settings: AudioProduction): this` | - | +| `productionStyle(style: ProductionStyle | ProductionStyle[]): this` | - | +| `era(era: Era): this` | - | +| `reference(artists: string[]): this` | - | +| `texture(texture: string): this` | - | +| `effects(effects: string[]): this` | - | +| `technical(settings: AudioTechnical): this` | - | +| `key(key: MusicalKey): this` | - | +| `timeSignature(sig: TimeSignature): this` | - | +| `formatType(format: AudioTechnical['format']): this` | - | +| `tag(tag: string): this` | - | +| `tags(tags: string[]): this` | - | +| `custom(text: string): this` | - | +| `build(): BuiltAudioPrompt` | - | +| `toString(): string` | - | +| `toStyleString(): string` | - | +| `toJSON(): string` | - | +| `toYAML(): string` | - | +| `toMarkdown(): string` | - | +| `outputFormat(fmt: OutputFormat): string` | - | + +##### `genre()` + +```typescript +genre(primary: MusicGenre | AudioGenre): this +``` + +**Parameters:** + +- `primary`: `MusicGenre | AudioGenre` + +**Returns:** `this` + +##### `subgenre()` + +```typescript +subgenre(subgenre: string): this +``` + +**Parameters:** + +- `subgenre`: `string` + +**Returns:** `this` + +##### `fusion()` + +```typescript +fusion(genres: MusicGenre[]): this +``` + +**Parameters:** + +- `genres`: `MusicGenre[]` + +**Returns:** `this` + +##### `mood()` + +```typescript +mood(primary: Mood | string, ...secondary: (Mood | string)[]): this +``` + +**Parameters:** + +- `primary`: `Mood | string` +- `secondary`: `(Mood | string)[]` + +**Returns:** `this` + +##### `energy()` + +```typescript +energy(level: AudioMood['energy']): this +``` + +**Parameters:** + +- `level`: `AudioMood['energy']` + +**Returns:** `this` + +##### `emotion()` + +```typescript +emotion(emotion: string): this +``` + +**Parameters:** + +- `emotion`: `string` + +**Returns:** `this` + +##### `tempo()` + +```typescript +tempo(bpmOrSettings: number | AudioTempo): this +``` + +**Parameters:** + +- `bpmOrSettings`: `number | AudioTempo` + +**Returns:** `this` + +##### `bpm()` + +```typescript +bpm(bpm: number): this +``` + +**Parameters:** + +- `bpm`: `number` + +**Returns:** `this` + +##### `tempoMarking()` + +```typescript +tempoMarking(marking: TempoMarking): this +``` + +**Parameters:** + +- `marking`: `TempoMarking` + +**Returns:** `this` + +##### `tempoFeel()` + +```typescript +tempoFeel(feel: AudioTempo['feel']): this +``` + +**Parameters:** + +- `feel`: `AudioTempo['feel']` + +**Returns:** `this` + +##### `vocals()` + +```typescript +vocals(settings: AudioVocals): this +``` + +**Parameters:** + +- `settings`: `AudioVocals` + +**Returns:** `this` + +##### `vocalStyle()` + +```typescript +vocalStyle(style: VocalStyle | VocalStyle[]): this +``` + +**Parameters:** + +- `style`: `VocalStyle | VocalStyle[]` + +**Returns:** `this` + +##### `language()` + +```typescript +language(language: VocalLanguage): this +``` + +**Parameters:** + +- `language`: `VocalLanguage` + +**Returns:** `this` + +##### `lyrics()` + +```typescript +lyrics(lyrics: string): this +``` + +**Parameters:** + +- `lyrics`: `string` + +**Returns:** `this` + +##### `lyricsTheme()` + +```typescript +lyricsTheme(theme: string): this +``` + +**Parameters:** + +- `theme`: `string` + +**Returns:** `this` + +##### `delivery()` + +```typescript +delivery(delivery: string): this +``` + +**Parameters:** + +- `delivery`: `string` + +**Returns:** `this` + +##### `instrumental()` + +```typescript +instrumental(): this +``` + +**Returns:** `this` + +##### `instruments()` + +```typescript +instruments(instruments: Instrument[]): this +``` + +**Parameters:** + +- `instruments`: `Instrument[]` + +**Returns:** `this` + +##### `instrumentation()` + +```typescript +instrumentation(settings: AudioInstrumentation): this +``` + +**Parameters:** + +- `settings`: `AudioInstrumentation` + +**Returns:** `this` + +##### `leadInstrument()` + +```typescript +leadInstrument(instrument: Instrument | Instrument[]): this +``` + +**Parameters:** + +- `instrument`: `Instrument | Instrument[]` + +**Returns:** `this` + +##### `rhythmSection()` + +```typescript +rhythmSection(instruments: Instrument[]): this +``` + +**Parameters:** + +- `instruments`: `Instrument[]` + +**Returns:** `this` + +##### `bassInstrument()` + +```typescript +bassInstrument(instrument: Instrument): this +``` + +**Parameters:** + +- `instrument`: `Instrument` + +**Returns:** `this` + +##### `percussion()` + +```typescript +percussion(instruments: Instrument | Instrument[]): this +``` + +**Parameters:** + +- `instruments`: `Instrument | Instrument[]` + +**Returns:** `this` + +##### `pads()` + +```typescript +pads(instruments: Instrument | Instrument[]): this +``` + +**Parameters:** + +- `instruments`: `Instrument | Instrument[]` + +**Returns:** `this` + +##### `featuredInstrument()` + +```typescript +featuredInstrument(instrument: Instrument): this +``` + +**Parameters:** + +- `instrument`: `Instrument` + +**Returns:** `this` + +##### `structure()` + +```typescript +structure(settings: AudioStructure | { [key in SongSection]?: number }): this +``` + +**Parameters:** + +- `settings`: `AudioStructure | { [key in SongSection]?: number }` + +**Returns:** `this` + +##### `section()` + +```typescript +section(type: SongSection, bars?: number, description?: string): this +``` + +**Parameters:** + +- `type`: `SongSection` +- `bars`: `number` (optional) +- `description`: `string` (optional) + +**Returns:** `this` + +##### `form()` + +```typescript +form(form: string): this +``` + +**Parameters:** + +- `form`: `string` + +**Returns:** `this` + +##### `duration()` + +```typescript +duration(seconds: number): this +``` + +**Parameters:** + +- `seconds`: `number` + +**Returns:** `this` + +##### `production()` + +```typescript +production(settings: AudioProduction): this +``` + +**Parameters:** + +- `settings`: `AudioProduction` + +**Returns:** `this` + +##### `productionStyle()` + +```typescript +productionStyle(style: ProductionStyle | ProductionStyle[]): this +``` + +**Parameters:** + +- `style`: `ProductionStyle | ProductionStyle[]` + +**Returns:** `this` + +##### `era()` + +```typescript +era(era: Era): this +``` + +**Parameters:** + +- `era`: `Era` + +**Returns:** `this` + +##### `reference()` + +```typescript +reference(artists: string[]): this +``` + +**Parameters:** + +- `artists`: `string[]` + +**Returns:** `this` + +##### `texture()` + +```typescript +texture(texture: string): this +``` + +**Parameters:** + +- `texture`: `string` + +**Returns:** `this` + +##### `effects()` + +```typescript +effects(effects: string[]): this +``` + +**Parameters:** + +- `effects`: `string[]` + +**Returns:** `this` + +##### `technical()` + +```typescript +technical(settings: AudioTechnical): this +``` + +**Parameters:** + +- `settings`: `AudioTechnical` + +**Returns:** `this` + +##### `key()` + +```typescript +key(key: MusicalKey): this +``` + +**Parameters:** + +- `key`: `MusicalKey` + +**Returns:** `this` + +##### `timeSignature()` + +```typescript +timeSignature(sig: TimeSignature): this +``` + +**Parameters:** + +- `sig`: `TimeSignature` + +**Returns:** `this` + +##### `formatType()` + +```typescript +formatType(format: AudioTechnical['format']): this +``` + +**Parameters:** + +- `format`: `AudioTechnical['format']` + +**Returns:** `this` + +##### `tag()` + +```typescript +tag(tag: string): this +``` + +**Parameters:** + +- `tag`: `string` + +**Returns:** `this` + +##### `tags()` + +```typescript +tags(tags: string[]): this +``` + +**Parameters:** + +- `tags`: `string[]` + +**Returns:** `this` + +##### `custom()` + +```typescript +custom(text: string): this +``` + +**Parameters:** + +- `text`: `string` + +**Returns:** `this` + +##### `build()` + +```typescript +build(): BuiltAudioPrompt +``` + +**Returns:** `BuiltAudioPrompt` + +##### `toString()` + +```typescript +toString(): string +``` + +**Returns:** `string` + +##### `toStyleString()` + +```typescript +toStyleString(): string +``` + +**Returns:** `string` + +##### `toJSON()` + +```typescript +toJSON(): string +``` + +**Returns:** `string` + +##### `toYAML()` + +```typescript +toYAML(): string +``` + +**Returns:** `string` + +##### `toMarkdown()` + +```typescript +toMarkdown(): string +``` + +**Returns:** `string` + +##### `outputFormat()` + +```typescript +outputFormat(fmt: OutputFormat): string +``` + +**Parameters:** + +- `fmt`: `OutputFormat` + +**Returns:** `string` + +### Functions + +#### `audio()` + +Create a new audio/music prompt builder + +```typescript +audio(): AudioPromptBuilder +``` + +**Returns:** `AudioPromptBuilder` diff --git a/packages/prompts.chat/README.md b/packages/prompts.chat/README.md index edbabe7a..e7363f49 100644 --- a/packages/prompts.chat/README.md +++ b/packages/prompts.chat/README.md @@ -1,4 +1,4 @@ -# prompts.chat Typed Prompts +# prompts.chat Prompt Builder A comprehensive developer toolkit for building, validating, and parsing AI prompts. Create structured prompts for chat models, image generators, video AI, and music generation with fluent, type-safe APIs. diff --git a/packages/prompts.chat/package.json b/packages/prompts.chat/package.json index 91db175b..5c880179 100644 --- a/packages/prompts.chat/package.json +++ b/packages/prompts.chat/package.json @@ -71,7 +71,9 @@ "typecheck": "tsc --noEmit", "test": "vitest run", "test:watch": "vitest", - "test:coverage": "vitest run --coverage" + "test:coverage": "vitest run --coverage", + "docs": "npx ts-node scripts/generate-docs.ts", + "docs:generate": "npx tsx scripts/generate-docs.ts" }, "devDependencies": { "@types/node": "^20", diff --git a/packages/prompts.chat/scripts/generate-docs.ts b/packages/prompts.chat/scripts/generate-docs.ts new file mode 100644 index 00000000..8ac4ea55 --- /dev/null +++ b/packages/prompts.chat/scripts/generate-docs.ts @@ -0,0 +1,1138 @@ +/** + * API Documentation Generator + * Parses TypeScript source files using the TypeScript Compiler API + * and generates markdown documentation from types, interfaces, functions, and classes. + */ + +import * as ts from 'typescript'; +import * as fs from 'fs'; +import * as path from 'path'; + +interface DocEntry { + name: string; + kind: 'interface' | 'type' | 'function' | 'class' | 'method' | 'property' | 'variable'; + description?: string; + signature?: string; + parameters?: Array<{ name: string; type: string; description?: string; optional?: boolean; defaultValue?: string }>; + returnType?: string; + returnDescription?: string; + properties?: DocEntry[]; + methods?: DocEntry[]; + examples?: string[]; + tags?: Record; + exported?: boolean; +} + +interface ModuleDoc { + name: string; + description?: string; + exports: DocEntry[]; +} + +function getJSDocComment(node: ts.Node, sourceFile: ts.SourceFile): { description?: string; tags: Record; examples: string[] } { + const tags: Record = {}; + const examples: string[] = []; + let description: string | undefined; + + const jsDocNodes = (node as any).jsDoc as ts.JSDoc[] | undefined; + if (jsDocNodes && jsDocNodes.length > 0) { + const jsDoc = jsDocNodes[0]; + + if (jsDoc.comment) { + description = typeof jsDoc.comment === 'string' + ? jsDoc.comment + : jsDoc.comment.map(c => c.text || '').join(''); + } + + if (jsDoc.tags) { + for (const tag of jsDoc.tags) { + const tagName = tag.tagName.text; + let tagComment = ''; + + if (tag.comment) { + tagComment = typeof tag.comment === 'string' + ? tag.comment + : tag.comment.map(c => c.text || '').join(''); + } + + if (tagName === 'example') { + examples.push(tagComment); + } else if (tagName === 'param' && ts.isJSDocParameterTag(tag)) { + const paramName = tag.name.getText(sourceFile); + tags[`param:${paramName}`] = tagComment; + } else if (tagName === 'returns' || tagName === 'return') { + tags['returns'] = tagComment; + } else { + tags[tagName] = tagComment; + } + } + } + } + + return { description, tags, examples }; +} + +function getTypeString(type: ts.TypeNode | undefined, sourceFile: ts.SourceFile): string { + if (!type) return 'any'; + return type.getText(sourceFile); +} + +function parseFunction(node: ts.FunctionDeclaration | ts.MethodDeclaration | ts.ArrowFunction, sourceFile: ts.SourceFile, checker: ts.TypeChecker): DocEntry { + const { description, tags, examples } = getJSDocComment(node, sourceFile); + + const name = ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node) + ? node.name?.getText(sourceFile) || 'anonymous' + : 'anonymous'; + + const parameters: Array<{ name: string; type: string; description?: string; optional?: boolean; defaultValue?: string; isRest?: boolean }> = []; + + for (const param of node.parameters) { + const paramName = param.name.getText(sourceFile); + const paramType = getTypeString(param.type, sourceFile); + const optional = !!param.questionToken || !!param.initializer; + const defaultValue = param.initializer?.getText(sourceFile); + const paramDescription = tags[`param:${paramName}`]; + const isRest = !!param.dotDotDotToken; + + parameters.push({ + name: paramName, + type: paramType, + description: paramDescription, + optional, + defaultValue, + isRest, + }); + } + + const returnType = getTypeString(node.type, sourceFile); + + // Build signature - handle rest parameters with ... prefix + const paramSignature = parameters + .map(p => `${p.isRest ? '...' : ''}${p.name}${p.optional ? '?' : ''}: ${p.type}`) + .join(', '); + const signature = `${name}(${paramSignature}): ${returnType}`; + + return { + name, + kind: ts.isMethodDeclaration(node) ? 'method' : 'function', + description, + signature, + parameters, + returnType, + returnDescription: tags['returns'], + examples, + tags, + }; +} + +function parseInterface(node: ts.InterfaceDeclaration, sourceFile: ts.SourceFile, checker: ts.TypeChecker): DocEntry { + const { description, tags, examples } = getJSDocComment(node, sourceFile); + const name = node.name.getText(sourceFile); + + const properties: DocEntry[] = []; + + for (const member of node.members) { + if (ts.isPropertySignature(member)) { + const propName = member.name.getText(sourceFile); + const propType = getTypeString(member.type, sourceFile); + const optional = !!member.questionToken; + const { description: propDesc } = getJSDocComment(member, sourceFile); + + properties.push({ + name: propName, + kind: 'property', + description: propDesc, + signature: `${propName}${optional ? '?' : ''}: ${propType}`, + }); + } else if (ts.isMethodSignature(member)) { + const methodName = member.name.getText(sourceFile); + const params = member.parameters.map(p => { + const pName = p.name.getText(sourceFile); + const pType = getTypeString(p.type, sourceFile); + const pOptional = !!p.questionToken; + return `${pName}${pOptional ? '?' : ''}: ${pType}`; + }).join(', '); + const returnType = getTypeString(member.type, sourceFile); + const { description: methodDesc } = getJSDocComment(member, sourceFile); + + properties.push({ + name: methodName, + kind: 'method', + description: methodDesc, + signature: `${methodName}(${params}): ${returnType}`, + }); + } + } + + return { + name, + kind: 'interface', + description, + properties, + examples, + tags, + }; +} + +function parseTypeAlias(node: ts.TypeAliasDeclaration, sourceFile: ts.SourceFile, checker: ts.TypeChecker): DocEntry { + const { description, tags, examples } = getJSDocComment(node, sourceFile); + const name = node.name.getText(sourceFile); + const typeText = node.type.getText(sourceFile); + + return { + name, + kind: 'type', + description, + signature: `type ${name} = ${typeText}`, + examples, + tags, + }; +} + +function parseClass(node: ts.ClassDeclaration, sourceFile: ts.SourceFile, checker: ts.TypeChecker): DocEntry { + const { description, tags, examples } = getJSDocComment(node, sourceFile); + const name = node.name?.getText(sourceFile) || 'AnonymousClass'; + + const methods: DocEntry[] = []; + const properties: DocEntry[] = []; + + for (const member of node.members) { + // Skip private members + const modifiers = ts.canHaveModifiers(member) ? ts.getModifiers(member) : undefined; + const isPrivate = modifiers?.some(m => m.kind === ts.SyntaxKind.PrivateKeyword); + if (isPrivate) continue; + + if (ts.isMethodDeclaration(member)) { + const methodDoc = parseFunction(member, sourceFile, checker); + // Only include public methods (not starting with _) + if (!methodDoc.name.startsWith('_')) { + methods.push(methodDoc); + } + } else if (ts.isPropertyDeclaration(member)) { + const propName = member.name.getText(sourceFile); + if (!propName.startsWith('_')) { + const propType = getTypeString(member.type, sourceFile); + const { description: propDesc } = getJSDocComment(member, sourceFile); + properties.push({ + name: propName, + kind: 'property', + description: propDesc, + signature: `${propName}: ${propType}`, + }); + } + } + } + + return { + name, + kind: 'class', + description, + methods, + properties, + examples, + tags, + }; +} + +function parseVariableStatement(node: ts.VariableStatement, sourceFile: ts.SourceFile, checker: ts.TypeChecker): DocEntry[] { + const { description, tags, examples } = getJSDocComment(node, sourceFile); + const entries: DocEntry[] = []; + + for (const decl of node.declarationList.declarations) { + const name = decl.name.getText(sourceFile); + let signature = name; + + if (decl.type) { + signature += `: ${decl.type.getText(sourceFile)}`; + } else if (decl.initializer) { + // Try to infer from initializer + const initText = decl.initializer.getText(sourceFile); + if (initText.length < 100) { + signature += ` = ${initText}`; + } + } + + entries.push({ + name, + kind: 'variable', + description, + signature, + examples, + tags, + }); + } + + return entries; +} + +function parseSourceFile(filePath: string, program: ts.Program): ModuleDoc { + const sourceFile = program.getSourceFile(filePath); + if (!sourceFile) { + throw new Error(`Could not find source file: ${filePath}`); + } + + const checker = program.getTypeChecker(); + const exports: DocEntry[] = []; + + // Get module-level JSDoc if any + let moduleDescription: string | undefined; + const firstStatement = sourceFile.statements[0]; + if (firstStatement) { + const { description } = getJSDocComment(firstStatement, sourceFile); + if (description && description.includes('@module')) { + moduleDescription = description; + } + } + + // Check for leading comment as module description + const fullText = sourceFile.getFullText(); + const leadingCommentMatch = fullText.match(/^\/\*\*\s*\n([^*]|\*(?!\/))*\*\//); + if (leadingCommentMatch) { + const comment = leadingCommentMatch[0]; + const lines = comment.split('\n').slice(1, -1).map(l => l.replace(/^\s*\*\s?/, '')); + moduleDescription = lines.join('\n').trim(); + } + + function visit(node: ts.Node) { + // Check if node is exported + const modifiers = ts.canHaveModifiers(node) ? ts.getModifiers(node) : undefined; + const isExported = modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword); + + if (ts.isFunctionDeclaration(node) && isExported && node.name) { + const doc = parseFunction(node, sourceFile!, checker); + doc.exported = true; + exports.push(doc); + } else if (ts.isInterfaceDeclaration(node) && isExported) { + const doc = parseInterface(node, sourceFile!, checker); + doc.exported = true; + exports.push(doc); + } else if (ts.isTypeAliasDeclaration(node) && isExported) { + const doc = parseTypeAlias(node, sourceFile!, checker); + doc.exported = true; + exports.push(doc); + } else if (ts.isClassDeclaration(node) && isExported && node.name) { + const doc = parseClass(node, sourceFile!, checker); + doc.exported = true; + exports.push(doc); + } else if (ts.isVariableStatement(node) && isExported) { + const docs = parseVariableStatement(node, sourceFile!, checker); + docs.forEach(d => { + d.exported = true; + exports.push(d); + }); + } + + ts.forEachChild(node, visit); + } + + visit(sourceFile); + + const moduleName = path.basename(filePath, '.ts'); + return { + name: moduleName, + description: moduleDescription, + exports, + }; +} + +function generateMarkdown(modules: ModuleDoc[]): string { + const lines: string[] = []; + + lines.push('# API Reference\n'); + lines.push('> Auto-generated from TypeScript source files\n'); + + // Table of contents + lines.push('## Table of Contents\n'); + for (const mod of modules) { + lines.push(`- [${mod.name}](#${mod.name.toLowerCase()})`); + for (const exp of mod.exports) { + if (exp.kind === 'function' || exp.kind === 'class') { + lines.push(` - [${exp.name}](#${exp.name.toLowerCase()})`); + } + } + } + lines.push(''); + + // Module documentation + for (const mod of modules) { + lines.push(`---\n`); + lines.push(`## ${mod.name}\n`); + + if (mod.description) { + lines.push(`${mod.description}\n`); + } + + // Group by kind + const interfaces = mod.exports.filter(e => e.kind === 'interface'); + const types = mod.exports.filter(e => e.kind === 'type'); + const functions = mod.exports.filter(e => e.kind === 'function'); + const classes = mod.exports.filter(e => e.kind === 'class'); + const variables = mod.exports.filter(e => e.kind === 'variable'); + + // Types + if (types.length > 0) { + lines.push(`### Types\n`); + for (const t of types) { + lines.push(`#### \`${t.name}\`\n`); + if (t.description) { + lines.push(`${t.description}\n`); + } + lines.push('```typescript'); + lines.push(t.signature || ''); + lines.push('```\n'); + } + } + + // Interfaces + if (interfaces.length > 0) { + lines.push(`### Interfaces\n`); + for (const iface of interfaces) { + lines.push(`#### \`${iface.name}\`\n`); + if (iface.description) { + lines.push(`${iface.description}\n`); + } + if (iface.properties && iface.properties.length > 0) { + lines.push('| Property | Type | Description |'); + lines.push('|----------|------|-------------|'); + for (const prop of iface.properties) { + const sig = prop.signature || prop.name; + const typeMatch = sig.match(/:\s*(.+)$/); + const type = typeMatch ? typeMatch[1] : 'unknown'; + lines.push(`| \`${prop.name}\` | \`${type}\` | ${prop.description || '-'} |`); + } + lines.push(''); + } + } + } + + // Classes + if (classes.length > 0) { + lines.push(`### Classes\n`); + for (const cls of classes) { + lines.push(`#### \`${cls.name}\`\n`); + if (cls.description) { + lines.push(`${cls.description}\n`); + } + + if (cls.methods && cls.methods.length > 0) { + lines.push('**Methods:**\n'); + lines.push('| Method | Description |'); + lines.push('|--------|-------------|'); + for (const method of cls.methods) { + const sig = method.signature?.replace(/\n/g, ' ') || method.name; + lines.push(`| \`${sig}\` | ${method.description || '-'} |`); + } + lines.push(''); + + // Detailed method docs + for (const method of cls.methods) { + lines.push(`##### \`${method.name}()\`\n`); + if (method.description) { + lines.push(`${method.description}\n`); + } + if (method.signature) { + lines.push('```typescript'); + lines.push(method.signature); + lines.push('```\n'); + } + if (method.parameters && method.parameters.length > 0) { + lines.push('**Parameters:**\n'); + for (const param of method.parameters) { + const opt = param.optional ? ' (optional)' : ''; + const def = param.defaultValue ? ` = \`${param.defaultValue}\`` : ''; + lines.push(`- \`${param.name}\`: \`${param.type}\`${opt}${def}${param.description ? ` - ${param.description}` : ''}`); + } + lines.push(''); + } + if (method.returnType && method.returnType !== 'void') { + lines.push(`**Returns:** \`${method.returnType}\`${method.returnDescription ? ` - ${method.returnDescription}` : ''}\n`); + } + } + } + } + } + + // Functions + if (functions.length > 0) { + lines.push(`### Functions\n`); + for (const fn of functions) { + lines.push(`#### \`${fn.name}()\`\n`); + if (fn.description) { + lines.push(`${fn.description}\n`); + } + if (fn.signature) { + lines.push('```typescript'); + lines.push(fn.signature); + lines.push('```\n'); + } + if (fn.parameters && fn.parameters.length > 0) { + lines.push('**Parameters:**\n'); + for (const param of fn.parameters) { + const opt = param.optional ? ' (optional)' : ''; + const def = param.defaultValue ? ` = \`${param.defaultValue}\`` : ''; + lines.push(`- \`${param.name}\`: \`${param.type}\`${opt}${def}${param.description ? ` - ${param.description}` : ''}`); + } + lines.push(''); + } + if (fn.returnType && fn.returnType !== 'void') { + lines.push(`**Returns:** \`${fn.returnType}\`${fn.returnDescription ? ` - ${fn.returnDescription}` : ''}\n`); + } + if (fn.examples && fn.examples.length > 0) { + lines.push('**Example:**\n'); + for (const example of fn.examples) { + lines.push('```typescript'); + lines.push(example.trim()); + lines.push('```\n'); + } + } + } + } + + // Variables/Constants + if (variables.length > 0) { + lines.push(`### Constants\n`); + for (const v of variables) { + lines.push(`#### \`${v.name}\`\n`); + if (v.description) { + lines.push(`${v.description}\n`); + } + if (v.signature) { + lines.push('```typescript'); + lines.push(v.signature); + lines.push('```\n'); + } + } + } + } + + return lines.join('\n'); +} + +// Generate TypeScript file for IDE sidebar +function generateSidebarTS(modules: ModuleDoc[]): string { + const lines: string[] = []; + + lines.push('/**'); + lines.push(' * Auto-generated API documentation for IDE sidebar'); + lines.push(' * Generated from TypeScript source files via reflection'); + lines.push(' * DO NOT EDIT MANUALLY - run `npm run docs:generate` to regenerate'); + lines.push(' */'); + lines.push(''); + lines.push('export interface ApiSection {'); + lines.push(' name: string;'); + lines.push(' items: ApiItem[];'); + lines.push('}'); + lines.push(''); + lines.push('export interface ApiItem {'); + lines.push(' name: string;'); + lines.push(' type: "function" | "class" | "type" | "interface" | "const" | "method";'); + lines.push(' signature?: string;'); + lines.push(' description?: string;'); + lines.push(' example?: string;'); + lines.push(' returns?: string;'); + lines.push(' params?: { name: string; type: string; description?: string }[];'); + lines.push('}'); + lines.push(''); + lines.push('export const API_DOCS: ApiSection[] = ['); + + // Group modules by category for better organization + const moduleGroups: Record = { + 'Text Prompts': [], + 'Chat Prompts': [], + 'Image Prompts': [], + 'Video Prompts': [], + 'Audio Prompts': [], + 'Variables': [], + 'Similarity': [], + 'Quality': [], + 'Parser': [], + }; + + for (const mod of modules) { + if (mod.name.includes('variables')) { + moduleGroups['Variables'].push(mod); + } else if (mod.name.includes('similarity')) { + moduleGroups['Similarity'].push(mod); + } else if (mod.name.includes('quality')) { + moduleGroups['Quality'].push(mod); + } else if (mod.name.includes('parser')) { + moduleGroups['Parser'].push(mod); + } else if (mod.name.includes('chat')) { + moduleGroups['Chat Prompts'].push(mod); + } else if (mod.name.includes('media') || mod.name.includes('image')) { + moduleGroups['Image Prompts'].push(mod); + } else if (mod.name.includes('video')) { + moduleGroups['Video Prompts'].push(mod); + } else if (mod.name.includes('audio')) { + moduleGroups['Audio Prompts'].push(mod); + } else if (mod.name.includes('builder')) { + moduleGroups['Text Prompts'].push(mod); + } + } + + // Process each group + for (const [groupName, groupModules] of Object.entries(moduleGroups)) { + if (groupModules.length === 0) continue; + + const items: string[] = []; + + for (const mod of groupModules) { + // Add functions + const functions = mod.exports.filter(e => e.kind === 'function'); + for (const fn of functions) { + const params = fn.parameters?.map(p => ({ + name: p.name, + type: p.type, + description: p.description || undefined, + })) || []; + + items.push(` { + name: "${fn.name}()", + type: "function", + signature: ${JSON.stringify(fn.signature || fn.name)}, + description: ${JSON.stringify(fn.description || '')}, + returns: ${JSON.stringify(fn.returnType || '')}, + params: ${JSON.stringify(params)}, + }`); + } + + // Add classes with their methods + const classes = mod.exports.filter(e => e.kind === 'class'); + for (const cls of classes) { + // Add the class itself + items.push(` { + name: "${cls.name}", + type: "class", + description: ${JSON.stringify(cls.description || '')}, + }`); + + // Add class methods + if (cls.methods) { + for (const method of cls.methods) { + const params = method.parameters?.map(p => ({ + name: p.name, + type: p.type, + description: p.description || undefined, + })) || []; + + items.push(` { + name: ".${method.name}()", + type: "method", + signature: ${JSON.stringify(method.signature || method.name)}, + description: ${JSON.stringify(method.description || '')}, + returns: ${JSON.stringify(method.returnType || '')}, + params: ${JSON.stringify(params)}, + }`); + } + } + } + + // Add interfaces + const interfaces = mod.exports.filter(e => e.kind === 'interface'); + for (const iface of interfaces) { + items.push(` { + name: "${iface.name}", + type: "interface", + description: ${JSON.stringify(iface.description || '')}, + }`); + } + + // Add types + const types = mod.exports.filter(e => e.kind === 'type'); + for (const t of types) { + items.push(` { + name: "${t.name}", + type: "type", + signature: ${JSON.stringify(t.signature || '')}, + description: ${JSON.stringify(t.description || '')}, + }`); + } + + // Add constants/variables + const vars = mod.exports.filter(e => e.kind === 'variable'); + for (const v of vars) { + items.push(` { + name: "${v.name}", + type: "const", + signature: ${JSON.stringify(v.signature || '')}, + description: ${JSON.stringify(v.description || '')}, + }`); + } + } + + if (items.length > 0) { + lines.push(` {`); + lines.push(` name: "${groupName}",`); + lines.push(` items: [`); + lines.push(items.join(',\n')); + lines.push(` ],`); + lines.push(` },`); + } + } + + lines.push('];'); + lines.push(''); + + return lines.join('\n'); +} + +// Generate TypeScript declaration file content for Monaco editor +function generateTypeDefinitions(modules: ModuleDoc[]): string { + const lines: string[] = []; + + lines.push('/**'); + lines.push(' * Auto-generated type definitions for prompts.chat'); + lines.push(' * Generated from TypeScript source files via reflection'); + lines.push(' * DO NOT EDIT MANUALLY - run `npm run docs:generate` to regenerate'); + lines.push(' */'); + lines.push(''); + lines.push("export const TYPE_DEFINITIONS = `"); + lines.push("declare module 'prompts.chat' {"); + + // Group by category + const builderModule = modules.find(m => m.name === 'builder/index'); + const chatModule = modules.find(m => m.name === 'builder/chat'); + const mediaModule = modules.find(m => m.name === 'builder/media'); + const videoModule = modules.find(m => m.name === 'builder/video'); + const audioModule = modules.find(m => m.name === 'builder/audio'); + const variablesModule = modules.find(m => m.name === 'variables/index'); + const similarityModule = modules.find(m => m.name === 'similarity/index'); + const qualityModule = modules.find(m => m.name === 'quality/index'); + const parserModule = modules.find(m => m.name === 'parser/index'); + + // Helper to generate interface/type declarations + const generateInterfaceDecl = (entry: DocEntry): string => { + if (entry.kind === 'interface' && entry.properties) { + const props = entry.properties.map(p => { + const sig = p.signature || `${p.name}: unknown`; + return ` ${sig};`; + }).join('\n'); + return ` export interface ${entry.name} {\n${props}\n }`; + } + return ''; + }; + + const generateTypeDecl = (entry: DocEntry): string => { + if (entry.kind === 'type' && entry.signature) { + return ` export ${entry.signature};`; + } + return ''; + }; + + const generateClassDecl = (entry: DocEntry): string => { + if (entry.kind === 'class' && entry.methods) { + const methods = entry.methods.map(m => { + const sig = m.signature || `${m.name}(): unknown`; + return ` ${sig};`; + }).join('\n'); + return ` export class ${entry.name} {\n${methods}\n }`; + } + return ''; + }; + + const generateFunctionDecl = (entry: DocEntry): string => { + if (entry.kind === 'function' && entry.signature) { + return ` export function ${entry.signature};`; + } + return ''; + }; + + // Track already added declarations to avoid duplicates + const addedTypes = new Set(); + const addedInterfaces = new Set(); + const addedClasses = new Set(); + const addedFunctions = new Set(); + + // Process each module + const processModule = (mod: ModuleDoc | undefined, sectionComment: string) => { + if (!mod) return; + + lines.push(''); + lines.push(` // ${sectionComment}`); + + // Types first (skip duplicates) + for (const entry of mod.exports.filter(e => e.kind === 'type')) { + if (addedTypes.has(entry.name)) continue; + const decl = generateTypeDecl(entry); + if (decl) { + lines.push(decl); + addedTypes.add(entry.name); + } + } + + // Interfaces (skip duplicates) + for (const entry of mod.exports.filter(e => e.kind === 'interface')) { + if (addedInterfaces.has(entry.name)) continue; + const decl = generateInterfaceDecl(entry); + if (decl) { + lines.push(decl); + addedInterfaces.add(entry.name); + } + } + + // Classes (skip duplicates) + for (const entry of mod.exports.filter(e => e.kind === 'class')) { + if (addedClasses.has(entry.name)) continue; + const decl = generateClassDecl(entry); + if (decl) { + lines.push(decl); + addedClasses.add(entry.name); + } + } + + // Functions (skip duplicates) + for (const entry of mod.exports.filter(e => e.kind === 'function')) { + if (addedFunctions.has(entry.name)) continue; + const decl = generateFunctionDecl(entry); + if (decl) { + lines.push(decl); + addedFunctions.add(entry.name); + } + } + }; + + // Process modules in order - audio first since it has the complete type definitions + processModule(builderModule, 'BUILDER TYPES'); + processModule(chatModule, 'CHAT BUILDER TYPES'); + processModule(audioModule, 'AUDIO BUILDER TYPES'); + processModule(videoModule, 'VIDEO BUILDER TYPES'); + processModule(mediaModule, 'IMAGE BUILDER TYPES'); + + // Utility namespaces + if (variablesModule) { + lines.push(''); + lines.push(' // UTILITY MODULES'); + lines.push(' export namespace variables {'); + for (const entry of variablesModule.exports.filter(e => e.kind === 'function')) { + if (entry.signature) { + lines.push(` export function ${entry.signature};`); + } + } + lines.push(' }'); + } + + if (similarityModule) { + lines.push(' export namespace similarity {'); + for (const entry of similarityModule.exports.filter(e => e.kind === 'function')) { + if (entry.signature) { + lines.push(` export function ${entry.signature};`); + } + } + lines.push(' }'); + } + + if (qualityModule) { + lines.push(' export namespace quality {'); + for (const entry of qualityModule.exports.filter(e => e.kind === 'function')) { + if (entry.signature) { + lines.push(` export function ${entry.signature};`); + } + } + lines.push(' }'); + } + + if (parserModule) { + lines.push(' export namespace parser {'); + for (const entry of parserModule.exports.filter(e => e.kind === 'function')) { + if (entry.signature) { + lines.push(` export function ${entry.signature};`); + } + } + lines.push(' }'); + } + + lines.push('}'); + lines.push('`;'); + lines.push(''); + + return lines.join('\n'); +} + +// Extract string literal options from type aliases and method parameters +function extractStringLiteralOptions(program: ts.Program, files: string[]): Record { + // Phase 1: Collect all type aliases and interface properties + const typeAliases: Record = {}; + const interfaceProps: Record> = {}; // InterfaceName -> { propName -> literals } + + function extractLiteralsFromType(type: ts.TypeNode, sourceFile: ts.SourceFile): string[] { + const literals: string[] = []; + + if (ts.isUnionTypeNode(type)) { + for (const member of type.types) { + if (ts.isLiteralTypeNode(member) && member.literal && ts.isStringLiteral(member.literal)) { + literals.push(member.literal.text); + } else if (ts.isUnionTypeNode(member)) { + literals.push(...extractLiteralsFromType(member, sourceFile)); + } + } + } else if (ts.isLiteralTypeNode(type) && type.literal && ts.isStringLiteral(type.literal)) { + literals.push(type.literal.text); + } + + return literals; + } + + // First pass: collect type aliases and interface properties + for (const filePath of files) { + const sourceFile = program.getSourceFile(filePath); + if (!sourceFile) continue; + const sf = sourceFile; // Capture for closure + + function collectTypes(node: ts.Node) { + if (ts.isTypeAliasDeclaration(node)) { + const typeName = node.name.getText(sf); + const literals = extractLiteralsFromType(node.type, sf); + if (literals.length > 0) { + typeAliases[typeName] = literals; + } + } + + if (ts.isInterfaceDeclaration(node)) { + const interfaceName = node.name.getText(sf); + interfaceProps[interfaceName] = interfaceProps[interfaceName] || {}; + + for (const member of node.members) { + if (ts.isPropertySignature(member) && member.name && member.type) { + const propName = member.name.getText(sf); + const literals = extractLiteralsFromType(member.type, sf); + if (literals.length > 0) { + interfaceProps[interfaceName][propName] = literals; + } + } + } + } + + ts.forEachChild(node, collectTypes); + } + + collectTypes(sf); + } + + // Phase 2: Extract method options by resolving parameter types + const methodOptions: Record = {}; + + for (const filePath of files) { + const sourceFile = program.getSourceFile(filePath); + if (!sourceFile) continue; + const sf = sourceFile; // Capture for closure + + function extractMethods(node: ts.Node) { + if (ts.isClassDeclaration(node)) { + for (const member of node.members) { + if (ts.isMethodDeclaration(member) && member.name) { + const methodName = member.name.getText(sf); + + for (const param of member.parameters) { + if (!param.type) continue; + + let literals: string[] = []; + + // Direct literal union in parameter + literals = extractLiteralsFromType(param.type, sf); + + // Type reference (e.g., MusicGenre) + if (literals.length === 0 && ts.isTypeReferenceNode(param.type)) { + const refName = param.type.typeName.getText(sf); + if (typeAliases[refName]) { + literals = typeAliases[refName]; + } + } + + // Indexed access type (e.g., AudioTempo['feel']) + if (literals.length === 0 && ts.isIndexedAccessTypeNode(param.type)) { + const objectType = param.type.objectType; + const indexType = param.type.indexType; + + if (ts.isTypeReferenceNode(objectType) && ts.isLiteralTypeNode(indexType)) { + const interfaceName = objectType.typeName.getText(sf); + if (indexType.literal && ts.isStringLiteral(indexType.literal)) { + const propName = indexType.literal.text; + if (interfaceProps[interfaceName]?.[propName]) { + literals = interfaceProps[interfaceName][propName]; + } + } + } + } + + // Union containing type references (e.g., MusicGenre | AudioGenre) + if (literals.length === 0 && ts.isUnionTypeNode(param.type)) { + for (const member of param.type.types) { + if (ts.isTypeReferenceNode(member)) { + const refName = member.typeName.getText(sf); + if (typeAliases[refName]) { + literals.push(...typeAliases[refName]); + } + } + } + } + + if (literals.length > 0) { + // Deduplicate + const uniqueLiterals = [...new Set(literals)]; + if (!methodOptions[methodName] || methodOptions[methodName].length < uniqueLiterals.length) { + methodOptions[methodName] = uniqueLiterals; + } + } + } + } + } + } + + ts.forEachChild(node, extractMethods); + } + + extractMethods(sourceFile); + } + + return methodOptions; +} + +// Generate method options file for Monaco autocomplete +function generateMethodOptions(options: Record): string { + const lines: string[] = []; + + lines.push('/**'); + lines.push(' * Auto-generated method options for Monaco autocomplete'); + lines.push(' * Generated from TypeScript source files via reflection'); + lines.push(' * DO NOT EDIT MANUALLY - run `npm run docs:generate` to regenerate'); + lines.push(' */'); + lines.push(''); + lines.push('export const METHOD_OPTIONS: Record = {'); + + // Collect all method names with their values, avoiding duplicates + const methodMap: Record = {}; + + // Common method name aliases (type name -> method name) + const methodAliases: Record = { + musicGenre: ['genre'], + personaTone: ['tone'], + personaExpertise: ['expertise'], + outputLength: ['length'], + outputStyle: ['style'], + shotType: ['shot'], + cameraAngle: ['angle'], + cameraMovement: ['movement'], + lensType: ['lens'], + lightingType: ['lighting', 'lightingType'], + focusType: ['focus'], + bokehStyle: ['bokeh'], + filterType: ['filter'], + colorPalette: ['palette'], + artStyle: ['medium', 'look', 'artStyle'], + videoPacing: ['pacing'], + videoTransition: ['transition'], + vocalStyle: ['vocalStyle'], + vocalLanguage: ['language'], + weatherLighting: ['weather'], + sensorFormat: ['sensor'], + songSection: ['section'], + }; + + for (const [key, values] of Object.entries(options)) { + if (values.length > 0) { + // Convert type names to likely method names (camelCase, remove 'Type' suffix) + const methodName = key.charAt(0).toLowerCase() + key.slice(1).replace(/Type$/, ''); + + // Keep the longer list if there's a conflict + if (!methodMap[methodName] || methodMap[methodName].length < values.length) { + methodMap[methodName] = values; + } + + // Also add aliases + const aliases = methodAliases[methodName] || []; + for (const alias of aliases) { + if (!methodMap[alias] || methodMap[alias].length < values.length) { + methodMap[alias] = values; + } + } + } + } + + // Sort keys for consistent output + const sortedKeys = Object.keys(methodMap).sort(); + + for (const key of sortedKeys) { + lines.push(` ${JSON.stringify(key)}: ${JSON.stringify(methodMap[key])},`); + } + + lines.push('};'); + lines.push(''); + + return lines.join('\n'); +} + +// Main execution +const srcDir = path.join(__dirname, '../src'); +const outputPath = path.join(__dirname, '../API.md'); +const sidebarOutputPath = path.resolve(__dirname, '../../../src/data/api-docs.ts'); +const typeDefsOutputPath = path.resolve(__dirname, '../../../src/data/type-definitions.ts'); +const methodOptionsOutputPath = path.resolve(__dirname, '../../../src/data/method-options.ts'); + +// Files to parse +const filesToParse = [ + path.join(srcDir, 'variables/index.ts'), + path.join(srcDir, 'similarity/index.ts'), + path.join(srcDir, 'quality/index.ts'), + path.join(srcDir, 'parser/index.ts'), + path.join(srcDir, 'builder/index.ts'), + path.join(srcDir, 'builder/chat.ts'), + path.join(srcDir, 'builder/media.ts'), + path.join(srcDir, 'builder/video.ts'), + path.join(srcDir, 'builder/audio.ts'), +]; + +// Filter to existing files +const existingFiles = filesToParse.filter(f => fs.existsSync(f)); + +// Create TypeScript program +const program = ts.createProgram(existingFiles, { + target: ts.ScriptTarget.ESNext, + module: ts.ModuleKind.ESNext, + strict: true, + esModuleInterop: true, + skipLibCheck: true, +}); + +// Parse each file +const modules: ModuleDoc[] = []; +for (const file of existingFiles) { + try { + const mod = parseSourceFile(file, program); + if (mod.exports.length > 0) { + // Use relative path as module name for clarity + mod.name = path.relative(srcDir, file).replace(/\.ts$/, '').replace(/\\/g, '/'); + modules.push(mod); + } + } catch (error) { + console.error(`Error parsing ${file}:`, error); + } +} + +// Generate and write markdown +const markdown = generateMarkdown(modules); +fs.writeFileSync(outputPath, markdown, 'utf-8'); + +// Generate and write TypeScript sidebar file +const sidebarTS = generateSidebarTS(modules); +// Ensure the data directory exists +const dataDir = path.dirname(sidebarOutputPath); +if (!fs.existsSync(dataDir)) { + fs.mkdirSync(dataDir, { recursive: true }); +} +fs.writeFileSync(sidebarOutputPath, sidebarTS, 'utf-8'); + +// Generate and write TYPE_DEFINITIONS file +const typeDefs = generateTypeDefinitions(modules); +fs.writeFileSync(typeDefsOutputPath, typeDefs, 'utf-8'); + +// Extract string literal options and generate method options file +const stringLiteralOptions = extractStringLiteralOptions(program, existingFiles); +const methodOptionsContent = generateMethodOptions(stringLiteralOptions); +fs.writeFileSync(methodOptionsOutputPath, methodOptionsContent, 'utf-8'); + +console.log(`✅ Generated API documentation: ${outputPath}`); +console.log(`✅ Generated sidebar TypeScript: ${sidebarOutputPath}`); +console.log(`✅ Generated type definitions: ${typeDefsOutputPath}`); +console.log(`✅ Generated method options: ${methodOptionsOutputPath}`); +console.log(` Parsed ${modules.length} modules with ${modules.reduce((acc, m) => acc + m.exports.length, 0)} exports`); +console.log(` Extracted ${Object.keys(stringLiteralOptions).length} string literal types`); diff --git a/scripts/generate-examples.ts b/scripts/generate-examples.ts new file mode 100644 index 00000000..efbb4105 --- /dev/null +++ b/scripts/generate-examples.ts @@ -0,0 +1,34 @@ +import fs from 'fs'; +import path from 'path'; + +const examplesDir = path.join(process.cwd(), 'src/components/ide/examples'); +const outputFile = path.join(examplesDir, 'generated.ts'); + +const examples = [ + { file: 'video.ts', export: 'EXAMPLE_VIDEO' }, + { file: 'audio.ts', export: 'EXAMPLE_AUDIO' }, + { file: 'image.ts', export: 'EXAMPLE_IMAGE' }, + { file: 'chat.ts', export: 'EXAMPLE_CHAT' }, + { file: 'default.ts', export: 'DEFAULT_CODE' }, +]; + +const lines: string[] = [ + '// Auto-generated from example .ts files - DO NOT EDIT MANUALLY', + '// Run: npm run generate:examples to regenerate', + '', +]; + +for (const { file, export: exportName } of examples) { + const content = fs.readFileSync(path.join(examplesDir, file), 'utf-8'); + // Escape backticks and ${} in the content + const escaped = content + .replace(/\\/g, '\\\\') + .replace(/`/g, '\\`') + .replace(/\$\{/g, '\\${'); + + lines.push(`export const ${exportName} = \`${escaped}\`;`); + lines.push(''); +} + +fs.writeFileSync(outputFile, lines.join('\n')); +console.log(`✅ Generated examples: ${outputFile}`); diff --git a/src/app/typed-prompts-editor/page.tsx b/src/app/builder/page.tsx similarity index 100% rename from src/app/typed-prompts-editor/page.tsx rename to src/app/builder/page.tsx diff --git a/src/components/ide/api-details-popup.tsx b/src/components/ide/api-details-popup.tsx new file mode 100644 index 00000000..a33b94fd --- /dev/null +++ b/src/components/ide/api-details-popup.tsx @@ -0,0 +1,103 @@ +"use client"; + +import { X } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; +import { type ApiItem } from "@/data/api-docs"; +import { METHOD_OPTIONS } from "@/data/method-options"; + +interface ApiDetailsPopupProps { + item: ApiItem; + onClose: () => void; +} + +export function ApiDetailsPopup({ item, onClose }: ApiDetailsPopupProps) { + const getTypeColor = (type: ApiItem["type"]) => { + switch (type) { + case "function": return "text-blue-500 dark:text-blue-400"; + case "method": return "text-blue-500 dark:text-blue-400"; + case "class": return "text-yellow-500 dark:text-yellow-400"; + case "interface": return "text-green-500 dark:text-green-400"; + case "type": return "text-purple-500 dark:text-purple-400"; + case "const": return "text-orange-500 dark:text-orange-400"; + default: return "text-muted-foreground"; + } + }; + + // Get method name from item name (strip leading dot and parentheses) + const methodName = item.name.replace(/^\./, '').replace(/\(\)$/, ''); + const availableOptions = METHOD_OPTIONS[methodName]; + + return ( + <> + {/* Backdrop */} +
+ {/* Popup */} +
+
+
+
+
+ {item.type} + {item.name} +
+ {item.signature && ( + {item.signature} + )} +
+ +
+ {item.description && ( +

{item.description}

+ )} + {item.params && item.params.length > 0 && ( +
+

Parameters

+
+ {item.params.map((p) => ( +
+ {p.name} + : {p.type} + {p.description && {p.description}} +
+ ))} +
+
+ )} + {availableOptions && availableOptions.length > 0 && ( +
+

Available Values

+
+ {availableOptions.slice(0, 20).map((opt) => ( + + "{opt}" + + ))} + {availableOptions.length > 20 && ( + +{availableOptions.length - 20} more + )} +
+
+ )} + {item.returns && ( +
+

Returns

+ {item.returns} +
+ )} + {item.example && ( +
+

Example

+
{item.example}
+
+ )} +
+
+ + ); +} diff --git a/src/components/ide/api-docs-sidebar.tsx b/src/components/ide/api-docs-sidebar.tsx new file mode 100644 index 00000000..4d86d8f0 --- /dev/null +++ b/src/components/ide/api-docs-sidebar.tsx @@ -0,0 +1,138 @@ +"use client"; + +import { useState } from "react"; +import { ChevronDown, ChevronRight, Book, Search } from "lucide-react"; +import { Input } from "@/components/ui/input"; +import { ScrollArea } from "@/components/ui/scroll-area"; +import { cn } from "@/lib/utils"; +import { API_DOCS, type ApiItem } from "@/data/api-docs"; + +interface ApiDocsSidebarProps { + selectedItem: ApiItem | null; + onSelectItem: (item: ApiItem | null) => void; +} + +export function ApiDocsSidebar({ selectedItem, onSelectItem }: ApiDocsSidebarProps) { + const [expandedSections, setExpandedSections] = useState>(new Set(["Builder", "PromptBuilder Methods"])); + const [searchQuery, setSearchQuery] = useState(""); + + const toggleSection = (name: string) => { + setExpandedSections(prev => { + const next = new Set(prev); + if (next.has(name)) { + next.delete(name); + } else { + next.add(name); + } + return next; + }); + }; + + const getTypeColor = (type: ApiItem["type"]) => { + switch (type) { + case "function": return "text-blue-500 dark:text-blue-400"; + case "class": return "text-yellow-500 dark:text-yellow-400"; + case "interface": return "text-green-500 dark:text-green-400"; + case "type": return "text-purple-500 dark:text-purple-400"; + case "const": return "text-orange-500 dark:text-orange-400"; + default: return "text-muted-foreground"; + } + }; + + const getTypeLabel = (type: ApiItem["type"]) => { + switch (type) { + case "function": return "fn"; + case "class": return "class"; + case "interface": return "interface"; + case "type": return "type"; + case "const": return "const"; + default: return type; + } + }; + + // Filter sections and items based on search query + const filteredDocs = searchQuery.trim() + ? API_DOCS.map(section => ({ + ...section, + items: section.items.filter(item => + item.name.toLowerCase().includes(searchQuery.toLowerCase()) || + item.description?.toLowerCase().includes(searchQuery.toLowerCase()) || + item.signature?.toLowerCase().includes(searchQuery.toLowerCase()) + ) + })).filter(section => section.items.length > 0) + : API_DOCS; + + // When searching, expand all sections with matches + const effectiveExpandedSections = searchQuery.trim() + ? new Set(filteredDocs.map(s => s.name)) + : expandedSections; + + return ( +
+
+
+ + API Docs +
+
+ + setSearchQuery(e.target.value)} + className="h-7 pl-7 text-sm" + /> +
+
+ +
+ {filteredDocs.length === 0 ? ( +

No results found

+ ) : ( + filteredDocs.map((section) => ( +
+ + {effectiveExpandedSections.has(section.name) && ( +
+ {section.items.map((item) => ( + + ))} +
+ )} +
+ )) + )} +
+
+
+ ); +} diff --git a/src/components/ide/examples/audio.ts b/src/components/ide/examples/audio.ts new file mode 100644 index 00000000..e9361b7b --- /dev/null +++ b/src/components/ide/examples/audio.ts @@ -0,0 +1,64 @@ +import { audio } from 'prompts.chat'; + +// Create a detailed music prompt for Suno/Udio +const prompt = audio() + // Genre - string or object form + .genre("synthwave") + .subgenre("darksynth") + .fusion(["electronic", "ambient"]) + + // Mood - takes primary and spread secondary args + .mood("nostalgic", "mysterious", "hopeful") + .energy("building") + .emotion("bittersweet longing for a retro-futuristic past") + + // Tempo - number or object + .bpm(108) + .tempoMarking("moderato") + .tempoFeel("driving") + + // Vocals + .vocalStyle(["male", "breathy"]) + .language("english") + .lyricsTheme("memories of a neon-lit city that never was") + .delivery("intimate and reflective, slight reverb") + + // Instrumentation - individual methods + .leadInstrument(["synthesizer", "electric-guitar"]) + .rhythmSection(["drums", "bass"]) + .bassInstrument("bass") + .percussion(["drums"]) + .pads(["synthesizer", "strings"]) + .featuredInstrument("synthesizer") + + // Song structure - section by section + .section("intro", 8, "Atmospheric synth pad fade-in") + .section("verse", 16, "Driving beat with vocals") + .section("pre-chorus", 8, "Building tension") + .section("chorus", 16, "Full arrangement, soaring melody") + .section("verse", 16, "Second verse, added elements") + .section("chorus", 16, "Repeat chorus with variations") + .section("bridge", 8, "Breakdown, stripped back") + .section("drop", 16, "Final chorus with extra energy") + .section("outro", 8, "Fade out with reverb tail") + + // Production style + .productionStyle(["polished", "atmospheric", "layered"]) + .era("1980s") + .reference(["The Midnight", "Gunship", "FM-84"]) + .texture("lush and cinematic with analog warmth") + .effects(["heavy reverb on snare", "chorus on guitars", "tape saturation"]) + + // Technical specs + .key("Am") + .timeSignature("4/4") + .duration(210) + + // Style tags - individual or batch + .tag("retrowave") + .tag("outrun") + .tags(["80s nostalgia", "neon", "night drive"]) + + .build(); + +prompt; diff --git a/src/components/ide/examples/chat.ts b/src/components/ide/examples/chat.ts new file mode 100644 index 00000000..2584f5cf --- /dev/null +++ b/src/components/ide/examples/chat.ts @@ -0,0 +1,24 @@ +import { chat } from 'prompts.chat'; + +// Create a chat prompt for conversational AI +const prompt = chat() + // Define the AI's role and expertise + .role("senior software architect") + .tone("professional") + .expertise(["coding", "engineering"]) + + // Set the main task + .task("Review code and provide architectural feedback") + + // Configure reasoning style + .stepByStep() + + // Output format + .json() + + // Response length + .detailed() + + .build(); + +prompt; diff --git a/src/components/ide/examples/default.ts b/src/components/ide/examples/default.ts new file mode 100644 index 00000000..0aa317f9 --- /dev/null +++ b/src/components/ide/examples/default.ts @@ -0,0 +1,21 @@ +import { builder, templates } from 'prompts.chat'; + +// Create a prompt using the fluent builder API +const prompt = builder() + .role("Senior TypeScript Developer") + .context("You are helping review code for a startup") + .task("Analyze the following code for bugs and improvements") + .constraints([ + "Be concise and actionable", + "Focus on critical issues first", + "Suggest modern TypeScript best practices" + ]) + .output("JSON with { bugs: [], suggestions: [], rating: number }") + .variable("code", { required: true, description: "The code to review" }) + .build(); + +// Or use pre-built templates +const translatePrompt = templates.translation("English", "Spanish").build(); + +// Export the main prompt +prompt; diff --git a/src/components/ide/examples/generated.ts b/src/components/ide/examples/generated.ts new file mode 100644 index 00000000..4be98128 --- /dev/null +++ b/src/components/ide/examples/generated.ts @@ -0,0 +1,273 @@ +// Auto-generated from example .ts files - DO NOT EDIT MANUALLY +// Run: npm run generate:examples to regenerate + +export const EXAMPLE_VIDEO = `import { video } from 'prompts.chat'; + +// Create a cinematic video prompt for Sora/Runway +const prompt = video() + // Scene - using individual methods for clarity + .scene("A lone samurai walks through an ancient bamboo forest") + .setting("Feudal Japan, remote mountain region") + .timeOfDay("golden-hour") + .weather("misty") + + // Subject - using object form + .subject({ + main: "A weathered samurai in traditional armor", + appearance: "battle-scarred face, grey streaks in hair tied in topknot", + clothing: "worn black and red yoroi armor, tattered cape flowing behind", + age: "50s", + count: "single" + }) + + // Camera - individual chainable methods + .shot("medium-wide") + .angle("low-angle") + .lens("anamorphic") + .focalLength("35mm") + .movement("tracking") + .cameraSpeed("slow") + .movementDirection("arc-left") + .aperture("f/1.4") + .filmStock("kodak-vision3-500t") + .filmGrain("subtle") + + // Lighting + .lighting({ + type: ["rim", "natural"], + time: "golden-hour", + direction: "back", + intensity: "dramatic" + }) + + // Actions - timed beats in the video + .action("Samurai pauses, hand resting on katana") + .action("Wind picks up, cape billows dramatically") + .action("He turns slowly to face camera") + + // Visual style + .look(["cinematic", "noir"]) + .era("1960s Japanese cinema") + .reference(["Akira Kurosawa", "Roger Deakins"]) + + // Color grading + .palette(["earthy", "muted"]) + .colorAnchors(["deep greens", "warm amber", "shadow blue"]) + .colorGrade("teal and orange with crushed blacks") + + // Audio elements + .ambient("wind rustling through bamboo, distant bird calls") + .diegetic(["footsteps on fallen leaves", "armor clinking softly"]) + .music("solo shakuhachi flute, melancholic melody") + + // Technical specifications + .duration(8) + .resolution("4K") + .fps(24) + .aspectRatio("21:9") + + // Mood and pacing + .mood(["melancholic", "epic", "mysterious"]) + .pacing("slow") + + .build(); + +prompt; +`; + +export const EXAMPLE_AUDIO = `import { audio } from 'prompts.chat'; + +// Create a detailed music prompt for Suno/Udio +const prompt = audio() + // Genre - string or object form + .genre("synthwave") + .subgenre("darksynth") + .fusion(["electronic", "ambient"]) + + // Mood - takes primary and spread secondary args + .mood("nostalgic", "mysterious", "hopeful") + .energy("building") + .emotion("bittersweet longing for a retro-futuristic past") + + // Tempo - number or object + .bpm(108) + .tempoMarking("moderato") + .tempoFeel("driving") + + // Vocals + .vocalStyle(["male", "breathy"]) + .language("english") + .lyricsTheme("memories of a neon-lit city that never was") + .delivery("intimate and reflective, slight reverb") + + // Instrumentation - individual methods + .leadInstrument(["synthesizer", "electric-guitar"]) + .rhythmSection(["drums", "bass"]) + .bassInstrument("bass") + .percussion(["drums"]) + .pads(["synthesizer", "strings"]) + .featuredInstrument("synthesizer") + + // Song structure - section by section + .section("intro", 8, "Atmospheric synth pad fade-in") + .section("verse", 16, "Driving beat with vocals") + .section("pre-chorus", 8, "Building tension") + .section("chorus", 16, "Full arrangement, soaring melody") + .section("verse", 16, "Second verse, added elements") + .section("chorus", 16, "Repeat chorus with variations") + .section("bridge", 8, "Breakdown, stripped back") + .section("drop", 16, "Final chorus with extra energy") + .section("outro", 8, "Fade out with reverb tail") + + // Production style + .productionStyle(["polished", "atmospheric", "layered"]) + .era("1980s") + .reference(["The Midnight", "Gunship", "FM-84"]) + .texture("lush and cinematic with analog warmth") + .effects(["heavy reverb on snare", "chorus on guitars", "tape saturation"]) + + // Technical specs + .key("Am") + .timeSignature("4/4") + .duration(210) + + // Style tags - individual or batch + .tag("retrowave") + .tag("outrun") + .tags(["80s nostalgia", "neon", "night drive"]) + + .build(); + +prompt; +`; + +export const EXAMPLE_IMAGE = `import { image } from 'prompts.chat'; + +// Create a detailed image prompt for Midjourney/DALL-E/Stable Diffusion +const prompt = image() + // Main subject - string or object form + .subject("An ancient library hidden inside a giant hollow tree") + .subjectDetails([ + "thousands of leather-bound books on curved wooden shelves", + "spiral staircase winding up through the center", + "glowing fireflies floating between bookshelves", + "worn reading chairs with velvet cushions" + ]) + .pose("majestic interior view") + .expression("magical and inviting atmosphere") + + // Environment - string or object form + .environment("interior of a massive ancient oak tree") + .location("enchanted forest, hidden realm") + .atmosphere("mystical, warm and cozy") + .season("autumn") + .props([ + "scattered scrolls and quills on oak desks", + "mystical runes carved into bark walls", + "mushrooms glowing softly in corners" + ]) + + // Camera - individual chainable methods + .angle("low-angle") + .shot("wide") + .lens("wide-angle") + .focalLength("24mm") + .focus("deep") + .cameraBrand("hasselblad") + .sensor("medium-format") + .aperture("f/8") + + // Lighting - object or individual methods + .lightingType(["practical", "rim"]) + .timeOfDay("twilight") + .lightDirection("three-quarter") + .lightIntensity("soft") + + // Composition - object or individual methods + .goldenRatio() + .foreground("scattered books and scrolls") + .midground("spiral staircase with warm glow") + .background("small windows showing starlit forest") + + // Art style + .medium("digital-art") + .artist(["Greg Rutkowski", "Thomas Kinkade", "Studio Ghibli"]) + .influence(["Art Nouveau", "cottage core aesthetic"]) + + // Color palette + .palette(["warm", "earthy"]) + .primaryColors(["amber", "deep brown", "forest green"]) + .accentColors(["soft gold", "moonlight blue", "fairy pink"]) + .colorGrade("rich saturation with deep shadows") + + // Mood + .mood(["serene", "peaceful", "nostalgic", "whimsical"]) + + // Technical specifications + .aspectRatio("3:2") + .resolution("8K") + .quality("masterpiece") + + // Negative prompt - takes array + .negative([ + "blurry", "low quality", "bad anatomy", "watermark", + "text", "signature", "modern elements", "plastic", + "harsh lighting", "overexposed", "underexposed" + ]) + + // Custom additions + .custom("volumetric lighting, ray tracing, octane render") + + .build(); + +prompt; +`; + +export const EXAMPLE_CHAT = `import { chat } from 'prompts.chat'; + +// Create a chat prompt for conversational AI +const prompt = chat() + // Define the AI's role and expertise + .role("senior software architect") + .tone("professional") + .expertise(["coding", "engineering"]) + + // Set the main task + .task("Review code and provide architectural feedback") + + // Configure reasoning style + .stepByStep() + + // Output format + .json() + + // Response length + .detailed() + + .build(); + +prompt; +`; + +export const DEFAULT_CODE = `import { builder, templates } from 'prompts.chat'; + +// Create a prompt using the fluent builder API +const prompt = builder() + .role("Senior TypeScript Developer") + .context("You are helping review code for a startup") + .task("Analyze the following code for bugs and improvements") + .constraints([ + "Be concise and actionable", + "Focus on critical issues first", + "Suggest modern TypeScript best practices" + ]) + .output("JSON with { bugs: [], suggestions: [], rating: number }") + .variable("code", { required: true, description: "The code to review" }) + .build(); + +// Or use pre-built templates +const translatePrompt = templates.translation("English", "Spanish").build(); + +// Export the main prompt +prompt; +`; diff --git a/src/components/ide/examples/image.ts b/src/components/ide/examples/image.ts new file mode 100644 index 00000000..c82d8405 --- /dev/null +++ b/src/components/ide/examples/image.ts @@ -0,0 +1,80 @@ +import { image } from 'prompts.chat'; + +// Create a detailed image prompt for Midjourney/DALL-E/Stable Diffusion +const prompt = image() + // Main subject - string or object form + .subject("An ancient library hidden inside a giant hollow tree") + .subjectDetails([ + "thousands of leather-bound books on curved wooden shelves", + "spiral staircase winding up through the center", + "glowing fireflies floating between bookshelves", + "worn reading chairs with velvet cushions" + ]) + .pose("majestic interior view") + .expression("magical and inviting atmosphere") + + // Environment - string or object form + .environment("interior of a massive ancient oak tree") + .location("enchanted forest, hidden realm") + .atmosphere("mystical, warm and cozy") + .season("autumn") + .props([ + "scattered scrolls and quills on oak desks", + "mystical runes carved into bark walls", + "mushrooms glowing softly in corners" + ]) + + // Camera - individual chainable methods + .angle("low-angle") + .shot("wide") + .lens("wide-angle") + .focalLength("24mm") + .focus("deep") + .cameraBrand("hasselblad") + .sensor("medium-format") + .aperture("f/8") + + // Lighting - object or individual methods + .lightingType(["practical", "rim"]) + .timeOfDay("twilight") + .lightDirection("three-quarter") + .lightIntensity("soft") + + // Composition - object or individual methods + .goldenRatio() + .foreground("scattered books and scrolls") + .midground("spiral staircase with warm glow") + .background("small windows showing starlit forest") + + // Art style + .medium("digital-art") + .artist(["Greg Rutkowski", "Thomas Kinkade", "Studio Ghibli"]) + .influence(["Art Nouveau", "cottage core aesthetic"]) + + // Color palette + .palette(["warm", "earthy"]) + .primaryColors(["amber", "deep brown", "forest green"]) + .accentColors(["soft gold", "moonlight blue", "fairy pink"]) + .colorGrade("rich saturation with deep shadows") + + // Mood + .mood(["serene", "peaceful", "nostalgic", "whimsical"]) + + // Technical specifications + .aspectRatio("3:2") + .resolution("8K") + .quality("masterpiece") + + // Negative prompt - takes array + .negative([ + "blurry", "low quality", "bad anatomy", "watermark", + "text", "signature", "modern elements", "plastic", + "harsh lighting", "overexposed", "underexposed" + ]) + + // Custom additions + .custom("volumetric lighting, ray tracing, octane render") + + .build(); + +prompt; diff --git a/src/components/ide/examples/index.ts b/src/components/ide/examples/index.ts new file mode 100644 index 00000000..c1478966 --- /dev/null +++ b/src/components/ide/examples/index.ts @@ -0,0 +1,8 @@ +// Re-export from generated file +export { + EXAMPLE_VIDEO, + EXAMPLE_AUDIO, + EXAMPLE_IMAGE, + EXAMPLE_CHAT, + DEFAULT_CODE, +} from './generated'; diff --git a/src/components/ide/examples/video.ts b/src/components/ide/examples/video.ts new file mode 100644 index 00000000..26989ec6 --- /dev/null +++ b/src/components/ide/examples/video.ts @@ -0,0 +1,72 @@ +import { video } from 'prompts.chat'; + +// Create a cinematic video prompt for Sora/Runway +const prompt = video() + // Scene - using individual methods for clarity + .scene("A lone samurai walks through an ancient bamboo forest") + .setting("Feudal Japan, remote mountain region") + .timeOfDay("golden-hour") + .weather("misty") + + // Subject - using object form + .subject({ + main: "A weathered samurai in traditional armor", + appearance: "battle-scarred face, grey streaks in hair tied in topknot", + clothing: "worn black and red yoroi armor, tattered cape flowing behind", + age: "50s", + count: "single" + }) + + // Camera - individual chainable methods + .shot("medium-wide") + .angle("low-angle") + .lens("anamorphic") + .focalLength("35mm") + .movement("tracking") + .cameraSpeed("slow") + .movementDirection("arc-left") + .aperture("f/1.4") + .filmStock("kodak-vision3-500t") + .filmGrain("subtle") + + // Lighting + .lighting({ + type: ["rim", "natural"], + time: "golden-hour", + direction: "back", + intensity: "dramatic" + }) + + // Actions - timed beats in the video + .action("Samurai pauses, hand resting on katana") + .action("Wind picks up, cape billows dramatically") + .action("He turns slowly to face camera") + + // Visual style + .look(["cinematic", "noir"]) + .era("1960s Japanese cinema") + .reference(["Akira Kurosawa", "Roger Deakins"]) + + // Color grading + .palette(["earthy", "muted"]) + .colorAnchors(["deep greens", "warm amber", "shadow blue"]) + .colorGrade("teal and orange with crushed blacks") + + // Audio elements + .ambient("wind rustling through bamboo, distant bird calls") + .diegetic(["footsteps on fallen leaves", "armor clinking softly"]) + .music("solo shakuhachi flute, melancholic melody") + + // Technical specifications + .duration(8) + .resolution("4K") + .fps(24) + .aspectRatio("21:9") + + // Mood and pacing + .mood(["melancholic", "epic", "mysterious"]) + .pacing("slow") + + .build(); + +prompt; diff --git a/src/components/ide/prompt-ide.tsx b/src/components/ide/prompt-ide.tsx index 624ba84b..e6003c90 100644 --- a/src/components/ide/prompt-ide.tsx +++ b/src/components/ide/prompt-ide.tsx @@ -6,11 +6,8 @@ import Editor from "@monaco-editor/react"; import { useTheme } from "next-themes"; import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Button } from "@/components/ui/button"; -import { Copy, Play, RotateCcw, Code2, FileJson, FileText, Book, ChevronDown, ChevronRight, Video, Music, Image, X, MessageSquare, Search } from "lucide-react"; -import { Input } from "@/components/ui/input"; -import { ScrollArea } from "@/components/ui/scroll-area"; +import { Copy, Play, RotateCcw, Code2, FileJson, FileText, Video, Music, Image as ImageIcon, MessageSquare } from "lucide-react"; import { toast } from "sonner"; -import { cn } from "@/lib/utils"; // Import the actual prompts.chat library import { @@ -28,1335 +25,25 @@ import { parser, } from "prompts.chat"; -type OutputFormat = "json" | "yaml" | "markdown"; +// Import auto-generated type definitions and method options for Monaco +import { type ApiItem } from "@/data/api-docs"; +import { TYPE_DEFINITIONS } from "@/data/type-definitions"; +import { METHOD_OPTIONS } from "@/data/method-options"; -interface ApiSection { - name: string; - items: ApiItem[]; -} +// Import separated components +import { ApiDocsSidebar } from "./api-docs-sidebar"; +import { ApiDetailsPopup } from "./api-details-popup"; +import { toYaml } from "./utils"; +import { type OutputFormat } from "./types"; -interface ApiItem { - name: string; - type: "function" | "class" | "type" | "interface" | "const"; - signature?: string; - description?: string; - example?: string; - returns?: string; - params?: { name: string; type: string; description: string }[]; -} - -const EXAMPLE_VIDEO = `import { video } from 'prompts.chat'; - -// Create a cinematic video prompt for Sora/Runway -const prompt = video() - // Scene - using individual methods for clarity - .scene("A lone samurai walks through an ancient bamboo forest") - .setting("Feudal Japan, remote mountain region") - .timeOfDay("golden-hour") - .weather("misty") - - // Subject - using object form - .subject({ - main: "A weathered samurai in traditional armor", - appearance: "battle-scarred face, grey streaks in hair tied in topknot", - clothing: "worn black and red yoroi armor, tattered cape flowing behind", - age: "50s", - count: "single" - }) - - // Camera - individual chainable methods - .shot("medium-wide") - .angle("low-angle") - .lens("anamorphic") - .focalLength("35mm") - .movement("tracking") - .cameraSpeed("slow") - .movementDirection("arc-left") - .aperture("f/1.4") - .filmStock("kodak-vision3-500t") - .filmGrain("subtle") - - // Lighting - .lighting({ - type: ["rim", "natural"], - time: "golden-hour", - direction: "back", - intensity: "dramatic" - }) - - // Actions - timed beats in the video - .action("Samurai pauses, hand resting on katana") - .action("Wind picks up, cape billows dramatically") - .action("He turns slowly to face camera") - - // Visual style - .look(["cinematic", "noir"]) - .era("1960s Japanese cinema") - .reference(["Akira Kurosawa", "Roger Deakins"]) - - // Color grading - .palette(["earthy", "muted"]) - .colorAnchors(["deep greens", "warm amber", "shadow blue"]) - .colorGrade("teal and orange with crushed blacks") - - // Audio elements - .ambient("wind rustling through bamboo, distant bird calls") - .diegetic(["footsteps on fallen leaves", "armor clinking softly"]) - .music("solo shakuhachi flute, melancholic melody") - - // Technical specifications - .duration(8) - .resolution("4K") - .fps(24) - .aspectRatio("21:9") - - // Mood and pacing - .mood(["melancholic", "epic", "mysterious"]) - .pacing("slow") - - .build(); - -prompt; -`; - -const EXAMPLE_AUDIO = `import { audio } from 'prompts.chat'; - -// Create a detailed music prompt for Suno/Udio -const prompt = audio() - // Genre - string or object form - .genre("synthwave") - .subgenre("darksynth") - .fusion(["electronic", "ambient"]) - - // Mood - takes primary and spread secondary args - .mood("nostalgic", "mysterious", "hopeful") - .energy("building") - .emotion("bittersweet longing for a retro-futuristic past") - - // Tempo - number or object - .bpm(108) - .tempoMarking("moderato") - .tempoFeel("driving") - - // Vocals - .vocalStyle(["male", "breathy"]) - .language("english") - .lyricsTheme("memories of a neon-lit city that never was") - .delivery("intimate and reflective, slight reverb") - - // Instrumentation - individual methods - .leadInstrument(["synthesizer", "electric-guitar"]) - .rhythmSection(["drums", "bass"]) - .bassInstrument("bass") - .percussion(["drums"]) - .pads(["synthesizer", "strings"]) - .featuredInstrument("synthesizer") - - // Song structure - section by section - .section("intro", 8, "Atmospheric synth pad fade-in") - .section("verse", 16, "Driving beat with vocals") - .section("pre-chorus", 8, "Building tension") - .section("chorus", 16, "Full arrangement, soaring melody") - .section("verse", 16, "Second verse, added elements") - .section("chorus", 16, "Repeat chorus with variations") - .section("bridge", 8, "Breakdown, stripped back") - .section("drop", 16, "Final chorus with extra energy") - .section("outro", 8, "Fade out with reverb tail") - - // Production style - .productionStyle(["polished", "atmospheric", "layered"]) - .era("1980s") - .reference(["The Midnight", "Gunship", "FM-84"]) - .texture("lush and cinematic with analog warmth") - .effects(["heavy reverb on snare", "chorus on guitars", "tape saturation"]) - - // Technical specs - .key("Am") - .timeSignature("4/4") - .duration(210) - - // Style tags - individual or batch - .tag("retrowave") - .tag("outrun") - .tags(["80s nostalgia", "neon", "night drive"]) - - .build(); - -prompt; -`; - -const EXAMPLE_IMAGE = `import { image } from 'prompts.chat'; - -// Create a detailed image prompt for Midjourney/DALL-E/Stable Diffusion -const prompt = image() - // Main subject - string or object form - .subject("An ancient library hidden inside a giant hollow tree") - .subjectDetails([ - "thousands of leather-bound books on curved wooden shelves", - "spiral staircase winding up through the center", - "glowing fireflies floating between bookshelves", - "worn reading chairs with velvet cushions" - ]) - .pose("majestic interior view") - .expression("magical and inviting atmosphere") - - // Environment - string or object form - .environment("interior of a massive ancient oak tree") - .location("enchanted forest, hidden realm") - .atmosphere("mystical, warm and cozy") - .season("autumn") - .props([ - "scattered scrolls and quills on oak desks", - "mystical runes carved into bark walls", - "mushrooms glowing softly in corners" - ]) - - // Camera - individual chainable methods - .angle("low-angle") - .shot("wide") - .lens("wide-angle") - .focalLength("24mm") - .focus("deep") - .cameraBrand("hasselblad") - .sensor("medium-format") - .aperture("f/8") - - // Lighting - object or individual methods - .lightingType(["practical", "rim"]) - .timeOfDay("twilight") - .lightDirection("three-quarter") - .lightIntensity("soft") - - // Composition - object or individual methods - .goldenRatio() - .foreground("scattered books and scrolls") - .midground("spiral staircase with warm glow") - .background("small windows showing starlit forest") - - // Art style - .medium("digital-art") - .artist(["Greg Rutkowski", "Thomas Kinkade", "Studio Ghibli"]) - .influence(["Art Nouveau", "cottage core aesthetic"]) - - // Color palette - .palette(["warm", "earthy"]) - .primaryColors(["amber", "deep brown", "forest green"]) - .accentColors(["soft gold", "moonlight blue", "fairy pink"]) - .colorGrade("rich saturation with deep shadows") - - // Mood - .mood(["serene", "peaceful", "nostalgic", "whimsical"]) - - // Technical specifications - .aspectRatio("3:2") - .resolution("8K") - .quality("masterpiece") - - // Negative prompt - takes array - .negative([ - "blurry", "low quality", "bad anatomy", "watermark", - "text", "signature", "modern elements", "plastic", - "harsh lighting", "overexposed", "underexposed" - ]) - - // Custom additions - .custom("volumetric lighting, ray tracing, octane render") - - .build(); - -prompt; -`; - -const EXAMPLE_CHAT = `import { chat } from 'prompts.chat'; - -// Create a chat prompt for conversational AI -const prompt = chat() - // Define the AI's role and expertise - .role("senior software architect") - .tone("professional") - .expertise("TypeScript", "React", "Node.js", "System Design") - - // Set the main task - .task("Review code and provide architectural feedback") - - // Configure reasoning style - .stepByStep() - - // Output format - .json() - - // Response length - .detailed() - - .build(); - -prompt; -`; - -const API_DOCS: ApiSection[] = [ - // ============================================================================ - // TEXT PROMPTS - // ============================================================================ - { - name: "Text Prompts", - items: [ - { name: "builder()", type: "function", signature: "builder(): PromptBuilder", description: "Create a new prompt builder" }, - { name: "fromPrompt()", type: "function", signature: "fromPrompt(content: string): PromptBuilder", description: "Create builder from existing prompt" }, - { name: ".role()", type: "function", signature: "role(role: string): this", description: "Set AI persona/role" }, - { name: ".context()", type: "function", signature: "context(ctx: string): this", description: "Set background context" }, - { name: ".task()", type: "function", signature: "task(task: string): this", description: "Set main instruction" }, - { name: ".constraints()", type: "function", signature: "constraints(c: string[]): this", description: "Add rules/constraints" }, - { name: ".output()", type: "function", signature: "output(format: string): this", description: "Set output format" }, - { name: ".example()", type: "function", signature: "example(in: string, out: string): this", description: "Add input/output example" }, - { name: ".variable()", type: "function", signature: "variable(name: string, opts?): this", description: "Define a placeholder variable" }, - { name: ".section()", type: "function", signature: "section(title: string, content: string): this", description: "Add custom section" }, - { name: ".build()", type: "function", signature: "build(): BuiltPrompt", description: "Build the final prompt" }, - ], - }, - { - name: "Templates", - items: [ - { name: "templates.codeReview()", type: "function", signature: "codeReview(opts?): PromptBuilder", description: "Code review template" }, - { name: "templates.translation()", type: "function", signature: "translation(from, to): PromptBuilder", description: "Translation template" }, - { name: "templates.summarize()", type: "function", signature: "summarize(opts?): PromptBuilder", description: "Summarization template" }, - { name: "templates.qa()", type: "function", signature: "qa(context?): PromptBuilder", description: "Q&A template" }, - ], - }, - // ============================================================================ - // CHAT PROMPTS - // ============================================================================ - { - name: "Chat: Messages", - items: [ - { name: "chat()", type: "function", signature: "chat(): ChatPromptBuilder", description: "Create chat prompt builder" }, - { name: ".system()", type: "function", signature: "system(content: string): this", description: "Set system message" }, - { name: ".user()", type: "function", signature: "user(content, name?): this", description: "Add user message" }, - { name: ".assistant()", type: "function", signature: "assistant(content: string): this", description: "Add assistant message" }, - { name: ".messages()", type: "function", signature: "messages(msgs[]): this", description: "Add multiple messages" }, - { name: ".conversation()", type: "function", signature: "conversation(turns[]): this", description: "Add conversation turns" }, - ], - }, - { - name: "Chat: Persona", - items: [ - { name: ".persona()", type: "function", signature: "persona(settings | string): this", description: "Set full persona" }, - { name: ".role()", type: "function", signature: "role(role: string): this", description: "Set AI role" }, - { name: ".tone()", type: "function", signature: "tone(tone): this", description: "Set tone(s)" }, - { name: ".expertise()", type: "function", signature: "expertise(areas): this", description: "Set expertise areas" }, - { name: ".personality()", type: "function", signature: "personality(traits[]): this", description: "Set personality traits" }, - { name: ".background()", type: "function", signature: "background(bg: string): this", description: "Set background info" }, - { name: ".speakAs()", type: "function", signature: "speakAs(name: string): this", description: "Set persona name" }, - ], - }, - { - name: "Chat: Context", - items: [ - { name: ".context()", type: "function", signature: "context(settings | string): this", description: "Set full context" }, - { name: ".domain()", type: "function", signature: "domain(domain: string): this", description: "Set knowledge domain" }, - { name: ".audience()", type: "function", signature: "audience(audience: string): this", description: "Set target audience" }, - { name: ".constraints()", type: "function", signature: "constraints(c[]): this", description: "Add constraints" }, - { name: ".knowledge()", type: "function", signature: "knowledge(facts[]): this", description: "Set known facts" }, - ], - }, - { - name: "Chat: Task", - items: [ - { name: ".task()", type: "function", signature: "task(instruction | ChatTask): this", description: "Set task" }, - { name: ".steps()", type: "function", signature: "steps(steps[]): this", description: "Set task steps" }, - { name: ".deliverables()", type: "function", signature: "deliverables(d[]): this", description: "Set deliverables" }, - { name: ".criteria()", type: "function", signature: "criteria(criteria[]): this", description: "Set success criteria" }, - { name: ".avoid()", type: "function", signature: "avoid(antiPatterns[]): this", description: "Set anti-patterns" }, - ], - }, - { - name: "Chat: Output", - items: [ - { name: ".json()", type: "function", signature: "json(schema?): this", description: "JSON output" }, - { name: ".jsonSchema()", type: "function", signature: "jsonSchema(name, schema): this", description: "JSON with schema" }, - { name: ".markdown()", type: "function", signature: "markdown(): this", description: "Markdown output" }, - { name: ".code()", type: "function", signature: "code(language?): this", description: "Code output" }, - { name: ".brief()", type: "function", signature: "brief(): this", description: "Brief output" }, - { name: ".detailed()", type: "function", signature: "detailed(): this", description: "Detailed output" }, - { name: ".comprehensive()", type: "function", signature: "comprehensive(): this", description: "Comprehensive output" }, - { name: ".withExamples()", type: "function", signature: "withExamples(): this", description: "Include examples" }, - { name: ".withSources()", type: "function", signature: "withSources(): this", description: "Cite sources" }, - ], - }, - { - name: "Chat: Reasoning", - items: [ - { name: ".stepByStep()", type: "function", signature: "stepByStep(): this", description: "Step-by-step reasoning" }, - { name: ".chainOfThought()", type: "function", signature: "chainOfThought(): this", description: "Chain-of-thought" }, - { name: ".treeOfThought()", type: "function", signature: "treeOfThought(): this", description: "Tree-of-thought" }, - { name: ".firstPrinciples()", type: "function", signature: "firstPrinciples(): this", description: "First principles" }, - { name: ".devilsAdvocate()", type: "function", signature: "devilsAdvocate(): this", description: "Devil's advocate" }, - { name: ".showWork()", type: "function", signature: "showWork(): this", description: "Show reasoning" }, - { name: ".verifyAnswer()", type: "function", signature: "verifyAnswer(): this", description: "Verify answer" }, - ], - }, - { - name: "Chat: Presets", - items: [ - { name: "chatPresets.coder()", type: "function", signature: "coder(lang?): ChatPromptBuilder", description: "Expert coder" }, - { name: "chatPresets.writer()", type: "function", signature: "writer(style?): ChatPromptBuilder", description: "Writer assistant" }, - { name: "chatPresets.tutor()", type: "function", signature: "tutor(subject?): ChatPromptBuilder", description: "Patient tutor" }, - { name: "chatPresets.analyst()", type: "function", signature: "analyst(): ChatPromptBuilder", description: "Data analyst" }, - { name: "chatPresets.socratic()", type: "function", signature: "socratic(): ChatPromptBuilder", description: "Socratic teacher" }, - { name: "chatPresets.summarizer()", type: "function", signature: "summarizer(len?): ChatPromptBuilder", description: "Summarizer" }, - { name: "chatPresets.translator()", type: "function", signature: "translator(lang): ChatPromptBuilder", description: "Translator" }, - ], - }, - // ============================================================================ - // MEDIA: IMAGE - // ============================================================================ - { - name: "Image: Subject", - items: [ - { name: "image()", type: "function", signature: "image(): ImagePromptBuilder", description: "Create image prompt builder" }, - { name: ".subject()", type: "function", signature: "subject(main | ImageSubject): this", description: "Set main subject" }, - { name: ".subjectDetails()", type: "function", signature: "subjectDetails(details[]): this", description: "Add subject details" }, - { name: ".expression()", type: "function", signature: "expression(expr: string): this", description: "Set facial expression" }, - { name: ".pose()", type: "function", signature: "pose(pose: string): this", description: "Set body pose" }, - { name: ".clothing()", type: "function", signature: "clothing(clothing: string): this", description: "Set clothing" }, - ], - }, - { - name: "Image: Environment", - items: [ - { name: ".environment()", type: "function", signature: "environment(setting | ImageEnv): this", description: "Set environment" }, - { name: ".location()", type: "function", signature: "location(location: string): this", description: "Set location" }, - { name: ".props()", type: "function", signature: "props(props[]): this", description: "Set scene props" }, - { name: ".atmosphere()", type: "function", signature: "atmosphere(atm: string): this", description: "Set atmosphere" }, - { name: ".season()", type: "function", signature: "season(season): this", description: "Set season" }, - ], - }, - { - name: "Image: Camera", - items: [ - { name: ".camera()", type: "function", signature: "camera(settings): this", description: "Set all camera settings" }, - { name: ".shot()", type: "function", signature: "shot(shot: ShotType): this", description: "Set shot type" }, - { name: ".angle()", type: "function", signature: "angle(angle: CameraAngle): this", description: "Set camera angle" }, - { name: ".lens()", type: "function", signature: "lens(lens: LensType): this", description: "Set lens type" }, - { name: ".focus()", type: "function", signature: "focus(focus: FocusType): this", description: "Set focus type" }, - { name: ".aperture()", type: "function", signature: "aperture(aperture: string): this", description: "Set aperture" }, - { name: ".bokeh()", type: "function", signature: "bokeh(style: BokehStyle): this", description: "Set bokeh style" }, - { name: ".filmStock()", type: "function", signature: "filmStock(stock: FilmStock): this", description: "Set film stock" }, - ], - }, - { - name: "Image: Lighting", - items: [ - { name: ".lighting()", type: "function", signature: "lighting(settings): this", description: "Set all lighting" }, - { name: ".lightingType()", type: "function", signature: "lightingType(type): this", description: "Set lighting type(s)" }, - { name: ".timeOfDay()", type: "function", signature: "timeOfDay(time: TimeOfDay): this", description: "Set time of day" }, - { name: ".weather()", type: "function", signature: "weather(weather): this", description: "Set weather" }, - { name: ".lightDirection()", type: "function", signature: "lightDirection(dir): this", description: "Set light direction" }, - ], - }, - { - name: "Image: Composition", - items: [ - { name: ".composition()", type: "function", signature: "composition(settings): this", description: "Set all composition" }, - { name: ".ruleOfThirds()", type: "function", signature: "ruleOfThirds(): this", description: "Enable rule of thirds" }, - { name: ".goldenRatio()", type: "function", signature: "goldenRatio(): this", description: "Enable golden ratio" }, - { name: ".foreground()", type: "function", signature: "foreground(fg: string): this", description: "Set foreground" }, - { name: ".background()", type: "function", signature: "background(bg: string): this", description: "Set background" }, - ], - }, - { - name: "Image: Style", - items: [ - { name: ".style()", type: "function", signature: "style(settings): this", description: "Set all style" }, - { name: ".medium()", type: "function", signature: "medium(medium: ArtStyle): this", description: "Set art medium" }, - { name: ".artist()", type: "function", signature: "artist(artist): this", description: "Reference artist(s)" }, - { name: ".influence()", type: "function", signature: "influence(influences[]): this", description: "Set style influences" }, - { name: ".palette()", type: "function", signature: "palette(palette): this", description: "Set color palette" }, - { name: ".primaryColors()", type: "function", signature: "primaryColors(colors[]): this", description: "Set primary colors" }, - { name: ".colorGrade()", type: "function", signature: "colorGrade(grade: string): this", description: "Set color grade" }, - { name: ".mood()", type: "function", signature: "mood(mood): this", description: "Set mood(s)" }, - { name: ".negative()", type: "function", signature: "negative(items[]): this", description: "Negative prompts" }, - { name: ".build()", type: "function", signature: "build(): BuiltImagePrompt", description: "Build the prompt" }, - ], - }, - // ============================================================================ - // MEDIA: VIDEO - // ============================================================================ - { - name: "Video: Scene", - items: [ - { name: "video()", type: "function", signature: "video(): VideoPromptBuilder", description: "Create video prompt builder" }, - { name: ".scene()", type: "function", signature: "scene(desc | VideoScene): this", description: "Set scene description" }, - { name: ".setting()", type: "function", signature: "setting(setting: string): this", description: "Set location/setting" }, - { name: ".subject()", type: "function", signature: "subject(main | VideoSubject): this", description: "Set main subject" }, - { name: ".appearance()", type: "function", signature: "appearance(app: string): this", description: "Set appearance" }, - { name: ".clothing()", type: "function", signature: "clothing(clothing: string): this", description: "Set clothing" }, - ], - }, - { - name: "Video: Camera", - items: [ - { name: ".camera()", type: "function", signature: "camera(settings): this", description: "Set all camera settings" }, - { name: ".shot()", type: "function", signature: "shot(shot: ShotType): this", description: "Set shot type" }, - { name: ".angle()", type: "function", signature: "angle(angle: CameraAngle): this", description: "Set camera angle" }, - { name: ".movement()", type: "function", signature: "movement(movement): this", description: "Set camera movement" }, - { name: ".lens()", type: "function", signature: "lens(lens: LensType): this", description: "Set lens type" }, - { name: ".platform()", type: "function", signature: "platform(platform): this", description: "Set camera platform" }, - { name: ".cameraSpeed()", type: "function", signature: "cameraSpeed(speed): this", description: "Set movement speed" }, - { name: ".filmStock()", type: "function", signature: "filmStock(stock): this", description: "Set film stock" }, - { name: ".filmGrain()", type: "function", signature: "filmGrain(grain): this", description: "Set film grain" }, - ], - }, - { - name: "Video: Action", - items: [ - { name: ".action()", type: "function", signature: "action(action, opts?): this", description: "Add single action" }, - { name: ".actions()", type: "function", signature: "actions(actions[]): this", description: "Add multiple actions" }, - { name: ".motion()", type: "function", signature: "motion(settings): this", description: "Set motion settings" }, - { name: ".motionBeats()", type: "function", signature: "motionBeats(beats[]): this", description: "Set motion beats" }, - ], - }, - { - name: "Video: Style", - items: [ - { name: ".style()", type: "function", signature: "style(settings): this", description: "Set all style" }, - { name: ".look()", type: "function", signature: "look(look: ArtStyle): this", description: "Set visual look" }, - { name: ".era()", type: "function", signature: "era(era: string): this", description: "Set era/period" }, - { name: ".reference()", type: "function", signature: "reference(refs[]): this", description: "Set reference films" }, - { name: ".palette()", type: "function", signature: "palette(palette): this", description: "Set color palette" }, - { name: ".colorGrade()", type: "function", signature: "colorGrade(grade: string): this", description: "Set color grade" }, - { name: ".lighting()", type: "function", signature: "lighting(settings): this", description: "Set lighting" }, - { name: ".timeOfDay()", type: "function", signature: "timeOfDay(time): this", description: "Set time of day" }, - ], - }, - { - name: "Video: Audio", - items: [ - { name: ".audio()", type: "function", signature: "audio(settings): this", description: "Set all audio" }, - { name: ".dialogue()", type: "function", signature: "dialogue(dialogue: string): this", description: "Set dialogue" }, - { name: ".ambient()", type: "function", signature: "ambient(ambient: string): this", description: "Set ambient sound" }, - { name: ".diegetic()", type: "function", signature: "diegetic(sounds[]): this", description: "Set diegetic sounds" }, - { name: ".music()", type: "function", signature: "music(music: string): this", description: "Set music" }, - ], - }, - { - name: "Video: Technical", - items: [ - { name: ".duration()", type: "function", signature: "duration(seconds: number): this", description: "Set duration" }, - { name: ".resolution()", type: "function", signature: "resolution(res): this", description: "Set resolution" }, - { name: ".fps()", type: "function", signature: "fps(fps): this", description: "Set frame rate" }, - { name: ".aspectRatio()", type: "function", signature: "aspectRatio(ratio): this", description: "Set aspect ratio" }, - { name: ".mood()", type: "function", signature: "mood(mood): this", description: "Set mood(s)" }, - { name: ".pacing()", type: "function", signature: "pacing(pacing): this", description: "Set pacing" }, - { name: ".build()", type: "function", signature: "build(): BuiltVideoPrompt", description: "Build the prompt" }, - ], - }, - // ============================================================================ - // MEDIA: AUDIO - // ============================================================================ - { - name: "Audio: Genre", - items: [ - { name: "audio()", type: "function", signature: "audio(): AudioPromptBuilder", description: "Create audio prompt builder" }, - { name: ".genre()", type: "function", signature: "genre(primary: MusicGenre): this", description: "Set primary genre" }, - { name: ".subgenre()", type: "function", signature: "subgenre(sub: string): this", description: "Set subgenre" }, - { name: ".fusion()", type: "function", signature: "fusion(genres[]): this", description: "Blend multiple genres" }, - ], - }, - { - name: "Audio: Mood", - items: [ - { name: ".mood()", type: "function", signature: "mood(primary, ...more): this", description: "Set moods (variadic)" }, - { name: ".energy()", type: "function", signature: "energy(level): this", description: "Set energy level" }, - { name: ".emotion()", type: "function", signature: "emotion(emotion: string): this", description: "Set emotion" }, - ], - }, - { - name: "Audio: Tempo", - items: [ - { name: ".tempo()", type: "function", signature: "tempo(bpm | AudioTempo): this", description: "Set tempo" }, - { name: ".bpm()", type: "function", signature: "bpm(bpm: number): this", description: "Set BPM" }, - { name: ".tempoMarking()", type: "function", signature: "tempoMarking(marking): this", description: "Classical tempo" }, - { name: ".tempoFeel()", type: "function", signature: "tempoFeel(feel): this", description: "Set rhythmic feel" }, - ], - }, - { - name: "Audio: Vocals", - items: [ - { name: ".vocals()", type: "function", signature: "vocals(settings): this", description: "Set all vocal settings" }, - { name: ".vocalStyle()", type: "function", signature: "vocalStyle(style): this", description: "Set vocal style(s)" }, - { name: ".language()", type: "function", signature: "language(lang): this", description: "Set language" }, - { name: ".lyricsTheme()", type: "function", signature: "lyricsTheme(theme: string): this", description: "Set lyrics theme" }, - { name: ".delivery()", type: "function", signature: "delivery(delivery: string): this", description: "Set vocal delivery" }, - { name: ".instrumental()", type: "function", signature: "instrumental(): this", description: "Make instrumental" }, - ], - }, - { - name: "Audio: Instruments", - items: [ - { name: ".instruments()", type: "function", signature: "instruments(instruments[]): this", description: "Set instruments" }, - { name: ".leadInstrument()", type: "function", signature: "leadInstrument(inst): this", description: "Set lead instrument" }, - { name: ".rhythmSection()", type: "function", signature: "rhythmSection(instruments[]): this", description: "Set rhythm section" }, - { name: ".bassInstrument()", type: "function", signature: "bassInstrument(inst): this", description: "Set bass" }, - { name: ".percussion()", type: "function", signature: "percussion(instruments): this", description: "Set percussion" }, - { name: ".pads()", type: "function", signature: "pads(instruments): this", description: "Set pad sounds" }, - ], - }, - { - name: "Audio: Structure", - items: [ - { name: ".structure()", type: "function", signature: "structure(settings): this", description: "Set structure" }, - { name: ".section()", type: "function", signature: "section(type, bars?, desc?): this", description: "Add song section" }, - { name: ".duration()", type: "function", signature: "duration(seconds): this", description: "Set duration" }, - ], - }, - { - name: "Audio: Production", - items: [ - { name: ".production()", type: "function", signature: "production(settings): this", description: "Production settings" }, - { name: ".productionStyle()", type: "function", signature: "productionStyle(style): this", description: "Set production style" }, - { name: ".era()", type: "function", signature: "era(era: Era): this", description: "Set era/decade" }, - { name: ".reference()", type: "function", signature: "reference(artists[]): this", description: "Reference artists" }, - { name: ".texture()", type: "function", signature: "texture(texture: string): this", description: "Set sound texture" }, - { name: ".effects()", type: "function", signature: "effects(effects[]): this", description: "Add audio effects" }, - { name: ".key()", type: "function", signature: "key(key: MusicalKey): this", description: "Set musical key" }, - { name: ".tags()", type: "function", signature: "tags(tags[]): this", description: "Add style tags" }, - { name: ".build()", type: "function", signature: "build(): BuiltAudioPrompt", description: "Build the prompt" }, - ], - }, - // ============================================================================ - // TYPES - // ============================================================================ - { - name: "Chat Types", - items: [ - { name: "MessageRole", type: "type", description: "'system' | 'user' | 'assistant'" }, - { name: "PersonaTone", type: "type", description: "'professional' | 'casual' | 'technical' | 'friendly' | ..." }, - { name: "PersonaExpertise", type: "type", description: "'coding' | 'writing' | 'analysis' | 'teaching' | ..." }, - { name: "ReasoningStyle", type: "type", description: "'step-by-step' | 'chain-of-thought' | 'tree-of-thought' | ..." }, - { name: "OutputLength", type: "type", description: "'brief' | 'moderate' | 'detailed' | 'comprehensive'" }, - { name: "OutputStyle", type: "type", description: "'prose' | 'bullet-points' | 'numbered-list' | 'table' | ..." }, - ], - }, - { - name: "Camera Types", - items: [ - { name: "ShotType", type: "type", description: "'close-up' | 'medium' | 'wide' | 'extreme-wide' | 'portrait' | ..." }, - { name: "CameraAngle", type: "type", description: "'eye-level' | 'low-angle' | 'high-angle' | 'dutch-angle' | ..." }, - { name: "CameraMovement", type: "type", description: "'static' | 'pan' | 'tilt' | 'dolly' | 'tracking' | 'crane' | ..." }, - { name: "LensType", type: "type", description: "'wide-angle' | '35mm' | '50mm' | '85mm' | 'telephoto' | ..." }, - { name: "FocusType", type: "type", description: "'shallow' | 'deep' | 'soft-focus' | 'bokeh-heavy' | ..." }, - { name: "BokehStyle", type: "type", description: "'smooth' | 'creamy' | 'swirly' | 'soap-bubble' | ..." }, - ], - }, - { - name: "Style Types", - items: [ - { name: "LightingType", type: "type", description: "'natural' | 'studio' | 'dramatic' | 'rim' | 'rembrandt' | ..." }, - { name: "TimeOfDay", type: "type", description: "'dawn' | 'golden-hour' | 'midday' | 'blue-hour' | 'night' | ..." }, - { name: "ArtStyle", type: "type", description: "'photorealistic' | 'cinematic' | 'anime' | 'oil-painting' | ..." }, - { name: "ColorPalette", type: "type", description: "'warm' | 'cool' | 'vibrant' | 'muted' | 'monochrome' | ..." }, - { name: "Mood", type: "type", description: "'serene' | 'dramatic' | 'mysterious' | 'romantic' | 'epic' | ..." }, - { name: "FilmStock", type: "type", description: "'kodak-portra-400' | 'fujifilm-velvia-50' | 'cinestill-800t' | ..." }, - ], - }, - { - name: "Audio Types", - items: [ - { name: "MusicGenre", type: "type", description: "'pop' | 'rock' | 'jazz' | 'electronic' | 'synthwave' | ..." }, - { name: "Instrument", type: "type", description: "'piano' | 'guitar' | 'drums' | 'synthesizer' | '808' | ..." }, - { name: "VocalStyle", type: "type", description: "'male' | 'female' | 'choir' | 'rap' | 'falsetto' | ..." }, - { name: "TempoMarking", type: "type", description: "'largo' | 'adagio' | 'andante' | 'allegro' | 'presto'" }, - { name: "SongSection", type: "type", description: "'intro' | 'verse' | 'chorus' | 'bridge' | 'drop' | 'outro'" }, - { name: "ProductionStyle", type: "type", description: "'lo-fi' | 'vintage' | 'modern' | 'polished' | 'raw' | ..." }, - { name: "MusicalKey", type: "type", description: "'C' | 'Am' | 'G' | 'Em' | 'D' | 'Bm' | ..." }, - ], - }, - // ============================================================================ - // UTILITIES - // ============================================================================ - { - name: "Parser", - items: [ - { name: "parsePrompt", type: "function", signature: "parse(content, format?): ParsedPrompt", description: "Parse prompt from string (YAML/JSON/MD)" }, - { name: "toYaml", type: "function", signature: "toYaml(prompt): string", description: "Serialize to YAML format" }, - { name: "toJson", type: "function", signature: "toJson(prompt, pretty?): string", description: "Serialize to JSON format" }, - { name: "getSystemPrompt", type: "function", signature: "getSystemPrompt(prompt): string", description: "Extract system message content" }, - { name: "interpolate", type: "function", signature: "interpolate(prompt, values): ParsedPrompt", description: "Fill in {{var}} placeholders" }, - ], - }, - { - name: "Variables", - items: [ - { name: "detectVariables", type: "function", signature: "detectVariables(text): DetectedVariable[]", description: "Find all variable patterns in text" }, - { name: "normalizeVariables", type: "function", signature: "normalize(content): string", description: "Convert all to ${var} format" }, - { name: "extractVariables", type: "function", signature: "extractVariables(text): {name,default?}[]", description: "Extract ${var} variables" }, - { name: "compile", type: "function", signature: "compile(template, values, opts?): string", description: "Fill template with values" }, - { name: "convertToSupportedFormat", type: "function", signature: "convertToSupportedFormat(v): string", description: "Convert single variable" }, - { name: "convertAllVariables", type: "function", signature: "convertAllVariables(text): string", description: "Convert all variables in text" }, - ], - }, - { - name: "Quality", - items: [ - { name: "checkQuality", type: "function", signature: "check(prompt): QualityResult", description: "Check prompt quality (score 0-1)" }, - { name: "validatePrompt", type: "function", signature: "validate(prompt): void", description: "Throw if prompt is invalid" }, - { name: "isValidPrompt", type: "function", signature: "isValid(prompt): boolean", description: "Check if prompt is valid" }, - { name: "getSuggestions", type: "function", signature: "getSuggestions(prompt): string[]", description: "Get improvement suggestions" }, - ], - }, - { - name: "Similarity", - items: [ - { name: "calculateSimilarity", type: "function", signature: "calculate(a, b): number", description: "Get similarity score 0-1" }, - { name: "isSimilarContent", type: "function", signature: "isSimilar(a, b, threshold?): boolean", description: "Check if similar (default 0.85)" }, - { name: "normalizeContent", type: "function", signature: "normalizeContent(text): string", description: "Normalize text for comparison" }, - { name: "getContentFingerprint", type: "function", signature: "getContentFingerprint(text): string", description: "Get content hash for indexing" }, - { name: "findDuplicates", type: "function", signature: "findDuplicates(items, threshold?): T[][]", description: "Find groups of duplicates" }, - { name: "deduplicate", type: "function", signature: "deduplicate(items, threshold?): T[]", description: "Remove duplicates, keep first" }, - ], - }, -]; - -const DEFAULT_CODE = `import { builder, templates } from 'prompts.chat'; - -// Create a prompt using the fluent builder API -const prompt = builder() - .role("Senior TypeScript Developer") - .context("You are helping review code for a startup") - .task("Analyze the following code for bugs and improvements") - .constraints([ - "Be concise and actionable", - "Focus on critical issues first", - "Suggest modern TypeScript best practices" - ]) - .output("JSON with { bugs: [], suggestions: [], rating: number }") - .variable("code", { required: true, description: "The code to review" }) - .build(); - -// Or use pre-built templates -const translatePrompt = templates.translation("English", "Spanish").build(); - -// Export the main prompt -prompt; -`; - -const TYPE_DEFINITIONS = ` -declare module 'prompts.chat' { - // ============================================================================ - // BUILDER TYPES - // ============================================================================ - - export interface PromptVariable { - name: string; - description?: string; - required?: boolean; - defaultValue?: string; - } - - export interface BuiltPrompt { - content: string; - variables: PromptVariable[]; - metadata: { - role?: string; - context?: string; - task?: string; - constraints?: string[]; - outputFormat?: string; - examples?: Array<{ input: string; output: string }>; - }; - } - - export class PromptBuilder { - role(role: string): this; - persona(persona: string): this; - context(context: string): this; - background(background: string): this; - task(task: string): this; - instruction(instruction: string): this; - constraints(constraints: string[]): this; - constraint(constraint: string): this; - rules(rules: string[]): this; - output(format: string): this; - format(format: string): this; - example(input: string, output: string): this; - examples(examples: Array<{ input: string; output: string }>): this; - variable(name: string, options?: { description?: string; required?: boolean; defaultValue?: string }): this; - section(title: string, content: string): this; - raw(content: string): this; - build(): BuiltPrompt; - toString(): string; - } - - export function builder(): PromptBuilder; - export function fromPrompt(content: string): PromptBuilder; - - export const templates: { - codeReview(options?: { language?: string; focus?: string[] }): PromptBuilder; - translation(from: string, to: string): PromptBuilder; - summarize(options?: { maxLength?: number; style?: 'bullet' | 'paragraph' }): PromptBuilder; - qa(context?: string): PromptBuilder; - }; - - // ============================================================================ - // CHAT BUILDER TYPES - // ============================================================================ - - export type PersonaTone = 'professional' | 'casual' | 'formal' | 'friendly' | 'academic' | 'technical' | 'creative' | 'empathetic' | 'authoritative' | 'playful' | 'concise' | 'detailed' | 'socratic' | 'coaching' | 'analytical' | 'encouraging' | 'neutral' | 'humorous' | 'serious'; - export type PersonaExpertise = 'general' | 'coding' | 'writing' | 'analysis' | 'research' | 'teaching' | 'counseling' | 'creative' | 'legal' | 'medical' | 'financial' | 'scientific' | 'engineering' | 'design' | 'marketing' | 'business' | 'philosophy' | 'history' | 'languages' | 'mathematics'; - export type ReasoningStyle = 'step-by-step' | 'chain-of-thought' | 'tree-of-thought' | 'direct' | 'analytical' | 'comparative' | 'deductive' | 'inductive' | 'first-principles' | 'analogical' | 'devil-advocate'; - export type OutputLength = 'brief' | 'moderate' | 'detailed' | 'comprehensive' | 'exhaustive'; - export type OutputStyle = 'prose' | 'bullet-points' | 'numbered-list' | 'table' | 'code' | 'mixed' | 'qa' | 'dialogue'; - export type MessageRole = 'system' | 'user' | 'assistant'; - - export interface ChatMessage { role: MessageRole; content: string; name?: string; } - export interface BuiltChatPrompt { messages: ChatMessage[]; systemPrompt: string; userPrompt?: string; metadata: Record; } - - export class ChatPromptBuilder { - // Message methods - system(content: string): this; - user(content: string, name?: string): this; - assistant(content: string): this; - message(role: MessageRole, content: string, name?: string): this; - messages(messages: ChatMessage[]): this; - conversation(turns: Array<{ user: string; assistant?: string }>): this; - // Persona methods - persona(settings: string | { role?: string; tone?: PersonaTone | PersonaTone[]; expertise?: PersonaExpertise | PersonaExpertise[]; }): this; - role(role: string): this; - tone(tone: PersonaTone | PersonaTone[]): this; - expertise(expertise: PersonaExpertise | PersonaExpertise[]): this; - personality(traits: string[]): this; - background(background: string): this; - speakAs(name: string): this; - responseLanguage(language: string): this; - // Context methods - context(settings: string | { background?: string; domain?: string; audience?: string; }): this; - domain(domain: string): this; - audience(audience: string): this; - purpose(purpose: string): this; - constraints(constraints: string[]): this; - constraint(constraint: string): this; - assumptions(assumptions: string[]): this; - knowledge(facts: string[]): this; - // Task methods - task(instruction: string): this; - instruction(instruction: string): this; - steps(steps: string[]): this; - deliverables(deliverables: string[]): this; - criteria(criteria: string[]): this; - avoid(antiPatterns: string[]): this; - priority(priority: 'accuracy' | 'speed' | 'creativity' | 'thoroughness'): this; - // Example methods - example(input: string, output: string, explanation?: string): this; - examples(examples: Array<{ input: string; output: string; explanation?: string }>): this; - fewShot(examples: Array<{ input: string; output: string }>): this; - // Output methods - outputFormat(format: 'text' | 'json' | 'markdown' | 'code' | 'table'): this; - json(schema?: { name: string; schema: Record }): this; - jsonSchema(name: string, schema: Record, description?: string): this; - markdown(): this; - code(language?: string): this; - table(): this; - length(length: OutputLength): this; - style(style: OutputStyle): this; - brief(): this; - moderate(): this; - detailed(): this; - comprehensive(): this; - exhaustive(): this; - withExamples(): this; - withExplanation(): this; - withSources(): this; - withConfidence(): this; - // Reasoning methods - reasoningStyle(style: ReasoningStyle): this; - stepByStep(): this; - chainOfThought(): this; - treeOfThought(): this; - firstPrinciples(): this; - devilsAdvocate(): this; - showWork(): this; - verifyAnswer(): this; - considerAlternatives(): this; - // Build - build(): BuiltChatPrompt; - } - - export function chat(): ChatPromptBuilder; - export const chatPresets: Record ChatPromptBuilder>; - - // ============================================================================ - // VIDEO BUILDER TYPES - // ============================================================================ - - export type ShotType = 'extreme-close-up' | 'close-up' | 'medium-close-up' | 'medium' | 'medium-wide' | 'wide' | 'extreme-wide' | 'establishing' | 'full-body' | 'portrait' | 'headshot'; - export type CameraAngle = 'eye-level' | 'low-angle' | 'high-angle' | 'dutch-angle' | 'birds-eye' | 'worms-eye' | 'over-the-shoulder' | 'point-of-view' | 'aerial' | 'drone' | 'ground-level'; - export type CameraMovement = 'static' | 'pan' | 'tilt' | 'dolly' | 'truck' | 'pedestal' | 'zoom' | 'handheld' | 'steadicam' | 'crane' | 'drone' | 'tracking' | 'arc' | 'whip-pan' | 'roll' | 'boom' | 'jib' | 'snorricam' | 'vertigo-effect' | 'crash-zoom' | 'slow-push' | 'slow-pull'; - export type LensType = 'wide-angle' | 'ultra-wide' | 'standard' | 'telephoto' | 'macro' | 'fisheye' | '14mm' | '24mm' | '35mm' | '50mm' | '85mm' | '100mm' | '135mm' | '200mm' | 'tilt-shift' | 'anamorphic' | 'spherical' | 'prime' | 'zoom'; - export type LightingType = 'natural' | 'studio' | 'dramatic' | 'soft' | 'hard' | 'diffused' | 'key' | 'fill' | 'rim' | 'backlit' | 'silhouette' | 'rembrandt' | 'split' | 'butterfly' | 'loop' | 'broad' | 'short' | 'chiaroscuro' | 'high-key' | 'low-key' | 'three-point' | 'practical' | 'motivated'; - export type TimeOfDay = 'dawn' | 'sunrise' | 'golden-hour' | 'morning' | 'midday' | 'afternoon' | 'blue-hour' | 'sunset' | 'dusk' | 'twilight' | 'night' | 'midnight'; - export type ArtStyle = 'photorealistic' | 'hyperrealistic' | 'cinematic' | 'documentary' | 'editorial' | 'fashion' | 'portrait' | 'landscape' | 'street' | 'fine-art' | 'conceptual' | 'surreal' | 'abstract' | 'minimalist' | 'vintage' | 'retro' | 'noir' | 'gothic' | 'romantic' | 'cyberpunk' | 'steampunk' | 'fantasy' | 'sci-fi' | 'anime' | 'manga' | 'comic-book' | 'illustration' | 'digital-art' | 'oil-painting' | 'watercolor' | 'sketch' | '3d-render'; - export type ColorPalette = 'warm' | 'cool' | 'neutral' | 'vibrant' | 'muted' | 'pastel' | 'neon' | 'monochrome' | 'sepia' | 'desaturated' | 'high-contrast' | 'low-contrast' | 'earthy' | 'oceanic' | 'forest' | 'sunset' | 'midnight' | 'golden'; - export type Mood = 'serene' | 'peaceful' | 'melancholic' | 'dramatic' | 'tense' | 'mysterious' | 'romantic' | 'nostalgic' | 'hopeful' | 'joyful' | 'energetic' | 'chaotic' | 'ethereal' | 'dark' | 'light' | 'whimsical' | 'eerie' | 'epic' | 'intimate'; - export type FilmStock = 'kodak-portra-400' | 'kodak-portra-800' | 'kodak-ektar-100' | 'kodak-tri-x-400' | 'kodak-vision3-500t' | 'fujifilm-pro-400h' | 'fujifilm-velvia-50' | 'ilford-hp5-plus' | 'cinestill-800t' | 'cinestill-50d'; - export type FocusType = 'shallow' | 'deep' | 'soft-focus' | 'tilt-shift' | 'rack-focus' | 'split-diopter' | 'selective' | 'bokeh-heavy' | 'tack-sharp'; - export type BokehStyle = 'smooth' | 'creamy' | 'swirly' | 'busy' | 'soap-bubble' | 'cat-eye' | 'oval-anamorphic'; - export type FilterType = 'uv' | 'polarizer' | 'nd' | 'nd-graduated' | 'black-pro-mist' | 'white-pro-mist' | 'glimmer-glass' | 'classic-soft' | 'diffusion' | 'infrared' | 'warming' | 'cooling' | 'vintage-look'; - export type VideoPacing = 'slow' | 'medium' | 'fast' | 'variable' | 'building' | 'frenetic' | 'contemplative'; - export type VideoTransition = 'cut' | 'fade' | 'dissolve' | 'wipe' | 'morph' | 'match-cut' | 'jump-cut' | 'cross-dissolve' | 'iris' | 'push' | 'slide'; - - export interface BuiltVideoPrompt { prompt: string; structure: Record; } - - export class VideoPromptBuilder { - // Scene methods - scene(description: string | { description: string; setting?: string; timeOfDay?: TimeOfDay; weather?: string; atmosphere?: string }): this; - setting(setting: string): this; - // Subject methods - subject(main: string | { main: string; appearance?: string; clothing?: string; age?: string; count?: string }): this; - appearance(appearance: string): this; - clothing(clothing: string): this; - // Camera methods - camera(settings: { shot?: ShotType; angle?: CameraAngle; movement?: CameraMovement; lens?: LensType }): this; - shot(shot: ShotType): this; - angle(angle: CameraAngle): this; - movement(movement: CameraMovement): this; - lens(lens: LensType): this; - platform(platform: 'handheld' | 'steadicam' | 'tripod' | 'drone' | 'crane' | 'gimbal' | 'slider' | 'dolly' | 'technocrane' | 'russian-arm' | 'fpv-drone'): this; - cameraSpeed(speed: 'slow' | 'medium' | 'fast'): this; - movementDirection(direction: 'left' | 'right' | 'forward' | 'backward' | 'up' | 'down' | 'arc-left' | 'arc-right'): this; - rig(rig: string): this; - gimbal(gimbal: string): this; - cameraBrand(brand: string): this; - cameraModel(model: string): this; - sensor(sensor: string): this; - lensModel(model: string): this; - lensBrand(brand: string): this; - focalLength(length: string): this; - anamorphic(ratio?: '1.33x' | '1.5x' | '1.8x' | '2x'): this; - aperture(aperture: string): this; - frameRate(fps: 24 | 25 | 30 | 48 | 60 | 120 | 240): this; - slowMotion(enabled?: boolean): this; - shutterAngle(angle: number): this; - filter(filter: FilterType | FilterType[]): this; - filmStock(stock: FilmStock): this; - filmGrain(grain: 'none' | 'subtle' | 'moderate' | 'heavy'): this; - halation(enabled?: boolean): this; - // Lighting methods - lighting(settings: { type?: LightingType | LightingType[]; time?: TimeOfDay; direction?: string; intensity?: string }): this; - lightingType(type: LightingType | LightingType[]): this; - timeOfDay(time: TimeOfDay): this; - weather(weather: 'sunny' | 'cloudy' | 'overcast' | 'foggy' | 'misty' | 'rainy' | 'stormy' | 'snowy' | 'hazy'): this; - // Action methods - action(action: string, options?: { duration?: number; timing?: 'start' | 'middle' | 'end' }): this; - actions(actions: string[]): this; - motion(settings: { subject?: string; type?: string; direction?: string; speed?: string; beats?: string[] }): this; - motionBeats(beats: string[]): this; - // Style methods - style(settings: { format?: string; era?: string; look?: ArtStyle | ArtStyle[]; reference?: string[] }): this; - format(format: string): this; - era(era: string): this; - styleFilmStock(stock: string): this; - look(look: ArtStyle | ArtStyle[]): this; - reference(references: string[]): this; - // Color methods - color(settings: { palette?: ColorPalette | ColorPalette[]; anchors?: string[]; grade?: string }): this; - palette(palette: ColorPalette | ColorPalette[]): this; - colorAnchors(anchors: string[]): this; - colorGrade(grade: string): this; - // Audio methods - audio(settings: { ambient?: string; diegetic?: string[]; music?: string; dialogue?: string; soundEffects?: string[] }): this; - dialogue(dialogue: string): this; - ambient(ambient: string): this; - diegetic(sounds: string[]): this; - soundEffects(effects: string[]): this; - music(music: string): this; - // Technical methods - technical(settings: { duration?: number; resolution?: string; fps?: number; aspectRatio?: string }): this; - duration(seconds: number): this; - resolution(res: '480p' | '720p' | '1080p' | '4K'): this; - fps(fps: 24 | 30 | 60): this; - aspectRatio(ratio: '16:9' | '21:9' | '4:3' | '1:1' | '9:16'): this; - // Mood and pacing - mood(mood: Mood | Mood[]): this; - pacing(pacing: VideoPacing): this; - transition(transition: VideoTransition): this; - transitions(transitions: VideoTransition[]): this; - custom(text: string): this; - build(): BuiltVideoPrompt; - } - - export function video(): VideoPromptBuilder; - - // ============================================================================ - // AUDIO BUILDER TYPES - // ============================================================================ - - export type MusicGenre = 'pop' | 'rock' | 'jazz' | 'classical' | 'electronic' | 'hip-hop' | 'r&b' | 'country' | 'folk' | 'blues' | 'metal' | 'punk' | 'indie' | 'alternative' | 'ambient' | 'lo-fi' | 'synthwave' | 'orchestral' | 'cinematic' | 'world' | 'latin' | 'reggae' | 'soul' | 'funk' | 'disco' | 'house' | 'techno' | 'edm' | 'trap' | 'drill' | 'k-pop' | 'j-pop' | 'bossa-nova' | 'gospel' | 'grunge' | 'shoegaze' | 'post-rock' | 'prog-rock' | 'psychedelic' | 'chillwave' | 'vaporwave' | 'drum-and-bass' | 'dubstep' | 'trance' | 'hardcore'; - export type Instrument = 'piano' | 'guitar' | 'acoustic-guitar' | 'electric-guitar' | 'bass' | 'drums' | 'violin' | 'cello' | 'viola' | 'flute' | 'saxophone' | 'trumpet' | 'trombone' | 'synthesizer' | 'organ' | 'harp' | 'percussion' | 'strings' | 'brass' | 'woodwinds' | 'choir' | 'vocals' | 'beatbox' | 'turntables' | 'harmonica' | 'banjo' | 'ukulele' | 'mandolin' | 'accordion' | 'marimba' | 'vibraphone' | 'xylophone' | 'timpani' | 'congas' | 'bongos' | 'djembe' | 'tabla' | 'sitar' | '808' | '909' | 'moog' | 'rhodes' | 'wurlitzer' | 'mellotron' | 'theremin'; - export type VocalStyle = 'male' | 'female' | 'duet' | 'choir' | 'a-cappella' | 'spoken-word' | 'rap' | 'falsetto' | 'belting' | 'whisper' | 'growl' | 'melodic' | 'harmonized' | 'auto-tuned' | 'operatic' | 'soul' | 'breathy' | 'nasal' | 'raspy' | 'clear'; - export type VocalLanguage = 'english' | 'spanish' | 'french' | 'german' | 'italian' | 'portuguese' | 'japanese' | 'korean' | 'chinese' | 'arabic' | 'hindi' | 'russian' | 'turkish' | 'instrumental'; - export type TempoMarking = 'largo' | 'adagio' | 'andante' | 'moderato' | 'allegro' | 'vivace' | 'presto'; - export type TimeSignature = '4/4' | '3/4' | '6/8' | '2/4' | '5/4' | '7/8' | '12/8'; - export type MusicalKey = 'C' | 'C#' | 'Db' | 'D' | 'D#' | 'Eb' | 'E' | 'F' | 'F#' | 'Gb' | 'G' | 'G#' | 'Ab' | 'A' | 'A#' | 'Bb' | 'B' | 'Cm' | 'C#m' | 'Dm' | 'D#m' | 'Ebm' | 'Em' | 'Fm' | 'F#m' | 'Gm' | 'G#m' | 'Am' | 'A#m' | 'Bbm' | 'Bm'; - export type SongSection = 'intro' | 'verse' | 'pre-chorus' | 'chorus' | 'bridge' | 'breakdown' | 'drop' | 'build-up' | 'outro' | 'solo' | 'interlude' | 'hook'; - export type ProductionStyle = 'lo-fi' | 'hi-fi' | 'vintage' | 'modern' | 'polished' | 'raw' | 'organic' | 'synthetic' | 'acoustic' | 'electric' | 'hybrid' | 'minimalist' | 'maximalist' | 'layered' | 'sparse' | 'dense' | 'atmospheric' | 'punchy' | 'warm' | 'bright'; - export type Era = '1950s' | '1960s' | '1970s' | '1980s' | '1990s' | '2000s' | '2010s' | '2020s' | 'retro' | 'vintage' | 'classic' | 'modern' | 'futuristic'; - - export interface BuiltAudioPrompt { prompt: string; structure: Record; } - - export class AudioPromptBuilder { - // Genre methods - genre(primary: MusicGenre | { primary: MusicGenre; secondary?: MusicGenre[]; subgenre?: string }): this; - subgenre(subgenre: string): this; - fusion(genres: MusicGenre[]): this; - // Mood methods - mood(primary: string, ...secondary: string[]): this; - energy(level: 'low' | 'medium' | 'high' | 'building' | 'dynamic'): this; - emotion(emotion: string): this; - // Tempo methods - tempo(bpmOrSettings: number | { bpm?: number; marking?: string; feel?: string }): this; - bpm(bpm: number): this; - tempoMarking(marking: 'largo' | 'adagio' | 'andante' | 'moderato' | 'allegro' | 'vivace' | 'presto'): this; - tempoFeel(feel: 'steady' | 'driving' | 'relaxed' | 'swinging' | 'syncopated'): this; - // Vocal methods - vocals(settings: { style?: VocalStyle | VocalStyle[]; language?: string; theme?: string; delivery?: string }): this; - vocalStyle(style: VocalStyle | VocalStyle[]): this; - language(language: string): this; - lyrics(lyrics: string): this; - lyricsTheme(theme: string): this; - delivery(delivery: string): this; - instrumental(): this; - // Instrumentation methods - instruments(instruments: Instrument[]): this; - instrumentation(settings: { lead?: Instrument | Instrument[]; rhythm?: Instrument[]; bass?: Instrument }): this; - leadInstrument(instrument: Instrument | Instrument[]): this; - rhythmSection(instruments: Instrument[]): this; - bassInstrument(instrument: Instrument): this; - percussion(instruments: Instrument | Instrument[]): this; - pads(instruments: Instrument | Instrument[]): this; - featuredInstrument(instrument: Instrument): this; - // Structure methods - structure(settings: { sections?: Array<{ type: string; bars?: number; description?: string }>; duration?: number }): this; - section(type: 'intro' | 'verse' | 'pre-chorus' | 'chorus' | 'bridge' | 'drop' | 'outro', bars?: number, description?: string): this; - form(form: string): this; - duration(seconds: number): this; - // Production methods - production(settings: { style?: string | string[]; era?: string; reference?: string[] }): this; - productionStyle(style: string | string[]): this; - era(era: string): this; - reference(artists: string[]): this; - texture(texture: string): this; - effects(effects: string[]): this; - // Technical methods - key(key: string): this; - timeSignature(sig: '4/4' | '3/4' | '6/8' | '5/4' | '7/8'): this; - // Tags - tag(tag: string): this; - tags(tags: string[]): this; - custom(text: string): this; - build(): BuiltAudioPrompt; - } - - export function audio(): AudioPromptBuilder; - - // ============================================================================ - // IMAGE BUILDER TYPES - // ============================================================================ - - export interface BuiltImagePrompt { prompt: string; structure: Record; } - - export class ImagePromptBuilder { - // Subject methods - subject(main: string | { main: string; details?: string[]; expression?: string; pose?: string }): this; - subjectDetails(details: string[]): this; - expression(expression: string): this; - pose(pose: string): this; - action(action: string): this; - clothing(clothing: string): this; - accessories(accessories: string[]): this; - subjectCount(count: number | 'single' | 'couple' | 'group' | 'crowd'): this; - // Environment methods - environment(setting: string | { setting: string; location?: string; atmosphere?: string; season?: string }): this; - location(location: string): this; - props(props: string[]): this; - atmosphere(atmosphere: string): this; - season(season: 'spring' | 'summer' | 'autumn' | 'winter'): this; - // Camera methods - camera(settings: { angle?: CameraAngle; shot?: ShotType; lens?: LensType; focus?: FocusType }): this; - angle(angle: CameraAngle): this; - shot(shot: ShotType): this; - lens(lens: LensType): this; - focus(focus: FocusType): this; - aperture(aperture: string): this; - filmStock(filmStock: FilmStock): this; - filmFormat(format: string): this; - cameraBrand(brand: string): this; - cameraModel(model: string): this; - sensor(sensor: string): this; - lensModel(model: string): this; - lensBrand(brand: string): this; - focalLength(length: string): this; - bokeh(style: BokehStyle): this; - filter(filter: FilterType | FilterType[]): this; - iso(iso: number): this; - shutterSpeed(speed: string): this; - whiteBalance(wb: 'daylight' | 'cloudy' | 'tungsten' | 'fluorescent' | 'flash' | 'custom'): this; - colorProfile(profile: string): this; - // Lighting methods - lighting(settings: { type?: LightingType | LightingType[]; time?: TimeOfDay; direction?: string; intensity?: string }): this; - lightingType(type: LightingType | LightingType[]): this; - timeOfDay(time: TimeOfDay): this; - weather(weather: 'sunny' | 'cloudy' | 'overcast' | 'foggy' | 'misty' | 'rainy' | 'stormy' | 'snowy' | 'hazy'): this; - lightDirection(direction: 'front' | 'side' | 'back' | 'top' | 'bottom' | 'three-quarter'): this; - lightIntensity(intensity: 'soft' | 'medium' | 'hard' | 'dramatic'): this; - // Composition methods - composition(settings: { ruleOfThirds?: boolean; goldenRatio?: boolean; symmetry?: string }): this; - ruleOfThirds(): this; - goldenRatio(): this; - symmetry(type: 'none' | 'horizontal' | 'vertical' | 'radial'): this; - foreground(fg: string): this; - midground(mg: string): this; - background(bg: string): this; - // Style methods - style(settings: { medium?: ArtStyle | ArtStyle[]; artist?: string | string[] }): this; - medium(medium: ArtStyle | ArtStyle[]): this; - artist(artist: string | string[]): this; - influence(influences: string[]): this; - // Color methods - color(settings: { palette?: ColorPalette | ColorPalette[]; primary?: string[]; accent?: string[] }): this; - palette(palette: ColorPalette | ColorPalette[]): this; - primaryColors(colors: string[]): this; - accentColors(colors: string[]): this; - colorGrade(grade: string): this; - // Technical methods - technical(settings: { aspectRatio?: string; resolution?: string; quality?: string }): this; - aspectRatio(ratio: '1:1' | '4:3' | '3:2' | '16:9' | '21:9' | '9:16'): this; - resolution(resolution: string): this; - quality(quality: 'draft' | 'standard' | 'high' | 'ultra' | 'masterpiece'): this; - // Mood and misc - mood(mood: string | string[]): this; - negative(items: string[]): this; - custom(text: string): this; - build(): BuiltImagePrompt; - } - - export function image(): ImagePromptBuilder; - - // ============================================================================ - // UTILITY MODULES - // ============================================================================ - - export namespace variables { - export function detect(text: string): Array<{ name: string; pattern: string }>; - export function normalize(text: string): string; - export function extractVariables(text: string): Array<{ name: string; defaultValue?: string }>; - export function compile(text: string, values: Record): string; - } - - export namespace similarity { - export function calculate(content1: string, content2: string): number; - export function isDuplicate(content1: string, content2: string, threshold?: number): boolean; - export function findDuplicates(prompts: string[], threshold?: number): string[][]; - export function deduplicate(prompts: string[], threshold?: number): string[]; - } - - export namespace quality { - export function check(content: string): { score: number; issues: Array<{ type: string; message: string }> }; - export function validate(content: string): boolean; - export function getSuggestions(content: string): string[]; - } - - export namespace parser { - export function parse(content: string): { type: string; content: unknown }; - export function toYaml(obj: unknown): string; - export function toJson(obj: unknown): string; - } -} -`; - -function ApiDocsSidebar({ selectedItem, onSelectItem }: { selectedItem: ApiItem | null; onSelectItem: (item: ApiItem | null) => void }) { - const [expandedSections, setExpandedSections] = useState>(new Set(["Builder", "PromptBuilder Methods"])); - const [searchQuery, setSearchQuery] = useState(""); - - const toggleSection = (name: string) => { - setExpandedSections(prev => { - const next = new Set(prev); - if (next.has(name)) { - next.delete(name); - } else { - next.add(name); - } - return next; - }); - }; - - const getTypeColor = (type: ApiItem["type"]) => { - switch (type) { - case "function": return "text-blue-500 dark:text-blue-400"; - case "class": return "text-yellow-500 dark:text-yellow-400"; - case "interface": return "text-green-500 dark:text-green-400"; - case "type": return "text-purple-500 dark:text-purple-400"; - case "const": return "text-orange-500 dark:text-orange-400"; - default: return "text-muted-foreground"; - } - }; - - const getTypeLabel = (type: ApiItem["type"]) => { - switch (type) { - case "function": return "fn"; - case "class": return "class"; - case "interface": return "interface"; - case "type": return "type"; - case "const": return "const"; - default: return type; - } - }; - - // Filter sections and items based on search query - const filteredDocs = searchQuery.trim() - ? API_DOCS.map(section => ({ - ...section, - items: section.items.filter(item => - item.name.toLowerCase().includes(searchQuery.toLowerCase()) || - item.description?.toLowerCase().includes(searchQuery.toLowerCase()) || - item.signature?.toLowerCase().includes(searchQuery.toLowerCase()) - ) - })).filter(section => section.items.length > 0) - : API_DOCS; - - // When searching, expand all sections with matches - const effectiveExpandedSections = searchQuery.trim() - ? new Set(filteredDocs.map(s => s.name)) - : expandedSections; - - return ( -
-
-
- - API Docs -
-
- - setSearchQuery(e.target.value)} - className="h-7 pl-7 text-sm" - /> -
-
- -
- {filteredDocs.length === 0 ? ( -

No results found

- ) : ( - filteredDocs.map((section) => ( -
- - {effectiveExpandedSections.has(section.name) && ( -
- {section.items.map((item) => ( - - ))} -
- )} -
- )) - )} -
-
-
- ); -} - -function ApiDetailsPanel({ item, onClose }: { item: ApiItem; onClose: () => void }) { - const getTypeColor = (type: ApiItem["type"]) => { - switch (type) { - case "function": return "text-blue-500 dark:text-blue-400"; - case "class": return "text-yellow-500 dark:text-yellow-400"; - case "interface": return "text-green-500 dark:text-green-400"; - case "type": return "text-purple-500 dark:text-purple-400"; - case "const": return "text-orange-500 dark:text-orange-400"; - default: return "text-muted-foreground"; - } - }; - - return ( -
-
-
-
-
- {item.type} - {item.name} -
- {item.signature && ( - {item.signature} - )} -
- -
- {item.description && ( -

{item.description}

- )} - {item.params && item.params.length > 0 && ( -
-

Parameters:

-
- {item.params.map((p) => ( -
- {p.name} - : {p.type} - — {p.description} -
- ))} -
-
- )} - {item.returns && ( -

Returns: {item.returns}

- )} - {item.example && ( -
-

Example:

-
{item.example}
-
- )} -
-
- ); -} +// Import examples as raw text +import { + EXAMPLE_VIDEO, + EXAMPLE_AUDIO, + EXAMPLE_IMAGE, + EXAMPLE_CHAT, + DEFAULT_CODE, +} from "./examples"; export function PromptIde() { const t = useTranslations("ide"); @@ -1463,48 +150,6 @@ export function PromptIde() { } }, [outputFormat]); - // Simple YAML serializer - const toYaml = (obj: unknown, indent = 0): string => { - const spaces = ' '.repeat(indent); - - if (obj === null || obj === undefined) return 'null'; - if (typeof obj === 'string') { - if (obj.includes('\n')) { - return `|\n${obj.split('\n').map(line => spaces + ' ' + line).join('\n')}`; - } - return obj.includes(':') || obj.includes('#') ? `"${obj.replace(/"/g, '\\"')}"` : obj; - } - if (typeof obj === 'number' || typeof obj === 'boolean') return String(obj); - - if (Array.isArray(obj)) { - if (obj.length === 0) return '[]'; - return obj.map(item => { - if (typeof item === 'object' && item !== null) { - const inner = toYaml(item, indent + 1); - const lines = inner.split('\n'); - return `${spaces}- ${lines[0]}\n${lines.slice(1).map(l => spaces + ' ' + l).join('\n')}`.trim(); - } - return `${spaces}- ${toYaml(item, indent)}`; - }).join('\n'); - } - - if (typeof obj === 'object') { - const entries = Object.entries(obj).filter(([, v]) => v !== undefined); - if (entries.length === 0) return '{}'; - return entries.map(([key, value]) => { - if (typeof value === 'object' && value !== null && !Array.isArray(value)) { - return `${spaces}${key}:\n${toYaml(value, indent + 1)}`; - } - if (Array.isArray(value)) { - return `${spaces}${key}:\n${toYaml(value, indent + 1)}`; - } - return `${spaces}${key}: ${toYaml(value, indent)}`; - }).join('\n'); - } - - return String(obj); - }; - // Re-run when output format changes useEffect(() => { if (output || error) { @@ -1516,6 +161,8 @@ export function PromptIde() { const handleEditorMount = useCallback((_editor: unknown, monaco: unknown) => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const m = monaco as any; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const editor = _editor as any; // Add custom type definitions for prompts.chat m.languages?.typescript?.typescriptDefaults?.addExtraLib( @@ -1523,7 +170,7 @@ export function PromptIde() { 'prompts.chat.d.ts' ); - // Configure TypeScript compiler options + // Configure TypeScript compiler options for better autocomplete m.languages?.typescript?.typescriptDefaults?.setCompilerOptions({ target: 99, // ESNext allowNonTsExtensions: true, @@ -1534,6 +181,80 @@ export function PromptIde() { allowSyntheticDefaultImports: true, strict: true, }); + + // Enable better diagnostics for autocomplete + m.languages?.typescript?.typescriptDefaults?.setDiagnosticsOptions({ + noSemanticValidation: false, + noSyntaxValidation: false, + }); + + // Trigger suggestions automatically on string quotes and method calls + editor?.updateOptions?.({ + quickSuggestions: { + strings: true, + comments: false, + other: true, + }, + suggestOnTriggerCharacters: true, + acceptSuggestionOnEnter: 'on', + tabCompletion: 'on', + wordBasedSuggestions: 'off', + parameterHints: { enabled: true }, + }); + + // Register completion provider that triggers on quotes for string literals + m.languages?.registerCompletionItemProvider?.('typescript', { + triggerCharacters: ['"', "'", '('], + provideCompletionItems: (model: unknown, position: unknown) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const mdl = model as any; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const pos = position as any; + + const textUntilPosition = mdl.getValueInRange({ + startLineNumber: pos.lineNumber, + startColumn: 1, + endLineNumber: pos.lineNumber, + endColumn: pos.column, + }); + + // Check if we're inside a method call with a string argument + // Match first param: .method(" or subsequent params: .method("value", " + const methodMatch = textUntilPosition.match(/\.(\w+)\s*\([^)]*,\s*["']?$/) || + textUntilPosition.match(/\.(\w+)\s*\(\s*["']?$/); + if (!methodMatch) { + return { suggestions: [] }; + } + + const methodName = methodMatch[1]; + + // Use dynamically generated method options from TypeScript source + const options = METHOD_OPTIONS[methodName]; + if (!options) { + return { suggestions: [] }; + } + + // Determine if we need to include quotes + const needsQuote = !textUntilPosition.endsWith('"') && !textUntilPosition.endsWith("'"); + const quoteChar = textUntilPosition.includes('"') ? '' : (needsQuote ? '"' : ''); + + const suggestions = options.map((option, index) => ({ + label: option, + kind: 12, // Value + insertText: needsQuote ? `"${option}"` : option, + sortText: String(index).padStart(3, '0'), + detail: `${methodName} option`, + range: { + startLineNumber: pos.lineNumber, + startColumn: pos.column, + endLineNumber: pos.lineNumber, + endColumn: pos.column, + }, + })); + + return { suggestions }; + }, + }); }, []); const copyOutput = useCallback(() => { @@ -1586,7 +307,7 @@ export function PromptIde() {
{selectedApiItem && ( - setSelectedApiItem(null)} /> + setSelectedApiItem(null)} /> )}
@@ -1619,7 +340,7 @@ export function PromptIde() { className="h-6 text-xs gap-1 px-2" onClick={() => setCode(EXAMPLE_IMAGE)} > - + Image