humanbehavior-js 0.7.0 → 0.8.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/packages/browser/dist/cjs/index.js +6 -6
- package/packages/browser/dist/cjs/index.js.map +1 -1
- package/packages/browser/dist/esm/index.js +4 -4
- package/packages/browser/dist/esm/index.js.map +1 -1
- package/packages/browser/dist/index.min.js +1 -1
- package/packages/browser/dist/index.min.js.map +1 -1
- package/packages/core/dist/index.js +1 -1
- package/packages/core/dist/index.js.map +1 -1
- package/packages/core/dist/index.mjs +1 -1
- package/packages/core/dist/index.mjs.map +1 -1
- package/packages/core/dist/tracker.d.ts +12 -0
- package/packages/core/dist/tracker.d.ts.map +1 -1
- package/packages/react/dist/index.js +1 -1
- package/packages/react/dist/index.js.map +1 -1
- package/packages/react/dist/index.mjs +1 -1
- package/packages/react/dist/index.mjs.map +1 -1
- package/packages/wizard/dist/agent/claude-agent-installer.d.ts +17 -0
- package/packages/wizard/dist/agent/claude-agent-installer.d.ts.map +1 -0
- package/packages/wizard/dist/ai/ai-install-wizard.d.ts +2 -2
- package/packages/wizard/dist/ai/ai-install-wizard.d.ts.map +1 -1
- package/packages/wizard/dist/ai/manual-framework-wizard.d.ts +2 -2
- package/packages/wizard/dist/ai/manual-framework-wizard.d.ts.map +1 -1
- package/packages/wizard/dist/cli/ai-auto-install.d.ts +6 -0
- package/packages/wizard/dist/cli/ai-auto-install.d.ts.map +1 -1
- package/packages/wizard/dist/cli/ai-auto-install.js +641 -81
- package/packages/wizard/dist/cli/ai-auto-install.js.map +1 -1
- package/packages/wizard/dist/cli/auto-install.d.ts +4 -0
- package/packages/wizard/dist/cli/auto-install.d.ts.map +1 -1
- package/packages/wizard/dist/cli/auto-install.js +314 -56
- package/packages/wizard/dist/cli/auto-install.js.map +1 -1
- package/packages/wizard/dist/core/install-wizard.d.ts +51 -3
- package/packages/wizard/dist/core/install-wizard.d.ts.map +1 -1
- package/packages/wizard/dist/index.d.ts +2 -0
- package/packages/wizard/dist/index.d.ts.map +1 -1
- package/packages/wizard/dist/index.js +1 -1
- package/packages/wizard/dist/index.js.map +1 -1
- package/packages/wizard/dist/index.mjs +1 -1
- package/packages/wizard/dist/index.mjs.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../src/core/install-wizard.ts","../src/ai/ai-install-wizard.ts","../src/services/remote-ai-service.ts","../src/ai/manual-framework-wizard.ts","../src/cli/ai-auto-install.ts","../src/cli/auto-install.ts","../src/services/centralized-ai-service.ts"],"sourcesContent":["/**\n * HumanBehavior SDK Auto-Installation Wizard\n * \n * This wizard automatically detects the user's framework and modifies their codebase\n * to integrate the SDK with minimal user intervention.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { execSync } from 'child_process';\n\nexport interface FrameworkInfo {\n name: string;\n type: 'react' | 'vue' | 'angular' | 'svelte' | 'nextjs' | 'nuxt' | 'remix' | 'vanilla' | 'astro' | 'gatsby' | 'node' | 'auto';\n bundler?: 'vite' | 'webpack' | 'esbuild' | 'rollup';\n packageManager?: 'npm' | 'yarn' | 'pnpm';\n hasTypeScript?: boolean;\n hasRouter?: boolean;\n projectRoot?: string;\n version?: string;\n majorVersion?: number;\n features?: {\n hasReact18?: boolean;\n hasVue3?: boolean;\n hasNuxt3?: boolean;\n hasAngularStandalone?: boolean;\n hasNextAppRouter?: boolean;\n hasSvelteKit?: boolean;\n };\n}\n\nexport interface CodeModification {\n filePath: string;\n action: 'create' | 'modify' | 'append';\n content: string;\n description: string;\n}\n\nexport interface InstallationResult {\n success: boolean;\n framework: FrameworkInfo;\n modifications: CodeModification[];\n errors: string[];\n nextSteps: string[];\n}\n\nexport class AutoInstallationWizard {\n protected apiKey: string;\n protected projectRoot: string;\n protected framework: FrameworkInfo | null = null;\n private manualNotes: string[] = [];\n\n constructor(apiKey: string, projectRoot: string = process.cwd()) {\n this.apiKey = apiKey;\n this.projectRoot = projectRoot;\n }\n\n /**\n * Simple version comparison utility\n */\n private compareVersions(version1: string, version2: string): number {\n const v1Parts = version1.split('.').map(Number);\n const v2Parts = version2.split('.').map(Number);\n \n for (let i = 0; i < Math.max(v1Parts.length, v2Parts.length); i++) {\n const v1 = v1Parts[i] || 0;\n const v2 = v2Parts[i] || 0;\n if (v1 > v2) return 1;\n if (v1 < v2) return -1;\n }\n return 0;\n }\n\n private isVersionGte(version: string, target: string): boolean {\n return this.compareVersions(version, target) >= 0;\n }\n\n private getMajorVersion(version: string): number {\n return parseInt(version.split('.')[0]) || 0;\n }\n\n /**\n * Main installation method - detects framework and auto-installs\n */\n async install(): Promise<InstallationResult> {\n try {\n // Step 1: Detect framework\n this.framework = await this.detectFramework();\n \n // Step 2: Install package\n await this.installPackage();\n \n // Step 3: Generate and apply code modifications\n const modifications = await this.generateModifications();\n await this.applyModifications(modifications);\n \n // Step 4: Generate next steps\n const nextSteps = this.generateNextSteps();\n \n return {\n success: true,\n framework: this.framework,\n modifications,\n errors: [],\n nextSteps\n };\n } catch (error) {\n return {\n success: false,\n framework: this.framework || { name: 'unknown', type: 'vanilla' },\n modifications: [],\n errors: [error instanceof Error ? error.message : 'Unknown error'],\n nextSteps: []\n };\n }\n }\n\n /**\n * Detect the current framework and project setup\n */\n public async detectFramework(): Promise<FrameworkInfo> {\n const packageJsonPath = path.join(this.projectRoot, 'package.json');\n \n if (!fs.existsSync(packageJsonPath)) {\n return {\n name: 'vanilla',\n type: 'vanilla',\n projectRoot: this.projectRoot\n };\n }\n\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));\n const dependencies = {\n ...packageJson.dependencies,\n ...packageJson.devDependencies\n };\n\n // Detect framework with version information\n let framework: FrameworkInfo = {\n name: 'vanilla',\n type: 'vanilla',\n projectRoot: this.projectRoot,\n features: {}\n };\n\n if (dependencies.nuxt) {\n const nuxtVersion = dependencies.nuxt;\n const isNuxt3 = this.isVersionGte(nuxtVersion, '3.0.0');\n \n framework = {\n name: 'nuxt',\n type: 'nuxt',\n version: nuxtVersion,\n majorVersion: this.getMajorVersion(nuxtVersion),\n hasTypeScript: !!dependencies.typescript,\n hasRouter: true,\n projectRoot: this.projectRoot,\n features: {\n hasNuxt3: isNuxt3\n }\n };\n } else if (dependencies.next) {\n const nextVersion = dependencies.next;\n const isNext13 = this.isVersionGte(nextVersion, '13.0.0');\n \n framework = {\n name: 'nextjs',\n type: 'nextjs',\n version: nextVersion,\n majorVersion: this.getMajorVersion(nextVersion),\n hasTypeScript: !!dependencies.typescript || !!dependencies['@types/node'],\n hasRouter: true,\n projectRoot: this.projectRoot,\n features: {\n hasNextAppRouter: isNext13\n }\n };\n } else if (dependencies['@remix-run/react'] || dependencies['@remix-run/dev']) {\n const remixVersion = dependencies['@remix-run/react'] || dependencies['@remix-run/dev'];\n framework = {\n name: 'remix',\n type: 'remix',\n version: remixVersion,\n majorVersion: this.getMajorVersion(remixVersion),\n hasTypeScript: !!dependencies.typescript || !!dependencies['@types/react'],\n hasRouter: true,\n projectRoot: this.projectRoot,\n features: {}\n };\n } else if (dependencies.react) {\n const reactVersion = dependencies.react;\n const isReact18 = this.isVersionGte(reactVersion, '18.0.0');\n \n framework = {\n name: 'react',\n type: 'react',\n version: reactVersion,\n majorVersion: this.getMajorVersion(reactVersion),\n hasTypeScript: !!dependencies.typescript || !!dependencies['@types/react'],\n hasRouter: !!dependencies['react-router-dom'] || !!dependencies['react-router'],\n projectRoot: this.projectRoot,\n features: {\n hasReact18: isReact18\n }\n };\n } else if (dependencies.vue) {\n const vueVersion = dependencies.vue;\n const isVue3 = this.isVersionGte(vueVersion, '3.0.0');\n \n framework = {\n name: 'vue',\n type: 'vue',\n version: vueVersion,\n majorVersion: this.getMajorVersion(vueVersion),\n hasTypeScript: !!dependencies.typescript || !!dependencies['@vue/cli-service'],\n hasRouter: !!dependencies['vue-router'],\n projectRoot: this.projectRoot,\n features: {\n hasVue3: isVue3\n }\n };\n } else if (dependencies['@angular/core']) {\n const angularVersion = dependencies['@angular/core'];\n const isAngular17 = this.isVersionGte(angularVersion, '17.0.0');\n \n framework = {\n name: 'angular',\n type: 'angular',\n version: angularVersion,\n majorVersion: this.getMajorVersion(angularVersion),\n hasTypeScript: true,\n hasRouter: true,\n projectRoot: this.projectRoot,\n features: {\n hasAngularStandalone: isAngular17\n }\n };\n } else if (dependencies.svelte) {\n const svelteVersion = dependencies.svelte;\n const isSvelteKit = !!dependencies['@sveltejs/kit'];\n \n framework = {\n name: 'svelte',\n type: 'svelte',\n version: svelteVersion,\n majorVersion: this.getMajorVersion(svelteVersion),\n hasTypeScript: !!dependencies.typescript || !!dependencies['svelte-check'],\n hasRouter: !!dependencies['svelte-routing'] || !!dependencies['@sveltejs/kit'],\n projectRoot: this.projectRoot,\n features: {\n hasSvelteKit: isSvelteKit\n }\n };\n } else if (dependencies.astro) {\n const astroVersion = dependencies.astro;\n framework = {\n name: 'astro',\n type: 'astro',\n version: astroVersion,\n majorVersion: this.getMajorVersion(astroVersion),\n hasTypeScript: !!dependencies.typescript || !!dependencies['@astrojs/ts-plugin'],\n hasRouter: true,\n projectRoot: this.projectRoot,\n features: {}\n };\n } else if (dependencies.gatsby) {\n const gatsbyVersion = dependencies.gatsby;\n framework = {\n name: 'gatsby',\n type: 'gatsby',\n version: gatsbyVersion,\n majorVersion: this.getMajorVersion(gatsbyVersion),\n hasTypeScript: !!dependencies.typescript || !!dependencies['@types/react'],\n hasRouter: true,\n projectRoot: this.projectRoot,\n features: {}\n };\n }\n\n // Detect bundler\n if (dependencies.vite) {\n framework.bundler = 'vite';\n } else if (dependencies.webpack) {\n framework.bundler = 'webpack';\n } else if (dependencies.esbuild) {\n framework.bundler = 'esbuild';\n } else if (dependencies.rollup) {\n framework.bundler = 'rollup';\n }\n\n // Detect package manager\n if (fs.existsSync(path.join(this.projectRoot, 'yarn.lock'))) {\n framework.packageManager = 'yarn';\n } else if (fs.existsSync(path.join(this.projectRoot, 'pnpm-lock.yaml'))) {\n framework.packageManager = 'pnpm';\n } else {\n framework.packageManager = 'npm';\n }\n\n return framework;\n }\n\n /**\n * Install the SDK package with latest version range\n */\n protected async installPackage(): Promise<void> {\n \n // Build base command with latest version range\n let command = this.framework?.packageManager === 'yarn' \n ? 'yarn add humanbehavior-js@latest'\n : this.framework?.packageManager === 'pnpm'\n ? 'pnpm add humanbehavior-js@latest'\n : 'npm install humanbehavior-js@latest';\n \n // Add legacy peer deps flag for npm to handle dependency conflicts\n if (this.framework?.packageManager !== 'yarn' && this.framework?.packageManager !== 'pnpm') {\n command += ' --legacy-peer-deps';\n }\n\n try {\n execSync(command, { cwd: this.projectRoot, stdio: 'inherit' });\n } catch (error) {\n throw new Error(`Failed to install humanbehavior-js: ${error}`);\n }\n }\n\n /**\n * Generate code modifications based on framework\n */\n protected async generateModifications(): Promise<CodeModification[]> {\n const modifications: CodeModification[] = [];\n\n switch (this.framework?.type) {\n case 'react':\n modifications.push(...await this.generateReactModifications());\n break;\n case 'nextjs':\n modifications.push(...await this.generateNextJSModifications());\n break;\n case 'nuxt':\n modifications.push(...await this.generateNuxtModifications());\n break;\n case 'astro':\n modifications.push(...await this.generateAstroModifications());\n break;\n case 'gatsby':\n modifications.push(...await this.generateGatsbyModifications());\n break;\n case 'remix':\n modifications.push(...await this.generateRemixModifications());\n break;\n case 'vue':\n modifications.push(...await this.generateVueModifications());\n break;\n case 'angular':\n modifications.push(...await this.generateAngularModifications());\n break;\n case 'svelte':\n modifications.push(...await this.generateSvelteModifications());\n break;\n default:\n modifications.push(...await this.generateVanillaModifications());\n }\n\n return modifications;\n }\n\n /**\n * Generate React-specific modifications\n */\n private async generateReactModifications(): Promise<CodeModification[]> {\n const modifications: CodeModification[] = [];\n \n // Find main App component or index file\n const appFile = this.findReactAppFile();\n if (appFile) {\n const content = fs.readFileSync(appFile, 'utf8');\n const modifiedContent = this.injectReactProvider(content, appFile);\n \n modifications.push({\n filePath: appFile,\n action: 'modify',\n content: modifiedContent,\n description: 'Added HumanBehaviorProvider to React app'\n });\n }\n\n // Create or append to environment file\n modifications.push(this.createEnvironmentModification(this.framework!));\n\n return modifications;\n }\n\n /**\n * Helper: Merge HBProvider into existing providers.tsx file\n */\n private mergeProvidersFile(filePath: string): string {\n const hbProviderContent = `export function HBProvider({ children }: { children: React.ReactNode }) {\n return (\n <HumanBehaviorProvider apiKey={process.env.NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY}>\n {children}\n </HumanBehaviorProvider>\n );\n}`;\n\n if (!fs.existsSync(filePath)) {\n // File doesn't exist, create new file\n return `'use client';\n\nimport { HumanBehaviorProvider } from 'humanbehavior-js/react';\n\n${hbProviderContent}`;\n }\n\n // File exists, read and merge\n const existingContent = fs.readFileSync(filePath, 'utf8');\n \n // Check if HBProvider already exists\n if (existingContent.includes('export function HBProvider') || existingContent.includes('export const HBProvider')) {\n // Already exists, return unchanged\n return existingContent;\n }\n\n // Check if HumanBehaviorProvider import exists\n let modifiedContent = existingContent;\n if (!existingContent.includes(\"from 'humanbehavior-js/react'\")) {\n // Add the import - try to add after 'use client' or at the top\n if (existingContent.includes(\"'use client'\")) {\n modifiedContent = existingContent.replace(\n /('use client';?)\\s*\\n/,\n `$1\\n\\nimport { HumanBehaviorProvider } from 'humanbehavior-js/react';\\n`\n );\n } else {\n // Add at the top\n modifiedContent = `import { HumanBehaviorProvider } from 'humanbehavior-js/react';\\n\\n${existingContent}`;\n }\n }\n\n // Add HBProvider export at the end\n // Ensure there's proper spacing before adding the export\n const trimmed = modifiedContent.trimEnd();\n if (trimmed === '') {\n // File is empty (after trimming trailing whitespace)\n modifiedContent = hbProviderContent;\n } else {\n // Add double newline for separation\n modifiedContent = `${trimmed}\\n\\n${hbProviderContent}`;\n }\n\n return modifiedContent;\n }\n\n /**\n * Generate Next.js-specific modifications\n */\n private async generateNextJSModifications(): Promise<CodeModification[]> {\n const modifications: CodeModification[] = [];\n \n // Check for App Router - try both with and without src directory\n const appLayoutFileWithSrc = path.join(this.projectRoot, 'src', 'app', 'layout.tsx');\n const appLayoutFile = path.join(this.projectRoot, 'app', 'layout.tsx');\n const pagesLayoutFileWithSrc = path.join(this.projectRoot, 'src', 'pages', '_app.tsx');\n const pagesLayoutFile = path.join(this.projectRoot, 'pages', '_app.tsx');\n \n // Determine which layout file exists and set paths accordingly\n let actualAppLayoutFile: string | null = null;\n let providersFilePath: string | null = null;\n let providersImportPath: string | null = null;\n \n if (fs.existsSync(appLayoutFileWithSrc)) {\n actualAppLayoutFile = appLayoutFileWithSrc;\n providersFilePath = path.join(this.projectRoot, 'src', 'app', 'providers.tsx');\n providersImportPath = '@/app/providers';\n } else if (fs.existsSync(appLayoutFile)) {\n actualAppLayoutFile = appLayoutFile;\n providersFilePath = path.join(this.projectRoot, 'app', 'providers.tsx');\n providersImportPath = '@/app/providers';\n }\n \n if (actualAppLayoutFile) {\n // Merge or create providers.tsx file\n const providersContent = this.mergeProvidersFile(providersFilePath!);\n const fileExists = fs.existsSync(providersFilePath!);\n \n modifications.push({\n filePath: providersFilePath!,\n action: fileExists ? 'modify' : 'create',\n content: providersContent,\n description: fileExists \n ? 'Merged HBProvider into existing providers.tsx file'\n : 'Created providers.tsx file with HBProvider for Next.js App Router'\n });\n\n // Modify layout.tsx to use the provider\n const content = fs.readFileSync(actualAppLayoutFile, 'utf8');\n const modifiedContent = this.injectNextJSAppRouter(content, providersImportPath!);\n \n modifications.push({\n filePath: actualAppLayoutFile,\n action: 'modify',\n content: modifiedContent,\n description: 'Added HumanBehavior provider wrapper to Next.js App Router layout'\n });\n } else if (fs.existsSync(pagesLayoutFileWithSrc) || fs.existsSync(pagesLayoutFile)) {\n const actualPagesLayoutFile = fs.existsSync(pagesLayoutFileWithSrc) ? pagesLayoutFileWithSrc : pagesLayoutFile;\n const providersPath = fs.existsSync(pagesLayoutFileWithSrc) \n ? path.join(this.projectRoot, 'src', 'components', 'HumanBehaviorProvider.tsx')\n : path.join(this.projectRoot, 'components', 'HumanBehaviorProvider.tsx');\n const importPath = fs.existsSync(pagesLayoutFileWithSrc) \n ? '../components/HumanBehaviorProvider'\n : './components/HumanBehaviorProvider';\n \n // Create dedicated HumanBehavior provider file for Pages Router\n modifications.push({\n filePath: providersPath,\n action: 'create',\n content: `'use client';\n\nimport { HumanBehaviorProvider } from 'humanbehavior-js/react';\n\nexport function HBProvider({ children }: { children: React.ReactNode }) {\n return (\n <HumanBehaviorProvider apiKey={process.env.NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY}>\n {children}\n </HumanBehaviorProvider>\n );\n}`,\n description: 'Created HumanBehavior provider file for Pages Router'\n });\n\n // Modify _app.tsx to use the provider\n const content = fs.readFileSync(actualPagesLayoutFile, 'utf8');\n const modifiedContent = this.injectNextJSPagesRouter(content, importPath);\n \n modifications.push({\n filePath: actualPagesLayoutFile,\n action: 'modify',\n content: modifiedContent,\n description: 'Added HumanBehavior provider wrapper to Next.js Pages Router'\n });\n }\n\n // Create or append to environment file\n modifications.push(this.createEnvironmentModification(this.framework!));\n\n return modifications;\n }\n\n /**\n * Generate Astro-specific modifications\n */\n private async generateAstroModifications(): Promise<CodeModification[]> {\n const modifications: CodeModification[] = [];\n\n // Create Astro component for HumanBehavior\n const astroComponentPath = path.join(this.projectRoot, 'src', 'components', 'HumanBehavior.astro');\n const astroComponentContent = `---\n// This component will only run on the client side\n---\n\n<script>\n import { HumanBehaviorTracker } from 'humanbehavior-js';\n const apiKey = import.meta.env.PUBLIC_HUMANBEHAVIOR_API_KEY;\n if (apiKey) {\n HumanBehaviorTracker.init(apiKey);\n }\n</script>`;\n\n modifications.push({\n filePath: astroComponentPath,\n action: 'create',\n content: astroComponentContent,\n description: 'Created Astro component for HumanBehavior SDK'\n });\n\n // Find and update layout file\n const layoutFiles = [\n path.join(this.projectRoot, 'src', 'layouts', 'Layout.astro'),\n path.join(this.projectRoot, 'src', 'layouts', 'layout.astro'),\n path.join(this.projectRoot, 'src', 'layouts', 'BaseLayout.astro')\n ];\n\n let layoutFile = null;\n for (const file of layoutFiles) {\n if (fs.existsSync(file)) {\n layoutFile = file;\n break;\n }\n }\n\n if (layoutFile) {\n const content = fs.readFileSync(layoutFile, 'utf8');\n const modifiedContent = this.injectAstroLayout(content);\n \n modifications.push({\n filePath: layoutFile,\n action: 'modify',\n content: modifiedContent,\n description: 'Added HumanBehavior component to Astro layout'\n });\n }\n\n // Add environment variable\n modifications.push(this.createEnvironmentModification(this.framework!));\n\n return modifications;\n }\n\n /**\n * Generate Nuxt-specific modifications\n */\n private async generateNuxtModifications(): Promise<CodeModification[]> {\n const modifications: CodeModification[] = [];\n \n // Create plugin file for Nuxt (in app directory)\n const pluginFile = path.join(this.projectRoot, 'app', 'plugins', 'humanbehavior.client.ts');\n modifications.push({\n filePath: pluginFile,\n action: 'create',\n content: `import { HumanBehaviorTracker } from 'humanbehavior-js';\n\nexport default defineNuxtPlugin(() => {\n const config = useRuntimeConfig();\n if (typeof window !== 'undefined') {\n const apiKey = config.public.humanBehaviorApiKey;\n if (apiKey) {\n HumanBehaviorTracker.init(apiKey);\n }\n }\n});`,\n description: 'Created Nuxt plugin for HumanBehavior SDK in app directory'\n });\n\n // Create environment configuration\n const nuxtConfigFile = path.join(this.projectRoot, 'nuxt.config.ts');\n {\n const mod = this.applyOrNotify(\n nuxtConfigFile,\n (c) => this.injectNuxtConfig(c),\n 'Added HumanBehavior runtime config to Nuxt config',\n 'Nuxt: Add inside defineNuxtConfig({ … }):\\nruntimeConfig: { public: { humanBehaviorApiKey: process.env.NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY } },'\n );\n if (mod) modifications.push(mod);\n }\n\n // Create or append to environment file\n modifications.push(this.createEnvironmentModification(this.framework!));\n\n return modifications;\n }\n\n /**\n * Generate Remix-specific modifications\n */\n private async generateRemixModifications(): Promise<CodeModification[]> {\n const modifications: CodeModification[] = [];\n \n // Find root.tsx file\n const rootFile = path.join(this.projectRoot, 'app', 'root.tsx');\n if (fs.existsSync(rootFile)) {\n const content = fs.readFileSync(rootFile, 'utf8');\n const modifiedContent = this.injectRemixProvider(content);\n \n modifications.push({\n filePath: rootFile,\n action: 'modify',\n content: modifiedContent,\n description: 'Added HumanBehaviorProvider to Remix root component'\n });\n }\n\n // Create or append to environment file\n modifications.push(this.createEnvironmentModification(this.framework!));\n\n return modifications;\n }\n\n /**\n * Generate Vue-specific modifications\n */\n private async generateVueModifications(): Promise<CodeModification[]> {\n const modifications: CodeModification[] = [];\n \n // Find main.js or main.ts\n const mainFile = this.findVueMainFile();\n // Create Vue composable per docs (idempotent)\n const composableDir = path.join(this.projectRoot, 'src', 'composables');\n const composablePath = path.join(composableDir, 'useHumanBehavior.ts');\n const composableContent = `import { HumanBehaviorTracker } from 'humanbehavior-js'\n\nexport function useHumanBehavior() {\n const apiKey = import.meta.env.VITE_HUMANBEHAVIOR_API_KEY\n \n if (apiKey) {\n const tracker = HumanBehaviorTracker.init(apiKey);\n \n return { tracker }\n }\n \n return { tracker: null }\n}\n`;\n try {\n if (!fs.existsSync(composableDir)) {\n fs.mkdirSync(composableDir, { recursive: true });\n }\n if (!fs.existsSync(composablePath)) {\n modifications.push({\n filePath: composablePath,\n action: 'create',\n content: composableContent,\n description: 'Created Vue composable useHumanBehavior'\n });\n }\n } catch {}\n if (mainFile) {\n const content = fs.readFileSync(mainFile, 'utf8');\n const modifiedContent = this.injectVuePlugin(content);\n \n modifications.push({\n filePath: mainFile,\n action: 'modify',\n content: modifiedContent,\n description: 'Added HumanBehaviorPlugin to Vue app'\n });\n }\n\n // Create or append to environment file\n modifications.push(this.createEnvironmentModification(this.framework!));\n\n return modifications;\n }\n\n /**\n * Generate Angular-specific modifications\n */\n private async generateAngularModifications(): Promise<CodeModification[]> {\n const modifications: CodeModification[] = [];\n \n // Create Angular service (docs pattern)\n const serviceDir = path.join(this.projectRoot, 'src', 'app', 'services');\n const servicePath = path.join(serviceDir, 'hb.service.ts');\n const serviceContent = `import { Injectable, NgZone, Inject, PLATFORM_ID } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\nimport { HumanBehaviorTracker } from 'humanbehavior-js';\nimport { environment } from '../../environments/environment';\n\n@Injectable({ providedIn: 'root' })\nexport class HumanBehavior {\n private tracker: ReturnType<typeof HumanBehaviorTracker.init> | null = null;\n\n constructor(private ngZone: NgZone, @Inject(PLATFORM_ID) private platformId: Object) {\n if (isPlatformBrowser(this.platformId)) {\n this.ngZone.runOutsideAngular(() => {\n this.tracker = HumanBehaviorTracker.init(environment.humanBehaviorApiKey);\n });\n }\n }\n\n capture(event: string, props?: Record<string, any>) {\n this.tracker?.customEvent(event, props);\n }\n\n identify(user: Record<string, any>) {\n this.tracker?.identifyUser({ userProperties: user });\n }\n\n trackPageView(path?: string) {\n this.tracker?.trackPageView(path);\n }\n}\n`;\n\n if (!fs.existsSync(serviceDir)) {\n fs.mkdirSync(serviceDir, { recursive: true });\n }\n if (!fs.existsSync(servicePath)) {\n modifications.push({\n filePath: servicePath,\n action: 'create',\n content: serviceContent,\n description: 'Created Angular HumanBehavior service (singleton)'\n });\n }\n\n // Handle Angular environment files (proper Angular way)\n const envFile = path.join(this.projectRoot, 'src', 'environments', 'environment.ts');\n const envProdFile = path.join(this.projectRoot, 'src', 'environments', 'environment.prod.ts');\n \n // Create environments directory if it doesn't exist\n const envDir = path.dirname(envFile);\n if (!fs.existsSync(envDir)) {\n fs.mkdirSync(envDir, { recursive: true });\n }\n \n // Create or update development environment\n if (fs.existsSync(envFile)) {\n const content = fs.readFileSync(envFile, 'utf8');\n if (!content.includes('humanBehaviorApiKey')) {\n const modifiedContent = content.replace(\n /export const environment = {([\\s\\S]*?)};/,\n `export const environment = {\n $1,\n humanBehaviorApiKey: '${this.apiKey}'\n};`\n );\n modifications.push({\n filePath: envFile,\n action: 'modify',\n content: modifiedContent,\n description: 'Added API key to Angular development environment'\n });\n }\n } else {\n // Create new development environment file\n modifications.push({\n filePath: envFile,\n action: 'create',\n content: `export const environment = {\n production: false,\n humanBehaviorApiKey: '${this.apiKey}'\n};`,\n description: 'Created Angular development environment file'\n });\n }\n \n // Create or update production environment\n if (fs.existsSync(envProdFile)) {\n const content = fs.readFileSync(envProdFile, 'utf8');\n if (!content.includes('humanBehaviorApiKey')) {\n const modifiedContent = content.replace(\n /export const environment = {([\\s\\S]*?)};/,\n `export const environment = {\n $1,\n humanBehaviorApiKey: '${this.apiKey}'\n};`\n );\n modifications.push({\n filePath: envProdFile,\n action: 'modify',\n content: modifiedContent,\n description: 'Added API key to Angular production environment'\n });\n }\n } else {\n // Create new production environment file\n modifications.push({\n filePath: envProdFile,\n action: 'create',\n content: `export const environment = {\n production: true,\n humanBehaviorApiKey: '${this.apiKey}'\n};`,\n description: 'Created Angular production environment file'\n });\n }\n\n // For Angular, we don't need .env files since we use environment.ts\n // The environment files are already created above\n\n // Inject service into app component\n const appComponentPath = path.join(this.projectRoot, 'src', 'app', 'app.ts');\n if (fs.existsSync(appComponentPath)) {\n const appContent = fs.readFileSync(appComponentPath, 'utf8');\n \n // Check if already has HumanBehavior service\n if (!appContent.includes('HumanBehavior')) {\n let modifiedAppContent = appContent\n .replace(\n /import { Component } from '@angular\\/core';/,\n `import { Component } from '@angular/core';\nimport { HumanBehavior } from './services/hb.service';`\n )\n .replace(\n /export class App {/,\n `export class App {\n constructor(private readonly humanBehavior: HumanBehavior) {}`\n );\n \n // Do not modify standalone setting; leave component decorator unchanged\n \n modifications.push({\n action: 'modify',\n filePath: appComponentPath,\n content: modifiedAppContent,\n description: 'Injected HumanBehavior service into Angular app component'\n });\n }\n }\n\n return modifications;\n }\n\n /**\n * Generate Svelte-specific modifications\n */\n private async generateSvelteModifications(): Promise<CodeModification[]> {\n const modifications: CodeModification[] = [];\n \n // Check for SvelteKit\n const svelteConfigFile = path.join(this.projectRoot, 'svelte.config.js');\n const isSvelteKit = fs.existsSync(svelteConfigFile);\n \n if (isSvelteKit) {\n // SvelteKit - create layout file\n const layoutFile = path.join(this.projectRoot, 'src', 'routes', '+layout.svelte');\n if (fs.existsSync(layoutFile)) {\n const content = fs.readFileSync(layoutFile, 'utf8');\n const modifiedContent = this.injectSvelteKitLayout(content);\n \n modifications.push({\n filePath: layoutFile,\n action: 'modify',\n content: modifiedContent,\n description: 'Added HumanBehavior tracker init to SvelteKit layout'\n });\n }\n } else {\n // Regular Svelte - modify main file\n const mainFile = this.findSvelteMainFile();\n if (mainFile) {\n const content = fs.readFileSync(mainFile, 'utf8');\n const modifiedContent = this.injectSvelteStore(content);\n \n modifications.push({\n filePath: mainFile,\n action: 'modify',\n content: modifiedContent,\n description: 'Added HumanBehavior tracker init to Svelte app'\n });\n }\n }\n\n // Create or append to environment file\n modifications.push(this.createEnvironmentModification(this.framework!));\n\n return modifications;\n }\n\n /**\n * Generate vanilla JS/TS modifications\n */\n private async generateVanillaModifications(): Promise<CodeModification[]> {\n const modifications: CodeModification[] = [];\n \n // Find HTML file to inject script\n const htmlFile = this.findHTMLFile();\n if (htmlFile) {\n const content = fs.readFileSync(htmlFile, 'utf8');\n const modifiedContent = this.injectVanillaScript(content);\n \n modifications.push({\n filePath: htmlFile,\n action: 'modify',\n content: modifiedContent,\n description: 'Added HumanBehavior CDN script to HTML file'\n });\n }\n\n // Create or append to environment file\n modifications.push(this.createEnvironmentModification(this.framework!));\n\n return modifications;\n }\n\n /**\n * Generate Gatsby-specific modifications\n */\n private async generateGatsbyModifications(): Promise<CodeModification[]> {\n const modifications: CodeModification[] = [];\n \n // Modify or create gatsby-browser.js for Gatsby\n const gatsbyBrowserFile = path.join(this.projectRoot, 'gatsby-browser.js');\n \n if (fs.existsSync(gatsbyBrowserFile)) {\n const content = fs.readFileSync(gatsbyBrowserFile, 'utf8');\n const modifiedContent = this.injectGatsbyBrowser(content);\n \n modifications.push({\n filePath: gatsbyBrowserFile,\n action: 'modify',\n content: modifiedContent,\n description: 'Added HumanBehavior initialization to Gatsby browser'\n });\n } else {\n // Create gatsby-browser.js if it doesn't exist\n modifications.push({\n filePath: gatsbyBrowserFile,\n action: 'create',\n content: `import { HumanBehaviorTracker } from 'humanbehavior-js';\n\nexport const onClientEntry = () => {\n const apiKey = process.env.GATSBY_HUMANBEHAVIOR_API_KEY;\n if (apiKey) {\n HumanBehaviorTracker.init(apiKey);\n }\n};`,\n description: 'Created gatsby-browser.js with HumanBehavior initialization'\n });\n }\n\n // Create or append to environment file\n modifications.push(this.createEnvironmentModification(this.framework!));\n\n return modifications;\n }\n\n\n\n /**\n * Apply modifications to the codebase\n */\n protected async applyModifications(modifications: CodeModification[]): Promise<void> {\n for (const modification of modifications) {\n try {\n const dir = path.dirname(modification.filePath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n\n switch (modification.action) {\n case 'create':\n fs.writeFileSync(modification.filePath, modification.content);\n break;\n case 'modify':\n fs.writeFileSync(modification.filePath, modification.content);\n break;\n case 'append':\n fs.appendFileSync(modification.filePath, '\\n' + modification.content);\n break;\n }\n } catch (error) {\n throw new Error(`Failed to apply modification to ${modification.filePath}: ${error}`);\n }\n }\n }\n\n /**\n * Generate next steps for the user\n */\n private generateNextSteps(): string[] {\n const steps = [\n '✅ SDK installed and configured automatically!',\n '🚀 Your app is now tracking user behavior',\n '📊 View sessions in your HumanBehavior dashboard',\n '🔧 Customize tracking in your code as needed'\n ];\n\n if (this.framework?.type === 'react' || this.framework?.type === 'nextjs') {\n steps.push('💡 Use the useHumanBehavior() hook to track custom events');\n }\n\n // Append any manual notes gathered during transformation\n if (this.manualNotes.length) {\n steps.push(...this.manualNotes.map((n) => `⚠️ ${n}`));\n }\n\n return steps;\n }\n\n /**\n * Helper: apply a file transform or record a manual instruction if unchanged/missing\n */\n private applyOrNotify(\n filePath: string,\n transform: (content: string) => string,\n description: string,\n manualNote: string\n ): CodeModification | null {\n if (!fs.existsSync(filePath)) {\n this.manualNotes.push(`${manualNote} (file missing: ${path.relative(this.projectRoot, filePath)})`);\n return null;\n }\n const original = fs.readFileSync(filePath, 'utf8');\n const updated = transform(original);\n if (updated !== original) {\n return {\n filePath,\n action: 'modify',\n content: updated,\n description\n };\n }\n this.manualNotes.push(manualNote);\n return null;\n }\n\n // Helper methods for file detection and content injection\n private findReactAppFile(): string | null {\n const possibleFiles = [\n 'src/App.jsx', 'src/App.js', 'src/App.tsx', 'src/App.ts',\n 'src/index.js', 'src/index.tsx', 'src/main.js', 'src/main.tsx'\n ];\n\n for (const file of possibleFiles) {\n const fullPath = path.join(this.projectRoot, file);\n if (fs.existsSync(fullPath)) {\n return fullPath;\n }\n }\n return null;\n }\n\n private findVueMainFile(): string | null {\n const possibleFiles = [\n 'src/main.js', 'src/main.ts', 'src/main.jsx', 'src/main.tsx'\n ];\n\n for (const file of possibleFiles) {\n const fullPath = path.join(this.projectRoot, file);\n if (fs.existsSync(fullPath)) {\n return fullPath;\n }\n }\n return null;\n }\n\n private findSvelteMainFile(): string | null {\n const possibleFiles = [\n 'src/main.js', 'src/main.ts', 'src/main.svelte'\n ];\n\n for (const file of possibleFiles) {\n const fullPath = path.join(this.projectRoot, file);\n if (fs.existsSync(fullPath)) {\n return fullPath;\n }\n }\n return null;\n }\n\n private findHTMLFile(): string | null {\n const possibleFiles = ['index.html', 'public/index.html', 'dist/index.html'];\n\n for (const file of possibleFiles) {\n const fullPath = path.join(this.projectRoot, file);\n if (fs.existsSync(fullPath)) {\n return fullPath;\n }\n }\n return null;\n }\n\n private injectReactProvider(content: string, filePath: string): string {\n const isTypeScript = filePath.endsWith('.tsx') || filePath.endsWith('.ts');\n \n // Check if already has HumanBehaviorProvider\n if (content.includes('HumanBehaviorProvider')) {\n return content;\n }\n\n // Determine the correct environment variable syntax based on bundler\n const isVite = this.framework?.bundler === 'vite';\n const envVar = isVite \n ? 'import.meta.env.VITE_HUMANBEHAVIOR_API_KEY!' \n : 'process.env.REACT_APP_HUMANBEHAVIOR_API_KEY!';\n\n const importStatement = `import { HumanBehaviorProvider } from 'humanbehavior-js/react';`;\n\n // Enhanced parsing for React 18+ features\n const hasReact18 = this.framework?.features?.hasReact18;\n \n // Handle different React patterns\n if (content.includes('function App()') || content.includes('const App =')) {\n // Add import statement\n let modifiedContent = content.replace(\n /(import.*?from.*?['\"]react['\"];?)/,\n `$1\\n${importStatement}`\n );\n \n // If no React import found, add it at the top\n if (!modifiedContent.includes(importStatement)) {\n modifiedContent = `${importStatement}\\n\\n${modifiedContent}`;\n }\n \n // Wrap the App component return with HumanBehaviorProvider\n modifiedContent = modifiedContent.replace(\n /return\\s*\\(([\\s\\S]*?)\\)\\s*;/,\n `return (\n <HumanBehaviorProvider apiKey={${envVar}}>\n $1\n </HumanBehaviorProvider>\n );`\n );\n \n return modifiedContent;\n }\n \n // Handle React 18+ createRoot pattern\n if (hasReact18 && content.includes('createRoot')) {\n let modifiedContent = content.replace(\n /(import.*?from.*?['\"]react['\"];?)/,\n `$1\\n${importStatement}`\n );\n \n if (!modifiedContent.includes(importStatement)) {\n modifiedContent = `${importStatement}\\n\\n${modifiedContent}`;\n }\n \n // Wrap the root render with HumanBehaviorProvider\n modifiedContent = modifiedContent.replace(\n /(root\\.render\\s*\\([\\s\\S]*?\\)\\s*;)/,\n `root.render(\n <HumanBehaviorProvider apiKey={${envVar}}>\n $1\n </HumanBehaviorProvider>\n );`\n );\n \n return modifiedContent;\n }\n\n // Fallback: simple injection\n return `${importStatement}\\n\\n${content}`;\n }\n\n private injectNextJSAppRouter(content: string, importPath: string = '@/app/providers'): string {\n if (content.includes('HBProvider')) {\n return content;\n }\n\n const importStatement = `import { HBProvider } from '${importPath}';`;\n \n // First, add the import statement\n let modifiedContent = content.replace(\n /export default function RootLayout/,\n `${importStatement}\\n\\nexport default function RootLayout`\n );\n \n // Then wrap the body content with Providers\n // Use a more specific approach to handle the body content\n modifiedContent = modifiedContent.replace(\n /<body([^>]*)>([\\s\\S]*?)<\\/body>/,\n (match, bodyAttrs, bodyContent) => {\n // Trim whitespace and newlines from bodyContent\n const trimmedContent = bodyContent.trim();\n return `<body${bodyAttrs}>\n <HBProvider>\n ${trimmedContent}\n </HBProvider>\n </body>`;\n }\n );\n \n return modifiedContent;\n }\n\n private injectNextJSPagesRouter(content: string, importPath: string = '../components/HumanBehaviorProvider'): string {\n if (content.includes('HBProvider')) {\n return content;\n }\n\n const importStatement = `import { HBProvider } from '${importPath}';`;\n \n return content.replace(\n /function MyApp/,\n `${importStatement}\\n\\nfunction MyApp`\n ).replace(\n /return \\(([\\s\\S]*?)\\);/,\n `return (\n <HBProvider>\n $1\n </HBProvider>\n );`\n );\n }\n\n private injectRemixProvider(content: string): string {\n if (content.includes('HumanBehaviorProvider')) {\n return content;\n }\n\n let modifiedContent = content;\n \n // Step 1: Add useLoaderData import\n if (!content.includes('useLoaderData')) {\n modifiedContent = modifiedContent.replace(\n /(} from ['\"]@remix-run\\/react['\"];?\\s*)/,\n `$1import { useLoaderData } from '@remix-run/react';\n`\n );\n }\n \n // Step 2: Add HumanBehaviorProvider import\n if (!content.includes('HumanBehaviorProvider')) {\n modifiedContent = modifiedContent.replace(\n /(} from ['\"]@remix-run\\/react['\"];?\\s*)/,\n `$1import { HumanBehaviorProvider } from 'humanbehavior-js/react';\n`\n );\n }\n \n // Step 3: Add LoaderFunctionArgs import\n if (!content.includes('LoaderFunctionArgs')) {\n modifiedContent = modifiedContent.replace(\n /(} from ['\"]@remix-run\\/node['\"];?\\s*)/,\n `$1import type { LoaderFunctionArgs } from '@remix-run/node';\n`\n );\n }\n\n // Step 4: Add loader function before Layout function\n if (!content.includes('export const loader')) {\n modifiedContent = modifiedContent.replace(\n /(export function Layout)/,\n `export const loader = async ({ request }: LoaderFunctionArgs) => {\n return {\n ENV: {\n HUMANBEHAVIOR_API_KEY: process.env.HUMANBEHAVIOR_API_KEY,\n },\n };\n};\n\n$1`\n );\n }\n\n // Step 5: Add useLoaderData call and wrap App function's return content with HumanBehaviorProvider\n if (!content.includes('const data = useLoaderData')) {\n modifiedContent = modifiedContent.replace(\n /(export default function App\\(\\) \\{\\s*)(return \\(\\s*<div[^>]*>[\\s\\S]*?<\\/div>\\s*\\);\\s*\\})/,\n `$1const data = useLoaderData<typeof loader>();\n \n return (\n <HumanBehaviorProvider apiKey={data.ENV.HUMANBEHAVIOR_API_KEY}>\n <div className=\"min-h-screen bg-gray-50\">\n <Navigation />\n <Outlet />\n </div>\n </HumanBehaviorProvider>\n );\n}`\n );\n }\n\n return modifiedContent;\n }\n\n private injectVuePlugin(content: string): string {\n // New: use composable/tracker pattern per docs; idempotent and migrates from plugin\n if (content.includes('useHumanBehavior')) {\n return content;\n }\n\n const hasVue3 = this.framework?.features?.hasVue3;\n const isVue3ByContent = content.includes('createApp') || content.includes('import { createApp }');\n \n let modifiedContent = content\n .replace(/import\\s*\\{\\s*HumanBehaviorPlugin\\s*\\}\\s*from\\s*['\\\"]humanbehavior-js\\/vue['\\\"];?/g, '')\n .replace(/app\\.use\\(\\s*HumanBehaviorPlugin[\\s\\S]*?\\);?/g, '');\n\n if (hasVue3 || isVue3ByContent) {\n const importComposable = `import { useHumanBehavior } from './composables/useHumanBehavior';`;\n if (!modifiedContent.includes(importComposable)) {\n const lastImportIndex = modifiedContent.lastIndexOf('import');\n if (lastImportIndex !== -1) {\n const nextLineIndex = modifiedContent.indexOf('\\n', lastImportIndex);\n if (nextLineIndex !== -1) {\n modifiedContent = modifiedContent.slice(0, nextLineIndex + 1) + importComposable + '\\n' + modifiedContent.slice(nextLineIndex + 1);\n } else {\n modifiedContent = modifiedContent + '\\n' + importComposable;\n }\n } else {\n modifiedContent = importComposable + '\\n' + modifiedContent;\n }\n }\n if (modifiedContent.includes('createApp')) {\n modifiedContent = modifiedContent.replace(\n /(const\\s+app\\s*=\\s*createApp\\([^)]*\\))/,\n `$1\\nconst { tracker } = useHumanBehavior();`\n );\n }\n return modifiedContent;\n } else {\n const trackerImport = `import { HumanBehaviorTracker } from 'humanbehavior-js';`;\n if (!modifiedContent.includes(trackerImport)) {\n modifiedContent = `${trackerImport}\\n${modifiedContent}`;\n }\n if (modifiedContent.includes('new Vue')) {\n modifiedContent = modifiedContent.replace(\n /(new\\s+Vue\\s*\\()/,\n `HumanBehaviorTracker.init(process.env.VUE_APP_HUMANBEHAVIOR_API_KEY || import.meta?.env?.VITE_HUMANBEHAVIOR_API_KEY);\\n$1`\n );\n }\n return modifiedContent;\n }\n }\n\n private injectAngularModule(content: string): string {\n if (content.includes('HumanBehaviorModule')) {\n return content;\n }\n\n const importStatement = `import { HumanBehaviorModule } from 'humanbehavior-js/angular';`;\n const environmentImport = `import { environment } from '../environments/environment';`;\n \n // Add environment import if not present\n let modifiedContent = content;\n if (!content.includes('environment')) {\n modifiedContent = content.replace(\n /import.*from.*['\"]@angular/,\n `${environmentImport}\\n$&`\n );\n }\n \n return modifiedContent.replace(\n /imports:\\s*\\[([\\s\\S]*?)\\]/,\n `imports: [\n $1,\n HumanBehaviorModule.forRoot({\n apiKey: environment.humanBehaviorApiKey\n })\n ]`\n ).replace(\n /import.*from.*['\"]@angular/,\n `$&\\n${importStatement}`\n );\n }\n\n private injectAngularStandaloneInit(content: string): string {\n if (content.includes('initializeHumanBehavior')) {\n return content;\n }\n\n const importStatement = `import { initializeHumanBehavior } from 'humanbehavior-js/angular';`;\n const environmentImport = `import { environment } from './environments/environment';`;\n \n // Add imports at the top\n let modifiedContent = content.replace(\n /import.*from.*['\"]@angular/,\n `${importStatement}\\n${environmentImport}\\n$&`\n );\n\n // Add initialization after bootstrapApplication\n modifiedContent = modifiedContent.replace(\n /(bootstrapApplication\\([^}]+\\}?\\)(?:\\s*\\.catch[^;]+;)?)/,\n `$1\n\n// Initialize HumanBehavior SDK (client-side only)\nif (typeof window !== 'undefined') {\n const tracker = initializeHumanBehavior(environment.humanBehaviorApiKey);\n}`\n );\n\n return modifiedContent;\n }\n\n private injectSvelteStore(content: string): string {\n // Direct tracker init for non-SSR Svelte\n if (content.includes('HumanBehaviorTracker.init')) {\n return content;\n }\n const importStatement = `import { HumanBehaviorTracker } from 'humanbehavior-js';`;\n const initCode = `// Initialize HumanBehavior SDK\\nHumanBehaviorTracker.init(import.meta.env?.VITE_HUMANBEHAVIOR_API_KEY || process.env.PUBLIC_HUMANBEHAVIOR_API_KEY || '');`;\n return `${importStatement}\\n${initCode}\\n\\n${content}`;\n }\n\n private injectSvelteKitLayout(content: string): string {\n // Direct tracker init with browser guard for SvelteKit\n if (content.includes('HumanBehaviorTracker.init')) {\n return content;\n }\n const envImport = `import { PUBLIC_HUMANBEHAVIOR_API_KEY } from '$env/static/public';`;\n const hbImport = `import { HumanBehaviorTracker } from 'humanbehavior-js';`;\n const browserImport = `import { browser } from '$app/environment';`;\n const initCode = `if (browser) {\\n const apiKey = PUBLIC_HUMANBEHAVIOR_API_KEY || import.meta.env.VITE_HUMANBEHAVIOR_API_KEY;\\n if (apiKey) {\\n HumanBehaviorTracker.init(apiKey);\\n }\\n}`;\n\n if (content.includes('<script lang=\"ts\">')) {\n return content.replace(\n /<script lang=\"ts\">/,\n `<script lang=\"ts\">\\n\\t${browserImport}\\n\\t${envImport}\\n\\t${hbImport}\\n\\t${initCode}`\n );\n } else if (content.includes('<script>')) {\n return content.replace(\n /<script>/,\n `<script>\\n\\t${browserImport}\\n\\t${envImport}\\n\\t${hbImport}\\n\\t${initCode}`\n );\n } else {\n return `<script lang=\"ts\">\\n${browserImport}\\n${envImport}\\n${hbImport}\\n${initCode}\\n</script>\\n\\n${content}`;\n }\n }\n\n private injectVanillaScript(content: string): string {\n if (content.includes('humanbehavior-js')) {\n return content;\n }\n\n const cdnScript = `<script src=\"https://unpkg.com/humanbehavior-js@latest/dist/index.min.js\"></script>`;\n const initScript = `<script>\n // Initialize HumanBehavior SDK\n // Note: For vanilla HTML, the API key must be hardcoded since env vars aren't available\n const tracker = HumanBehaviorTracker.init('${this.apiKey}');\n</script>`;\n \n return content.replace(\n /<\\/head>/,\n ` ${cdnScript}\\n ${initScript}\\n</head>`\n );\n }\n\n /**\n * Inject Astro layout with HumanBehavior component\n */\n private injectAstroLayout(content: string): string {\n // Check if HumanBehavior component is already imported\n if (content.includes('HumanBehavior') || content.includes('humanbehavior-js')) {\n return content; // Already has HumanBehavior\n }\n\n // Add import inside frontmatter if not present\n let modifiedContent = content;\n if (!content.includes('import HumanBehavior')) {\n const importStatement = 'import HumanBehavior from \\'../components/HumanBehavior.astro\\';';\n const frontmatterEndIndex = content.indexOf('---', 3);\n if (frontmatterEndIndex !== -1) {\n // Insert import inside frontmatter, before the closing ---\n modifiedContent = content.slice(0, frontmatterEndIndex) + '\\n' + importStatement + '\\n' + content.slice(frontmatterEndIndex);\n } else {\n // No frontmatter, add at the very beginning\n modifiedContent = '---\\n' + importStatement + '\\n---\\n\\n' + content;\n }\n }\n\n // Find the closing </body> tag and add HumanBehavior component before it\n const bodyCloseIndex = modifiedContent.lastIndexOf('</body>');\n if (bodyCloseIndex === -1) {\n // No body tag found, append to end\n return modifiedContent + '\\n\\n<HumanBehavior />';\n }\n\n // Add component before closing body tag\n return modifiedContent.slice(0, bodyCloseIndex) + ' <HumanBehavior />\\n' + modifiedContent.slice(bodyCloseIndex);\n }\n\n private injectNuxtConfig(content: string): string {\n if (content.includes('humanBehaviorApiKey')) {\n return content;\n }\n\n // Enhanced Nuxt 3 support with version detection\n const hasNuxt3 = this.framework?.features?.hasNuxt3;\n \n if (hasNuxt3) {\n // Nuxt 3 with runtime config (robust match for opening object)\n const pattern = /export\\s+default\\s+defineNuxtConfig\\s*\\(\\s*\\{/;\n if (pattern.test(content)) {\n const replaced = content.replace(\n pattern,\n `export default defineNuxtConfig({\\n runtimeConfig: {\\n public: {\\n humanBehaviorApiKey: process.env.NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY\\n }\\n },`\n );\n if (replaced !== content) return replaced;\n }\n\n // Fallback: insert runtimeConfig after opening brace of defineNuxtConfig\n const startIdx = content.indexOf('defineNuxtConfig(');\n if (startIdx !== -1) {\n const braceIdx = content.indexOf('{', startIdx);\n if (braceIdx !== -1) {\n const insertion = `\\n runtimeConfig: {\\n public: {\\n humanBehaviorApiKey: process.env.NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY\\n }\\n },`;\n const before = content.slice(0, braceIdx + 1);\n const after = content.slice(braceIdx + 1);\n return `${before}${insertion}${after}`;\n }\n }\n return content;\n } else {\n // Nuxt 2 with env config\n return content.replace(\n /export default \\{/,\n `export default {\n env: {\n humanBehaviorApiKey: process.env.HUMANBEHAVIOR_API_KEY\n },`\n );\n }\n }\n\n private injectGatsbyLayout(content: string): string {\n if (content.includes('HumanBehavior')) {\n return content;\n }\n\n const importStatement = `import HumanBehavior from './HumanBehavior';`;\n const componentUsage = `<HumanBehavior apiKey={process.env.GATSBY_HUMANBEHAVIOR_API_KEY || ''} />`;\n\n // Add import at the top\n let modifiedContent = content.replace(\n /import.*from.*['\"]\\./,\n `${importStatement}\\n$&`\n );\n\n // Add component before closing body tag\n modifiedContent = modifiedContent.replace(\n /(\\s*<\\/body>)/,\n `\\n ${componentUsage}\\n$1`\n );\n\n return modifiedContent;\n }\n\n private injectGatsbyBrowser(content: string): string {\n const importStatement = `import { HumanBehaviorTracker } from 'humanbehavior-js';`;\n\n // If an onClientEntry already exists, merge init into it idempotently\n if (/export\\s+const\\s+onClientEntry\\s*=\\s*\\(/.test(content)) {\n let modified = content;\n\n // Ensure import exists\n if (!modified.includes(\"from 'humanbehavior-js'\")) {\n modified = `${importStatement}\\n${modified}`;\n }\n\n // If init already present, return as-is\n if (modified.includes('HumanBehaviorTracker.init(')) {\n return modified;\n }\n\n // Inject minimal init at start of onClientEntry body\n modified = modified.replace(\n /(export\\s+const\\s+onClientEntry\\s*=\\s*\\([^)]*\\)\\s*=>\\s*\\{)/,\n `$1\\n const apiKey = process.env.GATSBY_HUMANBEHAVIOR_API_KEY;\\n if (apiKey) {\\n HumanBehaviorTracker.init(apiKey);\\n }\\n`\n );\n\n return modified;\n }\n\n // No existing onClientEntry: create minimal file content or prepend to existing\n const block = `export const onClientEntry = () => {\\n const apiKey = process.env.GATSBY_HUMANBEHAVIOR_API_KEY;\\n if (apiKey) {\\n HumanBehaviorTracker.init(apiKey);\\n }\\n};`;\n\n const header = content.trim() ? `${importStatement}\\n` : `${importStatement}\\n`;\n return `${header}${block}${content.trim() ? `\\n\\n${content}` : ''}`;\n }\n\n\n\n /**\n * Helper method to find the best environment file for a framework\n */\n private findBestEnvFile(framework: FrameworkInfo): { filePath: string; envVarName: string } {\n const possibleEnvFiles = [\n '.env.local',\n '.env.development.local',\n '.env.development',\n '.env.local.development',\n '.env',\n '.env.production',\n '.env.staging'\n ];\n\n // Framework-specific environment variable names\n const getEnvVarName = (framework: FrameworkInfo) => {\n // Handle React+Vite specifically\n if (framework.type === 'react' && framework.bundler === 'vite') {\n return 'VITE_HUMANBEHAVIOR_API_KEY';\n }\n \n // Framework-specific mappings\n const envVarNames = {\n react: 'REACT_APP_HUMANBEHAVIOR_API_KEY',\n nextjs: 'NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY',\n vue: 'VITE_HUMANBEHAVIOR_API_KEY',\n svelte: 'PUBLIC_HUMANBEHAVIOR_API_KEY',\n angular: 'HUMANBEHAVIOR_API_KEY',\n nuxt: 'NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY',\n remix: 'HUMANBEHAVIOR_API_KEY',\n vanilla: 'HUMANBEHAVIOR_API_KEY',\n astro: 'PUBLIC_HUMANBEHAVIOR_API_KEY',\n gatsby: 'GATSBY_HUMANBEHAVIOR_API_KEY',\n node: 'HUMANBEHAVIOR_API_KEY',\n auto: 'HUMANBEHAVIOR_API_KEY'\n };\n \n return envVarNames[framework.type] || 'HUMANBEHAVIOR_API_KEY';\n };\n\n const envVarName = getEnvVarName(framework);\n\n // Check for existing files\n for (const envFile of possibleEnvFiles) {\n const fullPath = path.join(this.projectRoot, envFile);\n if (fs.existsSync(fullPath)) {\n return { filePath: fullPath, envVarName };\n }\n }\n\n // Framework-specific default file creation\n const defaultFiles = {\n react: '.env.local',\n nextjs: '.env.local',\n vue: '.env.local',\n svelte: '.env',\n angular: '.env',\n nuxt: '.env',\n remix: '.env.local',\n vanilla: '.env',\n astro: '.env',\n gatsby: '.env.development',\n node: '.env',\n auto: '.env'\n };\n\n const defaultFile = defaultFiles[framework.type] || '.env';\n return {\n filePath: path.join(this.projectRoot, defaultFile),\n envVarName\n };\n }\n\n /**\n * Helper method to create or append to environment files\n */\n private createEnvironmentModification(framework: FrameworkInfo): CodeModification {\n const { filePath, envVarName } = this.findBestEnvFile(framework);\n\n // Clean the API key to prevent formatting issues\n const cleanApiKey = this.apiKey.trim();\n\n if (fs.existsSync(filePath)) {\n // Check if the variable already exists\n const content = fs.readFileSync(filePath, 'utf8');\n if (content.includes(envVarName)) {\n // Variable exists, don't modify\n return {\n filePath,\n action: 'modify',\n content: content, // No change\n description: `API key already exists in ${path.basename(filePath)}`\n };\n } else {\n // Append to existing file\n return {\n filePath,\n action: 'append',\n content: `\\n${envVarName}=${cleanApiKey}`,\n description: `Added API key to existing ${path.basename(filePath)}`\n };\n }\n } else {\n // Create new file\n return {\n filePath,\n action: 'create',\n content: `${envVarName}=${cleanApiKey}`,\n description: `Created ${path.basename(filePath)} with API key`\n };\n }\n }\n}\n\n/**\n * Browser-based auto-installation wizard\n */\nexport class BrowserAutoInstallationWizard {\n private apiKey: string;\n\n constructor(apiKey: string) {\n this.apiKey = apiKey;\n }\n\n async install(): Promise<InstallationResult> {\n try {\n // Detect framework in browser\n const framework = this.detectFramework();\n \n // Generate installation instructions\n const modifications = this.generateBrowserModifications(framework);\n \n return {\n success: true,\n framework,\n modifications,\n errors: [],\n nextSteps: [\n '✅ Framework detected automatically',\n '📋 Copy the generated code to your project',\n '🚀 Your app will be ready to track user behavior'\n ]\n };\n } catch (error) {\n return {\n success: false,\n framework: { name: 'unknown', type: 'vanilla' },\n modifications: [],\n errors: [error instanceof Error ? error.message : 'Unknown error'],\n nextSteps: []\n };\n }\n }\n\n private detectFramework(): FrameworkInfo {\n if (typeof window !== 'undefined') {\n if ((window as any).React) {\n return { name: 'react', type: 'react' };\n }\n if ((window as any).Vue) {\n return { name: 'vue', type: 'vue' };\n }\n if ((window as any).angular) {\n return { name: 'angular', type: 'angular' };\n }\n }\n \n return { name: 'vanilla', type: 'vanilla' };\n }\n\n private generateBrowserModifications(framework: FrameworkInfo): CodeModification[] {\n // Return code snippets for browser environment\n const modifications: CodeModification[] = [];\n \n switch (framework.type) {\n case 'react':\n modifications.push({\n filePath: 'App.jsx',\n action: 'create',\n content: `import { HumanBehaviorProvider } from 'humanbehavior-js/react';\n\nfunction App() {\n return (\n <HumanBehaviorProvider apiKey=\"${this.apiKey}\">\n {/* Your app components */}\n </HumanBehaviorProvider>\n );\n}\n\nexport default App;`,\n description: 'React component with HumanBehaviorProvider'\n });\n break;\n \n case 'remix':\n modifications.push({\n filePath: 'app/root.tsx',\n action: 'create',\n content: `import {\n Links,\n Meta,\n Outlet,\n Scripts,\n ScrollRestoration,\n useLoaderData,\n} from \"@remix-run/react\";\nimport { HumanBehaviorProvider } from 'humanbehavior-js/react';\nimport type { LoaderFunctionArgs } from \"@remix-run/node\";\n\nexport async function loader({ request }: LoaderFunctionArgs) {\n return {\n ENV: {\n HUMANBEHAVIOR_API_KEY: process.env.HUMANBEHAVIOR_API_KEY,\n },\n };\n}\n\nexport function Layout({ children }: { children: React.ReactNode }) {\n return (\n <html lang=\"en\">\n <head>\n <meta charSet=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <Meta />\n <Links />\n </head>\n <body>\n {children}\n <ScrollRestoration />\n <Scripts />\n </body>\n </html>\n );\n}\n\nexport default function App() {\n const data = useLoaderData<typeof loader>();\n \n return (\n <HumanBehaviorProvider apiKey={data.ENV.HUMANBEHAVIOR_API_KEY}>\n <div className=\"min-h-screen bg-gray-50\">\n {/* Your app content */}\n <Outlet />\n </div>\n </HumanBehaviorProvider>\n );\n}`,\n description: 'Remix root component with HumanBehaviorProvider'\n });\n break;\n \n case 'vue':\n modifications.push({\n filePath: 'main.js',\n action: 'create',\n content: `import { createApp } from 'vue';\nimport { HumanBehaviorPlugin } from 'humanbehavior-js/vue';\nimport App from './App.vue';\n\nconst app = createApp(App);\napp.use(HumanBehaviorPlugin, {\n apiKey: '${this.apiKey}'\n});\napp.mount('#app');`,\n description: 'Vue app with HumanBehaviorPlugin'\n });\n break;\n \n default:\n modifications.push({\n filePath: 'humanbehavior-init.js',\n action: 'create',\n content: `import { HumanBehaviorTracker } from 'humanbehavior-js';\n\nconst tracker = HumanBehaviorTracker.init('${this.apiKey}');`,\n description: 'Vanilla JS initialization'\n });\n }\n \n return modifications;\n }\n} \n","/**\n * AI-Enhanced HumanBehavior SDK Auto-Installation Wizard\n * \n * This wizard uses AI to intelligently detect frameworks, analyze code patterns,\n * and generate optimal integration code that's both future-proof and backward-compatible.\n * \n * 🚀 KEY FEATURES:\n * - AI-powered framework detection beyond package.json\n * - Intelligent code pattern analysis\n * - Future-proof integration strategies\n * - Backward compatibility with legacy frameworks\n * - Adaptive code generation for new frameworks\n * - Smart conflict resolution\n * - Learning from user feedback\n * - Centralized AI service (no user API keys required)\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { AutoInstallationWizard, FrameworkInfo, CodeModification, InstallationResult } from '../core/install-wizard';\n\nexport interface AICodeAnalysis {\n framework: FrameworkInfo;\n confidence: number;\n patterns: string[];\n conflicts: string[];\n recommendations: string[];\n integrationStrategy: 'provider' | 'plugin' | 'module' | 'script' | 'standalone';\n compatibilityMode: 'modern' | 'legacy' | 'hybrid';\n}\n\nexport interface AIInstallationResult extends InstallationResult {\n aiAnalysis: AICodeAnalysis;\n learningData: {\n patterns: string[];\n framework: string;\n success: boolean;\n userFeedback?: string;\n };\n}\n\n/**\n * Centralized AI Service Interface\n * This runs on your backend infrastructure, not in the user's environment\n */\ninterface CentralizedAIService {\n analyzeCodePatterns(codeSamples: string[]): Promise<AICodeAnalysis>;\n resolveConflicts(conflicts: string[], framework: FrameworkInfo): Promise<string[]>;\n generateOptimizations(framework: FrameworkInfo, patterns: string[]): Promise<string[]>;\n}\n\n/**\n * Default AI Service Implementation\n * Uses heuristic analysis when centralized service is not available\n */\nclass DefaultAIService implements CentralizedAIService {\n async analyzeCodePatterns(codeSamples: string[]): Promise<AICodeAnalysis> {\n return this.analyzeWithHeuristics(codeSamples);\n }\n\n async resolveConflicts(conflicts: string[], framework: FrameworkInfo): Promise<string[]> {\n // Default conflict resolution strategies\n const resolutions: string[] = [];\n \n for (const conflict of conflicts) {\n switch (conflict) {\n case 'existing_humanbehavior_code':\n resolutions.push('update_existing_integration');\n break;\n case 'existing_provider':\n resolutions.push('merge_providers');\n break;\n case 'module_system_conflict':\n resolutions.push('hybrid_module_support');\n break;\n default:\n resolutions.push('skip_conflict');\n }\n }\n \n return resolutions;\n }\n\n async generateOptimizations(framework: FrameworkInfo, patterns: string[]): Promise<string[]> {\n const optimizations: string[] = [];\n \n // Framework-specific optimizations\n switch (framework.type) {\n case 'react':\n optimizations.push('Use React.memo for performance optimization');\n optimizations.push('Implement error boundaries for better error tracking');\n optimizations.push('Consider using React.lazy for code splitting');\n break;\n case 'vue':\n optimizations.push('Use Vue 3 Composition API for better performance');\n optimizations.push('Implement proper error handling in components');\n optimizations.push('Consider using Vue Router for navigation tracking');\n break;\n case 'angular':\n optimizations.push('Use Angular standalone components for better tree-shaking');\n optimizations.push('Implement proper error handling with ErrorHandler');\n optimizations.push('Consider using Angular signals for state management');\n break;\n default:\n optimizations.push('Enable performance tracking');\n optimizations.push('Implement error tracking');\n optimizations.push('Consider progressive enhancement');\n }\n \n return optimizations;\n }\n\n private analyzeWithHeuristics(codeSamples: string[]): AICodeAnalysis {\n const patterns = codeSamples.join(' ').toLowerCase();\n \n // Framework detection\n let framework: FrameworkInfo = { name: 'vanilla', type: 'vanilla' };\n let confidence = 0.5;\n \n if (patterns.includes('nuxt') || patterns.includes('nuxtjs') || patterns.includes('defineNuxtConfig') || patterns.includes('nuxt.config') || patterns.includes('@nuxt/') || patterns.includes('useNuxtApp') || patterns.includes('useRuntimeConfig') || patterns.includes('useSeoMeta') || patterns.includes('useHead') || patterns.includes('useLazyFetch') || patterns.includes('useFetch') || patterns.includes('useAsyncData') || patterns.includes('#app')) {\n framework = { name: 'nuxt', type: 'nuxt' };\n confidence = 0.95;\n } else if (patterns.includes('next') || patterns.includes('nextjs') || patterns.includes('next/link') || patterns.includes('next/image') || patterns.includes('next/navigation') || patterns.includes('next/router') || patterns.includes('getserverSideProps') || patterns.includes('getstaticProps') || patterns.includes('getstaticPaths') || patterns.includes('app/layout') || patterns.includes('app/page') || patterns.includes('pages/')) {\n framework = { name: 'nextjs', type: 'nextjs' };\n confidence = 0.95;\n } else if (patterns.includes('gatsby') || patterns.includes('gatsby-browser') || patterns.includes('gatsby-ssr') || patterns.includes('gatsby-node') || patterns.includes('gatsby-config') || patterns.includes('useStaticQuery') || patterns.includes('graphql')) {\n framework = { name: 'gatsby', type: 'gatsby' };\n confidence = 0.95;\n } else if (patterns.includes('react')) {\n framework = { name: 'react', type: 'react' };\n confidence = 0.9;\n } else if (patterns.includes('vue')) {\n framework = { name: 'vue', type: 'vue' };\n confidence = 0.9;\n } else if (patterns.includes('angular')) {\n framework = { name: 'angular', type: 'angular' };\n confidence = 0.9;\n } else if (patterns.includes('svelte')) {\n framework = { name: 'svelte', type: 'svelte' };\n confidence = 0.9;\n }\n \n // Integration strategy\n let integrationStrategy: 'provider' | 'plugin' | 'module' | 'script' | 'standalone' = 'script';\n if (framework.type === 'react' || framework.type === 'nextjs' || framework.type === 'gatsby') {\n integrationStrategy = 'provider';\n } else if (framework.type === 'vue') {\n integrationStrategy = 'plugin';\n } else if (framework.type === 'angular') {\n integrationStrategy = 'module';\n }\n \n // Compatibility mode\n let compatibilityMode: 'modern' | 'legacy' | 'hybrid' = 'modern';\n if (patterns.includes('require(') || patterns.includes('var ')) {\n compatibilityMode = 'legacy';\n }\n \n return {\n framework,\n confidence,\n patterns: codeSamples,\n conflicts: [],\n recommendations: [],\n integrationStrategy,\n compatibilityMode\n };\n }\n}\n\nexport class AIEnhancedInstallationWizard extends AutoInstallationWizard {\n private aiService: CentralizedAIService;\n private learningCache: Map<string, any> = new Map();\n private patternDatabase: Map<string, any[]> = new Map();\n\n constructor(apiKey: string, projectRoot: string = process.cwd(), aiService?: CentralizedAIService) {\n super(apiKey, projectRoot);\n this.aiService = aiService || new DefaultAIService();\n this.loadLearningData();\n }\n\n /**\n * AI-enhanced installation with intelligent analysis\n */\n async install(): Promise<AIInstallationResult> {\n try {\n // Step 1: AI-powered framework detection\n const aiAnalysis = await this.performAICodeAnalysis();\n \n // Step 2: Smart framework detection with AI validation\n this.framework = await this.detectFrameworkWithAI(aiAnalysis);\n \n // Step 3: Generate AI-optimized modifications\n const modifications = await this.generateAIOptimizedModifications(aiAnalysis);\n \n // Step 4: Apply modifications with conflict resolution\n await this.applyModificationsWithAI(modifications, aiAnalysis);\n \n // Step 5: Generate intelligent next steps\n const nextSteps = this.generateAINextSteps(aiAnalysis);\n \n // Step 6: Learn from this installation\n await this.learnFromInstallation(aiAnalysis, modifications);\n \n return {\n success: true,\n framework: this.framework,\n modifications,\n errors: [],\n nextSteps,\n aiAnalysis,\n learningData: {\n patterns: aiAnalysis.patterns,\n framework: this.framework.name,\n success: true\n }\n };\n } catch (error) {\n return {\n success: false,\n framework: this.framework || { name: 'unknown', type: 'vanilla' },\n modifications: [],\n errors: [error instanceof Error ? error.message : 'Unknown error'],\n nextSteps: [],\n aiAnalysis: {\n framework: { name: 'unknown', type: 'vanilla' },\n confidence: 0,\n patterns: [],\n conflicts: [],\n recommendations: [],\n integrationStrategy: 'script',\n compatibilityMode: 'legacy'\n },\n learningData: {\n patterns: [],\n framework: 'unknown',\n success: false\n }\n };\n }\n }\n\n /**\n * AI-powered code analysis using centralized service\n */\n public async performAICodeAnalysis(): Promise<AICodeAnalysis> {\n const projectFiles = await this.scanProjectFiles();\n const codeSamples = await this.extractCodeSamples(projectFiles);\n \n // Use centralized AI service (no user API key required)\n return await this.aiService.analyzeCodePatterns(codeSamples);\n }\n\n /**\n * Scan project files for analysis\n */\n private async scanProjectFiles(): Promise<string[]> {\n const files: string[] = [];\n const scanDir = (dir: string, depth: number = 0) => {\n if (depth > 3) return; // Limit depth\n \n try {\n const items = fs.readdirSync(dir);\n for (const item of items) {\n const fullPath = path.join(dir, item);\n const stat = fs.statSync(fullPath);\n \n if (stat.isDirectory() && !item.startsWith('.') && item !== 'node_modules') {\n scanDir(fullPath, depth + 1);\n } else if (stat.isFile() && this.isRelevantFile(item)) {\n files.push(fullPath);\n }\n }\n } catch (error) {\n // Skip inaccessible directories\n }\n };\n \n scanDir(this.projectRoot);\n return files;\n }\n\n /**\n * Check if file is relevant for analysis\n */\n private isRelevantFile(filename: string): boolean {\n const relevantExtensions = [\n '.js', '.jsx', '.ts', '.tsx', '.vue', '.svelte', '.html',\n '.json', '.config.js', '.config.ts', '.babelrc', '.eslintrc'\n ];\n \n const relevantNames = [\n 'package.json', 'tsconfig.json', 'vite.config', 'webpack.config',\n 'next.config', 'nuxt.config', 'angular.json', 'svelte.config',\n 'app/layout', 'app/page', 'pages/index', 'pages/_app', 'pages/_document'\n ];\n \n return relevantExtensions.some(ext => filename.endsWith(ext)) ||\n relevantNames.some(name => filename.includes(name));\n }\n\n /**\n * Extract code samples for AI analysis\n */\n private async extractCodeSamples(files: string[]): Promise<string[]> {\n const samples: string[] = [];\n \n for (const file of files.slice(0, 20)) { // Limit to 20 files\n try {\n const content = fs.readFileSync(file, 'utf8');\n const relativePath = path.relative(this.projectRoot, file);\n \n // Extract relevant code patterns\n const patterns = this.extractCodePatterns(content);\n if (patterns.length > 0) {\n samples.push(`File: ${relativePath}\\n${patterns.join('\\n')}`);\n }\n } catch (error) {\n // Skip unreadable files\n }\n }\n \n return samples;\n }\n\n /**\n * Extract relevant code patterns\n */\n private extractCodePatterns(content: string): string[] {\n const patterns: string[] = [];\n \n // Framework-specific patterns\n const frameworkPatterns = {\n react: [\n /import\\s+React\\s+from\\s+['\"]react['\"]/gi,\n /from\\s+['\"]react['\"]/gi,\n /function\\s+\\w+\\s*\\(\\s*\\)\\s*{/gi,\n /const\\s+\\w+\\s*=\\s*\\(\\s*\\)\\s*=>\\s*{/gi\n ],\n vue: [\n /import\\s+{\\s*createApp\\s*}\\s+from\\s+['\"]vue['\"]/gi,\n /from\\s+['\"]vue['\"]/gi,\n /<template>/gi,\n /<script\\s+setup>/gi\n ],\n angular: [\n /import\\s+{\\s*Component\\s*}\\s+from\\s+['\"]@angular\\/core['\"]/gi,\n /@Component\\s*\\(\\s*{/gi,\n /from\\s+['\"]@angular/gi\n ],\n svelte: [\n /<script>/gi,\n /import\\s+.*\\s+from\\s+['\"]svelte/gi,\n /from\\s+['\"]svelte/gi\n ],\n nextjs: [\n /import\\s+.*\\s+from\\s+['\"]next/gi,\n /from\\s+['\"]next/gi,\n /export\\s+default\\s+function\\s+Page/gi,\n /export\\s+default\\s+function\\s+Layout/gi,\n /export\\s+default\\s+function\\s+Loading/gi,\n /export\\s+default\\s+function\\s+Error/gi,\n /export\\s+default\\s+function\\s+Not-found/gi,\n /useRouter\\s+from\\s+['\"]next\\/navigation['\"]/gi,\n /useRouter\\s+from\\s+['\"]next\\/router['\"]/gi,\n /Link\\s+from\\s+['\"]next\\/link['\"]/gi,\n /Image\\s+from\\s+['\"]next\\/image['\"]/gi,\n /getServerSideProps/gi,\n /getStaticProps/gi,\n /getStaticPaths/gi,\n /next\\.config/gi,\n /app\\/layout\\.tsx/gi,\n /app\\/page\\.tsx/gi,\n /pages\\/.*\\.tsx/gi,\n /pages\\/.*\\.jsx/gi,\n /pages\\/.*\\.ts/gi,\n /pages\\/.*\\.js/gi\n ],\n nuxt: [\n /import\\s+.*\\s+from\\s+['\"]nuxt/gi,\n /from\\s+['\"]nuxt/gi,\n /export\\s+default\\s+defineNuxtConfig/gi,\n /defineNuxtConfig/gi,\n /nuxt\\.config\\.ts/gi,\n /nuxt\\.config\\.js/gi,\n /@nuxt\\//gi,\n /#app/gi,\n /useNuxtApp/gi,\n /useRuntimeConfig/gi,\n /useSeoMeta/gi,\n /useHead/gi,\n /useLazyFetch/gi,\n /useFetch/gi,\n /useAsyncData/gi,\n /<NuxtLayout/gi,\n /<NuxtPage/gi,\n /NuxtLayout/gi,\n /NuxtPage/gi,\n /pages\\/.*\\.vue/gi,\n /layouts\\/.*\\.vue/gi,\n /components\\/.*\\.vue/gi,\n /composables\\/.*\\.ts/gi,\n /middleware\\/.*\\.ts/gi,\n /server\\/.*\\.ts/gi,\n /plugins\\/.*\\.ts/gi,\n /public\\//gi,\n /assets\\//gi,\n /content\\//gi\n ]\n };\n \n // Extract patterns for each framework\n for (const [framework, regexes] of Object.entries(frameworkPatterns)) {\n for (const regex of regexes) {\n const matches = content.match(regex);\n if (matches) {\n // Add raw patterns for heuristic analysis\n patterns.push(...matches.slice(0, 3));\n // Also add formatted patterns for debugging\n patterns.push(`${framework.toUpperCase()}: ${matches.slice(0, 3).join(', ')}`);\n }\n }\n }\n \n // Extract import patterns\n const importMatches = content.match(/import\\s+.*\\s+from\\s+['\"][^'\"]+['\"]/gi);\n if (importMatches) {\n patterns.push(`IMPORTS: ${importMatches.slice(0, 5).join(', ')}`);\n }\n \n // Extract export patterns\n const exportMatches = content.match(/export\\s+.*/gi);\n if (exportMatches) {\n patterns.push(`EXPORTS: ${exportMatches.slice(0, 3).join(', ')}`);\n }\n \n return patterns;\n }\n\n /**\n * AI-enhanced framework detection\n */\n private async detectFrameworkWithAI(aiAnalysis: AICodeAnalysis): Promise<FrameworkInfo> {\n // Combine AI analysis with traditional detection\n const traditionalFramework = await super.detectFramework();\n \n // Use AI analysis if confidence is high, but preserve bundler info\n if (aiAnalysis.confidence > 0.8) {\n return {\n ...aiAnalysis.framework,\n bundler: traditionalFramework.bundler, // Preserve bundler detection\n packageManager: traditionalFramework.packageManager, // Preserve package manager\n hasTypeScript: traditionalFramework.hasTypeScript, // Preserve TypeScript detection\n hasRouter: traditionalFramework.hasRouter, // Preserve router detection\n projectRoot: this.projectRoot\n };\n }\n \n // Merge AI insights with traditional detection\n return {\n ...traditionalFramework,\n // Override with AI insights if available\n ...(aiAnalysis.framework.type !== 'vanilla' && {\n type: aiAnalysis.framework.type,\n name: aiAnalysis.framework.name\n })\n };\n }\n\n /**\n * Generate AI-optimized modifications\n */\n private async generateAIOptimizedModifications(aiAnalysis: AICodeAnalysis): Promise<CodeModification[]> {\n const baseModifications = await super.generateModifications();\n \n // Enhance with AI recommendations\n const enhancedModifications = baseModifications.map(mod => {\n return this.enhanceModificationWithAI(mod, aiAnalysis);\n });\n \n // Add AI-specific optimizations\n const aiOptimizations = this.generateAIOptimizations(aiAnalysis);\n enhancedModifications.push(...aiOptimizations);\n \n return enhancedModifications;\n }\n\n /**\n * Enhance modification with AI insights\n */\n private enhanceModificationWithAI(mod: CodeModification, aiAnalysis: AICodeAnalysis): CodeModification {\n let enhancedContent = mod.content;\n \n // Add compatibility comments\n if (aiAnalysis.compatibilityMode === 'legacy') {\n enhancedContent = `// HumanBehavior SDK - Legacy Compatibility Mode\\n${enhancedContent}`;\n }\n \n // Add future-proofing comments\n if (aiAnalysis.integrationStrategy === 'provider') {\n enhancedContent = `// HumanBehavior SDK - Provider Pattern (Future-proof)\\n${enhancedContent}`;\n }\n \n // Add conflict resolution\n if (aiAnalysis.conflicts.length > 0) {\n enhancedContent = `// Conflict Resolution: ${aiAnalysis.conflicts.join(', ')}\\n${enhancedContent}`;\n }\n \n return {\n ...mod,\n content: enhancedContent,\n description: `${mod.description} (AI-optimized)`\n };\n }\n\n /**\n * Generate AI-specific optimizations\n */\n private generateAIOptimizations(aiAnalysis: AICodeAnalysis): CodeModification[] {\n const optimizations: CodeModification[] = [];\n \n // AI optimizations are now handled through environment variables and code injection\n // No separate config file needed - everything is integrated into the existing codebase\n \n return optimizations;\n }\n\n /**\n * Apply modifications with AI conflict resolution\n */\n private async applyModificationsWithAI(modifications: CodeModification[], aiAnalysis: AICodeAnalysis): Promise<void> {\n for (const modification of modifications) {\n try {\n // Check for conflicts\n const conflicts = await this.detectConflicts(modification);\n \n if (conflicts.length > 0) {\n // Resolve conflicts using centralized AI service\n const resolutions = await this.aiService.resolveConflicts(conflicts, aiAnalysis.framework);\n const resolvedModification = await this.resolveConflicts(modification, conflicts, resolutions, aiAnalysis);\n await this.applyModification(resolvedModification);\n } else {\n await this.applyModification(modification);\n }\n } catch (error) {\n throw new Error(`Failed to apply AI-optimized modification to ${modification.filePath}: ${error}`);\n }\n }\n }\n\n /**\n * Detect potential conflicts\n */\n private async detectConflicts(modification: CodeModification): Promise<string[]> {\n const conflicts: string[] = [];\n \n if (fs.existsSync(modification.filePath)) {\n const existingContent = fs.readFileSync(modification.filePath, 'utf8');\n \n // Check for existing HumanBehavior code\n if (existingContent.includes('HumanBehavior') || existingContent.includes('humanbehavior')) {\n conflicts.push('existing_humanbehavior_code');\n }\n \n // Check for conflicting providers/plugins\n if (modification.content.includes('Provider') && existingContent.includes('Provider')) {\n conflicts.push('existing_provider');\n }\n \n // Check for TypeScript conflicts\n if (modification.content.includes('import') && existingContent.includes('require(')) {\n conflicts.push('module_system_conflict');\n }\n }\n \n return conflicts;\n }\n\n /**\n * Resolve conflicts with AI\n */\n private async resolveConflicts(modification: CodeModification, conflicts: string[], resolutions: string[], aiAnalysis: AICodeAnalysis): Promise<CodeModification> {\n let resolvedContent = modification.content;\n \n for (let i = 0; i < conflicts.length; i++) {\n const conflict = conflicts[i];\n const resolution = resolutions[i];\n \n switch (resolution) {\n case 'update_existing_integration':\n resolvedContent = `// Updated HumanBehavior Integration\\n${resolvedContent}`;\n break;\n case 'merge_providers':\n resolvedContent = resolvedContent.replace(/<HumanBehaviorProvider/g, '<HumanBehaviorProvider key=\"updated\"');\n break;\n case 'hybrid_module_support':\n resolvedContent = `// Hybrid module system support\\n${resolvedContent}`;\n break;\n case 'skip_conflict':\n // Skip this modification\n return { ...modification, content: '', description: `${modification.description} (skipped due to conflict)` };\n default:\n // Default resolution\n resolvedContent = `// Conflict resolved: ${conflict}\\n${resolvedContent}`;\n }\n }\n \n return {\n ...modification,\n content: resolvedContent,\n description: `${modification.description} (conflict-resolved)`\n };\n }\n\n /**\n * Apply single modification\n */\n private async applyModification(modification: CodeModification): Promise<void> {\n if (!modification.content) return; // Skip empty modifications\n \n const dir = path.dirname(modification.filePath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n\n switch (modification.action) {\n case 'create':\n fs.writeFileSync(modification.filePath, modification.content);\n break;\n case 'modify':\n fs.writeFileSync(modification.filePath, modification.content);\n break;\n case 'append':\n fs.appendFileSync(modification.filePath, '\\n' + modification.content);\n break;\n }\n }\n\n /**\n * Generate AI-enhanced next steps\n */\n private generateAINextSteps(aiAnalysis: AICodeAnalysis): string[] {\n const steps = [\n '✅ AI-optimized SDK installation completed!',\n `🎯 Framework detected: ${aiAnalysis.framework.name} (confidence: ${Math.round(aiAnalysis.confidence * 100)}%)`,\n `🔧 Integration strategy: ${aiAnalysis.integrationStrategy}`,\n `🔄 Compatibility mode: ${aiAnalysis.compatibilityMode}`,\n '🚀 Your app is now tracking user behavior with AI-optimized configuration'\n ];\n \n if (aiAnalysis.recommendations.length > 0) {\n steps.push('💡 AI Recommendations:');\n aiAnalysis.recommendations.forEach(rec => steps.push(` • ${rec}`));\n }\n \n return steps;\n }\n\n /**\n * Learn from installation for future improvements\n */\n private async learnFromInstallation(aiAnalysis: AICodeAnalysis, modifications: CodeModification[]): Promise<void> {\n const learningData = {\n timestamp: new Date().toISOString(),\n framework: aiAnalysis.framework.name,\n patterns: aiAnalysis.patterns,\n integrationStrategy: aiAnalysis.integrationStrategy,\n compatibilityMode: aiAnalysis.compatibilityMode,\n modifications: modifications.length,\n success: true\n };\n \n // Store learning data\n this.learningCache.set(`${aiAnalysis.framework.name}_${Date.now()}`, learningData);\n \n // Update pattern database\n if (!this.patternDatabase.has(aiAnalysis.framework.name)) {\n this.patternDatabase.set(aiAnalysis.framework.name, []);\n }\n this.patternDatabase.get(aiAnalysis.framework.name)!.push(learningData);\n \n // Save to disk\n await this.saveLearningData();\n }\n\n /**\n * Load learning data from disk\n */\n private loadLearningData(): void {\n // Don't load learning data from user's project - keep it in memory only\n // This prevents cluttering the user's project with internal files\n }\n\n /**\n * Save learning data to disk\n */\n private async saveLearningData(): Promise<void> {\n // Don't save learning data to user's project - keep it in memory only\n // This prevents cluttering the user's project with internal files\n }\n\n /**\n * Get AI insights for a specific framework\n */\n public getAIInsights(frameworkName: string): any[] {\n return this.patternDatabase.get(frameworkName) || [];\n }\n\n /**\n * Get learning statistics\n */\n public getLearningStats(): any {\n const stats = {\n totalInstallations: this.learningCache.size,\n frameworks: {} as any,\n patterns: {} as any\n };\n \n for (const [framework, data] of this.patternDatabase.entries()) {\n stats.frameworks[framework] = data.length;\n }\n \n return stats;\n }\n}\n\n/**\n * Browser-based AI installation wizard\n */\nexport class AIBrowserInstallationWizard {\n private apiKey: string;\n private aiService: CentralizedAIService;\n\n constructor(apiKey: string, aiService?: CentralizedAIService) {\n this.apiKey = apiKey;\n this.aiService = aiService || new DefaultAIService();\n }\n\n async install(): Promise<AIInstallationResult> {\n try {\n // AI-powered browser detection\n const aiAnalysis = await this.performBrowserAIAnalysis();\n \n // Generate AI-optimized browser modifications\n const modifications = this.generateAIBrowserModifications(aiAnalysis);\n \n return {\n success: true,\n framework: aiAnalysis.framework,\n modifications,\n errors: [],\n nextSteps: [\n '✅ AI-optimized browser integration ready!',\n `🎯 Framework detected: ${aiAnalysis.framework.name}`,\n `🔧 Integration strategy: ${aiAnalysis.integrationStrategy}`,\n '📋 Copy the generated code to your project',\n '🚀 Your app will be ready to track user behavior'\n ],\n aiAnalysis,\n learningData: {\n patterns: aiAnalysis.patterns,\n framework: aiAnalysis.framework.name,\n success: true\n }\n };\n } catch (error) {\n return {\n success: false,\n framework: { name: 'unknown', type: 'vanilla' },\n modifications: [],\n errors: [error instanceof Error ? error.message : 'Unknown error'],\n nextSteps: [],\n aiAnalysis: {\n framework: { name: 'unknown', type: 'vanilla' },\n confidence: 0,\n patterns: [],\n conflicts: [],\n recommendations: [],\n integrationStrategy: 'script',\n compatibilityMode: 'legacy'\n },\n learningData: {\n patterns: [],\n framework: 'unknown',\n success: false\n }\n };\n }\n }\n\n private async performBrowserAIAnalysis(): Promise<AICodeAnalysis> {\n // Browser-based framework detection\n const framework = this.detectBrowserFramework();\n \n // Analyze browser environment\n const patterns = this.analyzeBrowserPatterns();\n \n // Use centralized AI service for analysis\n const codeSamples = [`Browser Environment: ${patterns.join(', ')}`];\n return await this.aiService.analyzeCodePatterns(codeSamples);\n }\n\n private detectBrowserFramework(): FrameworkInfo {\n if (typeof window !== 'undefined') {\n if ((window as any).React) {\n return { name: 'react', type: 'react' };\n }\n if ((window as any).Vue) {\n return { name: 'vue', type: 'vue' };\n }\n if ((window as any).angular) {\n return { name: 'angular', type: 'angular' };\n }\n }\n \n return { name: 'vanilla', type: 'vanilla' };\n }\n\n private analyzeBrowserPatterns(): string[] {\n const patterns: string[] = [];\n \n if (typeof window !== 'undefined') {\n // Analyze global objects\n if ((window as any).React) patterns.push('React global detected');\n if ((window as any).Vue) patterns.push('Vue global detected');\n if ((window as any).angular) patterns.push('Angular global detected');\n \n // Analyze DOM patterns\n if (document.querySelector('[data-reactroot]')) patterns.push('React DOM detected');\n if (document.querySelector('[data-vue]')) patterns.push('Vue DOM detected');\n \n // Analyze script patterns\n const scripts = document.querySelectorAll('script');\n scripts.forEach(script => {\n if (script.src.includes('react')) patterns.push('React script detected');\n if (script.src.includes('vue')) patterns.push('Vue script detected');\n });\n }\n \n return patterns;\n }\n\n private generateAIBrowserModifications(aiAnalysis: AICodeAnalysis): CodeModification[] {\n const modifications: CodeModification[] = [];\n \n switch (aiAnalysis.framework.type) {\n case 'react':\n modifications.push({\n filePath: 'App.jsx',\n action: 'create',\n content: `// AI-Optimized React Integration\nimport { HumanBehaviorProvider } from 'humanbehavior-js/react';\n\nfunction App() {\n return (\n <HumanBehaviorProvider \n apiKey=\"${this.apiKey}\"\n config={{\n // AI-generated optimizations\n enablePerformanceTracking: true,\n enableErrorTracking: true,\n framework: '${aiAnalysis.framework.name}',\n integrationStrategy: '${aiAnalysis.integrationStrategy}'\n }}\n >\n {/* Your app components */}\n </HumanBehaviorProvider>\n );\n}\n\nexport default App;`,\n description: 'AI-optimized React component with HumanBehaviorProvider'\n });\n break;\n \n default:\n modifications.push({\n filePath: 'humanbehavior-init.js',\n action: 'create',\n content: `// AI-Optimized Vanilla JS Integration\nimport { HumanBehaviorTracker } from 'humanbehavior-js';\n\nconst tracker = HumanBehaviorTracker.init('${this.apiKey}', {\n // AI-generated configuration\n framework: '${aiAnalysis.framework.name}',\n integrationStrategy: '${aiAnalysis.integrationStrategy}',\n compatibilityMode: '${aiAnalysis.compatibilityMode}',\n enablePerformanceTracking: true,\n enableErrorTracking: true\n});`,\n description: 'AI-optimized vanilla JS initialization'\n });\n }\n \n return modifications;\n }\n} ","/**\n * Remote AI Service Implementation\n * \n * This connects to your deployed Lambda function via API Gateway\n */\n\nimport { AICodeAnalysis } from '../ai/ai-install-wizard';\n\nexport interface FrameworkInfo {\n name: string;\n type: 'react' | 'vue' | 'angular' | 'svelte' | 'nextjs' | 'nuxt' | 'remix' | 'vanilla' | 'astro' | 'gatsby' | 'node';\n bundler?: 'vite' | 'webpack' | 'esbuild' | 'rollup';\n packageManager?: 'npm' | 'yarn' | 'pnpm';\n hasTypeScript?: boolean;\n hasRouter?: boolean;\n projectRoot?: string;\n version?: string;\n majorVersion?: number;\n features?: {\n hasReact18?: boolean;\n hasVue3?: boolean;\n hasNuxt3?: boolean;\n hasAngularStandalone?: boolean;\n hasNextAppRouter?: boolean;\n hasSvelteKit?: boolean;\n };\n}\n\nexport interface RemoteAIServiceConfig {\n apiEndpoint: string;\n timeout?: number;\n}\n\nexport class RemoteAIService {\n private config: RemoteAIServiceConfig;\n\n constructor(config: RemoteAIServiceConfig) {\n this.config = {\n timeout: 10000, // 10 seconds\n ...config\n };\n }\n\n /**\n * Analyze code patterns using your deployed AI service\n */\n async analyzeCodePatterns(codeSamples: string[]): Promise<AICodeAnalysis> {\n try {\n const response = await fetch(`${this.config.apiEndpoint}/analyze`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ codeSamples }),\n signal: AbortSignal.timeout(this.config.timeout || 10000)\n });\n\n if (!response.ok) {\n throw new Error(`AI service returned ${response.status}: ${response.statusText}`);\n }\n\n const result = await response.json();\n return result.analysis;\n } catch (error) {\n console.warn('Remote AI service failed, falling back to heuristic analysis:', error);\n return this.performHeuristicAnalysis(codeSamples);\n }\n }\n\n /**\n * Resolve conflicts using your deployed AI service\n */\n async resolveConflicts(conflicts: string[], framework: FrameworkInfo): Promise<string[]> {\n try {\n const response = await fetch(`${this.config.apiEndpoint}/resolve-conflicts`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ conflicts, framework }),\n signal: AbortSignal.timeout(this.config.timeout || 10000)\n });\n\n if (!response.ok) {\n throw new Error(`AI service returned ${response.status}: ${response.statusText}`);\n }\n\n const result = await response.json();\n return result.resolutions || [];\n } catch (error) {\n console.warn('Remote AI conflict resolution failed, using heuristic approach:', error);\n return this.resolveConflictsHeuristic(conflicts, framework);\n }\n }\n\n /**\n * Generate optimizations using your deployed AI service\n */\n async generateOptimizations(framework: FrameworkInfo, patterns: string[]): Promise<string[]> {\n try {\n const response = await fetch(`${this.config.apiEndpoint}/optimize`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ framework, patterns }),\n signal: AbortSignal.timeout(this.config.timeout || 10000)\n });\n\n if (!response.ok) {\n throw new Error(`AI service returned ${response.status}: ${response.statusText}`);\n }\n\n const result = await response.json();\n return result.optimizations || [];\n } catch (error) {\n console.warn('Remote AI optimization generation failed, using heuristic approach:', error);\n return this.generateOptimizationsHeuristic(framework, patterns);\n }\n }\n\n /**\n * Heuristic analysis fallback\n */\n private performHeuristicAnalysis(codeSamples: string[]): AICodeAnalysis {\n const patterns = codeSamples.join(' ').toLowerCase();\n \n // Framework detection\n let framework: FrameworkInfo = { name: 'vanilla', type: 'vanilla' };\n let confidence = 0.5;\n \n if (patterns.includes('nuxt') || patterns.includes('nuxtjs') || patterns.includes('defineNuxtConfig') || patterns.includes('nuxt.config') || patterns.includes('@nuxt/') || patterns.includes('useNuxtApp') || patterns.includes('useRuntimeConfig') || patterns.includes('useSeoMeta') || patterns.includes('useHead') || patterns.includes('useLazyFetch') || patterns.includes('useFetch') || patterns.includes('useAsyncData') || patterns.includes('#app')) {\n framework = { name: 'nuxt', type: 'nuxt' };\n confidence = 0.95;\n } else if (patterns.includes('next') || patterns.includes('nextjs') || patterns.includes('next/link') || patterns.includes('next/image') || patterns.includes('next/navigation') || patterns.includes('next/router') || patterns.includes('getserverSideProps') || patterns.includes('getstaticProps') || patterns.includes('getstaticPaths') || patterns.includes('app/layout') || patterns.includes('app/page') || patterns.includes('pages/')) {\n framework = { name: 'nextjs', type: 'nextjs' };\n confidence = 0.95;\n } else if (patterns.includes('gatsby') || patterns.includes('gatsby-browser') || patterns.includes('gatsby-ssr') || patterns.includes('gatsby-node') || patterns.includes('gatsby-config') || patterns.includes('useStaticQuery') || patterns.includes('graphql')) {\n framework = { name: 'gatsby', type: 'gatsby' };\n confidence = 0.95;\n } else if (patterns.includes('react')) {\n framework = { name: 'react', type: 'react' };\n confidence = 0.9;\n } else if (patterns.includes('vue')) {\n framework = { name: 'vue', type: 'vue' };\n confidence = 0.9;\n } else if (patterns.includes('angular')) {\n framework = { name: 'angular', type: 'angular' };\n confidence = 0.9;\n } else if (patterns.includes('svelte')) {\n framework = { name: 'svelte', type: 'svelte' };\n confidence = 0.9;\n } else if (patterns.includes('astro')) {\n framework = { name: 'astro', type: 'astro' };\n confidence = 0.9;\n }\n \n // Integration strategy\n let integrationStrategy: 'provider' | 'plugin' | 'module' | 'script' | 'standalone' = 'script';\n if (framework.type === 'react' || framework.type === 'nextjs' || framework.type === 'gatsby') {\n integrationStrategy = 'provider';\n } else if (framework.type === 'vue') {\n integrationStrategy = 'plugin';\n } else if (framework.type === 'angular') {\n integrationStrategy = 'module';\n }\n \n // Compatibility mode\n let compatibilityMode: 'modern' | 'legacy' | 'hybrid' = 'modern';\n if (patterns.includes('require(') || patterns.includes('var ')) {\n compatibilityMode = 'legacy';\n }\n \n return {\n framework,\n confidence,\n patterns: codeSamples,\n conflicts: [],\n recommendations: [],\n integrationStrategy,\n compatibilityMode\n };\n }\n\n /**\n * Heuristic conflict resolution\n */\n private resolveConflictsHeuristic(conflicts: string[], framework: FrameworkInfo): string[] {\n const resolutions: string[] = [];\n \n for (const conflict of conflicts) {\n switch (conflict) {\n case 'existing_humanbehavior_code':\n resolutions.push('update_existing_integration');\n break;\n case 'existing_provider':\n resolutions.push('merge_providers');\n break;\n case 'module_system_conflict':\n resolutions.push('hybrid_module_support');\n break;\n default:\n resolutions.push('skip_conflict');\n }\n }\n \n return resolutions;\n }\n\n /**\n * Heuristic optimization generation\n */\n private generateOptimizationsHeuristic(framework: FrameworkInfo, patterns: string[]): string[] {\n const optimizations: string[] = [];\n \n switch (framework.type) {\n case 'react':\n optimizations.push('Use React.memo for performance optimization');\n optimizations.push('Implement error boundaries for better error tracking');\n optimizations.push('Consider using React.lazy for code splitting');\n break;\n case 'vue':\n optimizations.push('Use Vue 3 Composition API for better performance');\n optimizations.push('Implement proper error handling in components');\n optimizations.push('Consider using Vue Router for navigation tracking');\n break;\n case 'angular':\n optimizations.push('Use Angular standalone components for better tree-shaking');\n optimizations.push('Implement proper error handling with ErrorHandler');\n optimizations.push('Consider using Angular signals for state management');\n break;\n default:\n optimizations.push('Enable performance tracking');\n optimizations.push('Implement error tracking');\n optimizations.push('Consider progressive enhancement');\n }\n \n return optimizations;\n }\n} ","/**\n * Manual Framework Installation Wizard\n * \n * This wizard allows users to manually specify their framework instead of auto-detection.\n * Useful when auto-detection fails or users want more control.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { AutoInstallationWizard, FrameworkInfo, CodeModification, InstallationResult } from '../core/install-wizard';\nimport { RemoteAIService } from '../services/remote-ai-service';\n\nexport interface ManualInstallationResult extends InstallationResult {\n selectedFramework: string;\n manualMode: boolean;\n}\n\nexport class ManualFrameworkInstallationWizard extends AutoInstallationWizard {\n private selectedFramework: string;\n\n constructor(apiKey: string, projectRoot: string = process.cwd(), framework: string) {\n super(apiKey, projectRoot);\n this.selectedFramework = framework.toLowerCase();\n this.framework = this.createFrameworkInfo(this.selectedFramework);\n }\n\n /**\n * Manual installation with user-specified framework\n */\n async install(): Promise<ManualInstallationResult> {\n try {\n // Step 1: Handle framework selection\n if (this.selectedFramework === 'auto') {\n // Use full AI detection for \"Other\" option\n this.framework = await this.runFullDetection();\n } else {\n // Set framework based on user selection\n this.framework = this.createFrameworkInfo(this.selectedFramework);\n if (!this.framework) {\n this.framework = { name: 'unknown', type: 'vanilla' };\n }\n \n // Step 2: Run full detection logic to find entry points, file names, etc.\n const detectedFramework = await this.runFullDetection();\n \n // Step 3: Merge manual framework with detected details\n this.framework = {\n ...detectedFramework,\n name: this.framework.name,\n type: this.framework.type\n };\n }\n \n // Step 4: Install package\n await this.installPackage();\n \n // Step 5: Generate and apply code modifications\n const modifications = await this.generateModifications();\n await this.applyModifications(modifications);\n \n // Step 6: Generate next steps\n const nextSteps = this.generateManualNextSteps();\n \n return {\n success: true,\n framework: this.framework,\n modifications,\n errors: [],\n nextSteps,\n selectedFramework: this.selectedFramework,\n manualMode: true\n };\n } catch (error) {\n return {\n success: false,\n framework: this.framework || { name: 'unknown', type: 'vanilla' },\n modifications: [],\n errors: [error instanceof Error ? error.message : 'Unknown error'],\n nextSteps: [],\n selectedFramework: this.selectedFramework,\n manualMode: true\n };\n }\n }\n\n /**\n * Run full detection logic to find entry points, file names, bundler, etc.\n */\n private async runFullDetection(): Promise<FrameworkInfo> {\n if (this.selectedFramework === 'auto') {\n // Use AI service for auto-detection\n const aiService = new RemoteAIService({\n apiEndpoint: 'https://ik3zxh4790.execute-api.us-east-1.amazonaws.com/prod'\n });\n \n // Use AI service directly for detection\n const projectFiles = await this.scanProjectFiles();\n const codeSamples = await this.extractCodeSamples(projectFiles);\n const aiAnalysis = await aiService.analyzeCodePatterns(codeSamples);\n return aiAnalysis.framework;\n } else {\n // Use traditional detection for manual frameworks\n const tempWizard = new AutoInstallationWizard(this.apiKey, this.projectRoot);\n const detected = await tempWizard.detectFramework();\n return detected;\n }\n }\n\n /**\n * Scan project files for analysis\n */\n private async scanProjectFiles(): Promise<string[]> {\n const files: string[] = [];\n const scanDir = (dir: string, depth: number = 0) => {\n if (depth > 3) return; // Limit depth\n \n try {\n const items = fs.readdirSync(dir);\n for (const item of items) {\n const fullPath = path.join(dir, item);\n const stat = fs.statSync(fullPath);\n \n if (stat.isDirectory() && !item.startsWith('.') && item !== 'node_modules') {\n scanDir(fullPath, depth + 1);\n } else if (stat.isFile() && this.isRelevantFile(item)) {\n files.push(fullPath);\n }\n }\n } catch (error) {\n // Skip inaccessible directories\n }\n };\n \n scanDir(this.projectRoot);\n return files;\n }\n\n /**\n * Check if file is relevant for analysis\n */\n private isRelevantFile(filename: string): boolean {\n const relevantExtensions = [\n '.js', '.jsx', '.ts', '.tsx', '.vue', '.svelte', '.html',\n '.json', '.config.js', '.config.ts', '.babelrc', '.eslintrc'\n ];\n \n const relevantNames = [\n 'package.json', 'tsconfig.json', 'vite.config', 'webpack.config',\n 'next.config', 'nuxt.config', 'angular.json', 'svelte.config'\n ];\n \n return relevantExtensions.some(ext => filename.endsWith(ext)) ||\n relevantNames.some(name => filename.includes(name));\n }\n\n /**\n * Extract code samples for AI analysis\n */\n private async extractCodeSamples(files: string[]): Promise<string[]> {\n const samples: string[] = [];\n \n for (const file of files.slice(0, 20)) { // Limit to 20 files\n try {\n const content = fs.readFileSync(file, 'utf8');\n const relativePath = path.relative(this.projectRoot, file);\n samples.push(`File: ${relativePath}\\n${content.substring(0, 1000)}`);\n } catch (error) {\n // Skip unreadable files\n }\n }\n \n return samples;\n }\n\n /**\n * Create framework info based on user selection\n */\n private createFrameworkInfo(framework: string): FrameworkInfo {\n const frameworkMap: Record<string, FrameworkInfo> = {\n 'react': { name: 'react', type: 'react' },\n 'nextjs': { name: 'nextjs', type: 'nextjs' },\n 'next': { name: 'nextjs', type: 'nextjs' },\n 'vue': { name: 'vue', type: 'vue' },\n 'nuxt': { name: 'nuxt', type: 'nuxt' },\n 'nuxtjs': { name: 'nuxt', type: 'nuxt' },\n 'angular': { name: 'angular', type: 'angular' },\n 'svelte': { name: 'svelte', type: 'svelte' },\n 'sveltekit': { name: 'svelte', type: 'svelte' },\n 'remix': { name: 'remix', type: 'remix' },\n 'astro': { name: 'astro', type: 'astro' },\n 'gatsby': { name: 'gatsby', type: 'gatsby' },\n 'vanilla': { name: 'vanilla', type: 'vanilla' },\n 'node': { name: 'node', type: 'node' },\n 'auto': { name: 'auto-detected', type: 'auto' }\n };\n\n return frameworkMap[framework] || { name: framework, type: 'vanilla' };\n }\n\n /**\n * Override framework detection to use manual selection\n */\n public async detectFramework(): Promise<FrameworkInfo> {\n return this.framework || { name: 'unknown', type: 'vanilla' };\n }\n\n /**\n * Generate next steps with manual mode info\n */\n private generateManualNextSteps(): string[] {\n return [\n '✅ Manual framework installation completed!',\n `🎯 Selected framework: ${this.framework?.name || 'unknown'}`,\n `🔧 Integration strategy: ${this.getIntegrationStrategy()}`,\n '🚀 Your app is now ready to track user behavior',\n '📊 View sessions in your HumanBehavior dashboard'\n ];\n }\n\n /**\n * Get integration strategy based on framework\n */\n private getIntegrationStrategy(): string {\n if (!this.framework?.type) return 'script';\n \n switch (this.framework.type) {\n case 'react':\n case 'nextjs':\n return 'provider';\n case 'vue':\n return 'plugin';\n case 'angular':\n return 'module';\n default:\n return 'script';\n }\n }\n} ","#!/usr/bin/env node\n\n/**\n * AI-Enhanced HumanBehavior SDK Auto-Installation CLI\n * \n * Usage: npx humanbehavior-js ai-auto-install [api-key]\n * \n * This tool uses AI to intelligently detect frameworks, analyze code patterns,\n * and generate optimal integration code that's both future-proof and backward-compatible.\n */\n\nimport { AIEnhancedInstallationWizard, AIBrowserInstallationWizard } from '../ai/ai-install-wizard';\nimport { ManualFrameworkInstallationWizard } from '../ai/manual-framework-wizard';\nimport { AutoInstallationWizard } from '../core/install-wizard';\nimport { RemoteAIService } from '../services/remote-ai-service';\nimport * as clack from '@clack/prompts';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\ninterface AICLIOptions {\n apiKey?: string;\n projectPath?: string;\n yes?: boolean;\n dryRun?: boolean;\n framework?: string;\n}\n\nclass AIAutoInstallCLI {\n private options: AICLIOptions;\n\n constructor(options: AICLIOptions) {\n this.options = options;\n }\n\n async run() {\n clack.intro('🤖 AI-Enhanced HumanBehavior SDK Auto-Installation');\n\n try {\n // Get API key\n const apiKey = await this.getApiKey();\n if (!apiKey) {\n clack.cancel('API key is required');\n process.exit(1);\n }\n\n // Get project path\n const projectPath = this.options.projectPath || process.cwd();\n \n // Choose framework\n const framework = await this.chooseFramework();\n if (!framework) {\n clack.cancel('Installation cancelled.');\n process.exit(0);\n }\n \n // Confirm installation\n if (!this.options.yes) {\n const confirmed = await this.confirmInstallation(projectPath, framework);\n if (!confirmed) {\n clack.cancel('Installation cancelled.');\n process.exit(0);\n }\n }\n\n // Run installation\n const spinner = clack.spinner();\n spinner.start('🔍 Analyzing your project with AI...');\n \n const wizard = new ManualFrameworkInstallationWizard(apiKey, projectPath, framework);\n const result = await wizard.install();\n\n spinner.stop('Analysis complete!');\n\n // Display results\n this.displayResults(result, framework);\n\n } catch (error) {\n clack.cancel(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exit(1);\n }\n }\n\n private async getApiKey(): Promise<string> {\n if (this.options.apiKey) {\n return this.options.apiKey;\n }\n\n const apiKey = await clack.text({\n message: 'Enter your HumanBehavior API key:',\n placeholder: 'hb_...',\n validate: (value) => {\n if (!value) return 'API key is required';\n if (!value.startsWith('hb_')) return 'API key should start with \"hb_\"';\n return undefined;\n }\n });\n\n return apiKey as string;\n }\n\n\n\n\n\n private async confirmInstallation(projectPath: string, framework: string): Promise<boolean> {\n const confirmed = await clack.confirm({\n message: `Ready to install HumanBehavior SDK in ${projectPath} for ${framework}?`\n });\n\n return confirmed as boolean;\n }\n\n private async chooseFramework(): Promise<string> {\n const framework = await clack.select({\n message: 'Select your framework:',\n options: [\n { label: 'React', value: 'react' },\n { label: 'Next.js', value: 'nextjs' },\n { label: 'Vue', value: 'vue' },\n { label: 'Angular', value: 'angular' },\n { label: 'Svelte', value: 'svelte' },\n { label: 'Nuxt.js', value: 'nuxt' },\n { label: 'Remix', value: 'remix' },\n { label: 'Astro', value: 'astro' },\n { label: 'Gatsby', value: 'gatsby' },\n { label: 'Vanilla JS/TS', value: 'vanilla' }\n ]\n });\n\n return framework as string;\n }\n\n private displayResults(result: any, framework: string) {\n if (result.success) {\n clack.outro('🎉 Installation completed successfully!');\n\n // Display framework info\n clack.note(`Framework detected: ${result.framework.name} (${result.framework.type})`, 'Framework Info');\n\n // Display modifications\n if (result.modifications && result.modifications.length > 0) {\n const modifications = result.modifications.map((mod: any) => \n `${mod.action}: ${mod.filePath} - ${mod.description}`\n );\n clack.note(modifications.join('\\n'), 'Files Modified');\n }\n\n // Display next steps\n if (result.nextSteps && result.nextSteps.length > 0) {\n clack.note(result.nextSteps.join('\\n'), 'Next Steps');\n }\n\n // Display AI insights if available\n if (result.aiAnalysis) {\n clack.note(`Confidence: ${Math.round(result.aiAnalysis.confidence * 100)}%`, 'AI Analysis');\n if (result.aiAnalysis.recommendations && result.aiAnalysis.recommendations.length > 0) {\n clack.note(result.aiAnalysis.recommendations.join('\\n'), 'AI Recommendations');\n }\n }\n\n } else {\n clack.cancel('Installation failed');\n \n if (result.errors && result.errors.length > 0) {\n clack.note(result.errors.join('\\n'), 'Errors');\n }\n }\n }\n}\n\nfunction parseArgs(): AICLIOptions {\n const args = process.argv.slice(2);\n const options: AICLIOptions = {};\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n \n switch (arg) {\n case '--help':\n case '-h':\n showHelp();\n process.exit(0);\n break;\n case '--yes':\n case '-y':\n options.yes = true;\n break;\n case '--dry-run':\n options.dryRun = true;\n break;\n case '--project':\n case '-p':\n options.projectPath = args[++i];\n break;\n case '--framework':\n case '-f':\n options.framework = args[++i];\n break;\n case 'init':\n if (!args[i+1] || args[i+1].startsWith('-')) {\n showInitHelp();\n process.exit(1);\n }\n options.apiKey = args[++i];\n break;\n default:\n if (!options.apiKey && !arg.startsWith('-')) {\n options.apiKey = arg;\n }\n break;\n }\n }\n\n return options;\n}\n\nfunction showHelp() {\n console.log(`\n🤖 HumanBehavior SDK AI Auto-Installation\n\nUsage: npx humanbehavior-js ai-auto-install [api-key] [options]\n\nOptions:\n -h, --help Show this help message\n -y, --yes Skip all prompts and use defaults\n --dry-run Show what would be changed without making changes\n\n -p, --project <path> Specify project directory\n -f, --framework <name> Specify framework manually\n\nExamples:\n npx humanbehavior-js ai-auto-install\n npx humanbehavior-js ai-auto-install hb_your_api_key_here\n npx humanbehavior-js ai-auto-install --project ./my-app --ai\n npx humanbehavior-js ai-auto-install --framework react --yes\n`);\n}\n\nfunction showInitHelp() {\n console.log(`\nUsage: npx humanbehavior-js init <api-key>\n\nArguments:\n api-key Your HumanBehavior API key (required, starts with \"hb_\")\n\nExamples:\n npx humanbehavior-js init hb_your_api_key_here\n`);\n}\n\n// Main execution\nconst options = parseArgs();\nconst cli = new AIAutoInstallCLI(options);\ncli.run().catch((error) => {\n clack.cancel(`Unexpected error: ${error.message}`);\n process.exit(1);\n});\n\nexport { AIAutoInstallCLI }; ","#!/usr/bin/env node\n\n/**\n * HumanBehavior SDK Auto-Installation CLI\n * \n * Usage: npx humanbehavior-js auto-install [api-key]\n * \n * This tool automatically detects the user's framework and modifies their codebase\n * to integrate the SDK with minimal user intervention.\n */\n\nimport { AutoInstallationWizard } from '../core/install-wizard';\nimport * as clack from '@clack/prompts';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\ninterface CLIOptions {\n apiKey?: string;\n projectPath?: string;\n yes?: boolean;\n dryRun?: boolean;\n}\n\nclass AutoInstallCLI {\n private options: CLIOptions;\n\n constructor(options: CLIOptions) {\n this.options = options;\n }\n\n async run() {\n clack.intro('🚀 HumanBehavior SDK Auto-Installation');\n\n try {\n // Get API key\n const apiKey = await this.getApiKey();\n if (!apiKey) {\n clack.cancel('API key is required');\n process.exit(1);\n }\n\n // Get project path\n const projectPath = this.options.projectPath || process.cwd();\n \n // Confirm installation\n if (!this.options.yes) {\n const confirmed = await this.confirmInstallation(projectPath);\n if (!confirmed) {\n clack.cancel('Installation cancelled.');\n process.exit(0);\n }\n }\n\n // Run installation\n const spinner = clack.spinner();\n spinner.start('🔍 Detecting framework and applying integration...');\n \n const wizard = new AutoInstallationWizard(apiKey, projectPath);\n const result = await wizard.install();\n\n spinner.stop('Installation complete!');\n\n // Display results\n this.displayResults(result);\n\n } catch (error) {\n clack.cancel(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exit(1);\n }\n }\n\n private async getApiKey(): Promise<string> {\n if (this.options.apiKey) {\n return this.options.apiKey;\n }\n\n const apiKey = await clack.text({\n message: 'Enter your HumanBehavior API key:',\n placeholder: 'hb_...',\n validate: (value) => {\n if (!value) return 'API key is required';\n if (!value.startsWith('hb_')) return 'API key should start with \"hb_\"';\n return undefined;\n }\n });\n\n return apiKey as string;\n }\n\n\n\n // Framework selection no longer needed; AutoInstallationWizard auto-detects\n\n private async confirmInstallation(projectPath: string): Promise<boolean> {\n const confirmed = await clack.confirm({\n message: `Ready to install HumanBehavior SDK in ${projectPath}?`\n });\n\n return confirmed as boolean;\n }\n\n private displayResults(result: any) {\n if (result.success) {\n clack.outro('🎉 Installation completed successfully!');\n\n // Display framework info\n clack.note(`Framework detected: ${result.framework.name} (${result.framework.type})`, 'Framework Info');\n\n // Display modifications\n if (result.modifications && result.modifications.length > 0) {\n const modifications = result.modifications.map((mod: any) => \n `${mod.action}: ${mod.filePath} - ${mod.description}`\n );\n clack.note(modifications.join('\\n'), 'Files Modified');\n }\n\n // Display next steps\n if (result.nextSteps && result.nextSteps.length > 0) {\n clack.note(result.nextSteps.join('\\n'), 'Next Steps');\n }\n\n } else {\n clack.cancel('Installation failed');\n \n if (result.errors && result.errors.length > 0) {\n clack.note(result.errors.join('\\n'), 'Errors');\n }\n }\n }\n}\n\nfunction parseArgs(): CLIOptions {\n const args = process.argv.slice(2);\n const options: CLIOptions = {};\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n \n switch (arg) {\n case '--help':\n case '-h':\n showHelp();\n process.exit(0);\n break;\n case '--yes':\n case '-y':\n options.yes = true;\n break;\n case '--dry-run':\n options.dryRun = true;\n break;\n case '--project':\n case '-p':\n options.projectPath = args[++i];\n break;\n default:\n if (!options.apiKey && !arg.startsWith('-')) {\n options.apiKey = arg;\n }\n break;\n }\n }\n\n return options;\n}\n\nfunction showHelp() {\n console.log(`\n🚀 HumanBehavior SDK Auto-Installation\n\nUsage: npx humanbehavior-js auto-install [api-key] [options]\n\nThis tool automatically detects your framework and integrates the HumanBehavior SDK.\n\nOptions:\n -h, --help Show this help message\n -y, --yes Skip all prompts and use defaults\n --dry-run Show what would be changed without making changes\n -p, --project <path> Specify project directory\n\nExamples:\n npx humanbehavior-js auto-install\n npx humanbehavior-js auto-install hb_your_api_key_here\n npx humanbehavior-js auto-install --project ./my-app --yes\n`);\n}\n\n// Main execution (ES module compatible)\n// Check if this file is being run directly\nconst isMain = import.meta.url === `file://${process.argv[1]}`;\nif (isMain) {\n const options = parseArgs();\n const cli = new AutoInstallCLI(options);\n cli.run().catch((error) => {\n clack.cancel(`Unexpected error: ${error.message}`);\n process.exit(1);\n });\n}\n\nexport { AutoInstallCLI }; ","/**\n * Centralized AI Service Implementation\n * \n * This service runs on your backend infrastructure and provides AI-powered\n * code analysis without requiring users to provide their own API keys.\n * \n * The service can be deployed as:\n * - AWS Lambda function\n * - Docker container\n * - Express.js server\n * - Cloud function\n */\n\nimport { AICodeAnalysis } from '../ai/ai-install-wizard';\n\nexport interface FrameworkInfo {\n name: string;\n type: 'react' | 'vue' | 'angular' | 'svelte' | 'nextjs' | 'nuxt' | 'remix' | 'vanilla' | 'astro' | 'node';\n bundler?: 'vite' | 'webpack' | 'esbuild' | 'rollup';\n packageManager?: 'npm' | 'yarn' | 'pnpm';\n hasTypeScript?: boolean;\n hasRouter?: boolean;\n projectRoot?: string;\n}\n\nexport interface CentralizedAIServiceConfig {\n openaiApiKey: string;\n openaiModel?: string;\n maxTokens?: number;\n temperature?: number;\n enableCaching?: boolean;\n cacheTTL?: number;\n}\n\nexport interface AIAnalysisRequest {\n codeSamples: string[];\n projectType?: string;\n userAgent?: string;\n timestamp: string;\n}\n\nexport interface AIAnalysisResponse {\n analysis: AICodeAnalysis;\n processingTime: number;\n cacheHit?: boolean;\n modelUsed: string;\n}\n\nexport interface ConflictResolutionRequest {\n conflicts: string[];\n framework: FrameworkInfo;\n codeContext?: string;\n}\n\nexport interface OptimizationRequest {\n framework: FrameworkInfo;\n patterns: string[];\n projectContext?: string;\n}\n\n/**\n * Centralized AI Service Implementation\n * This runs on your backend infrastructure\n */\nexport class CentralizedAIService {\n private config: CentralizedAIServiceConfig;\n private cache: Map<string, any> = new Map();\n private openai: any; // OpenAI client\n\n constructor(config: CentralizedAIServiceConfig) {\n this.config = {\n openaiModel: 'gpt-4',\n maxTokens: 2000,\n temperature: 0.3,\n enableCaching: true,\n cacheTTL: 3600, // 1 hour\n ...config\n };\n \n this.initializeOpenAI();\n }\n\n /**\n * Initialize OpenAI client\n */\n private initializeOpenAI() {\n try {\n // Import OpenAI dynamically to avoid bundling issues\n const { OpenAI } = require('openai');\n this.openai = new OpenAI({\n apiKey: this.config.openaiApiKey\n });\n } catch (error) {\n console.warn('OpenAI not available, falling back to heuristic analysis');\n this.openai = null;\n }\n }\n\n /**\n * Analyze code patterns using AI\n */\n async analyzeCodePatterns(codeSamples: string[]): Promise<AICodeAnalysis> {\n const request: AIAnalysisRequest = {\n codeSamples,\n timestamp: new Date().toISOString()\n };\n\n // Check cache first\n const cacheKey = this.generateCacheKey(request);\n if (this.config.enableCaching) {\n const cached = this.cache.get(cacheKey);\n if (cached && this.isCacheValid(cached.timestamp)) {\n return cached.analysis;\n }\n }\n\n // Perform AI analysis\n const startTime = Date.now();\n const analysis = await this.performAIAnalysis(request);\n const processingTime = Date.now() - startTime;\n\n // Cache the result\n if (this.config.enableCaching) {\n this.cache.set(cacheKey, {\n analysis,\n timestamp: Date.now()\n });\n }\n\n return analysis;\n }\n\n /**\n * Resolve conflicts using AI\n */\n async resolveConflicts(conflicts: string[], framework: FrameworkInfo): Promise<string[]> {\n const request: ConflictResolutionRequest = {\n conflicts,\n framework,\n codeContext: 'HumanBehavior SDK integration'\n };\n\n if (!this.openai) {\n return this.resolveConflictsHeuristic(conflicts, framework);\n }\n\n try {\n const prompt = this.buildConflictResolutionPrompt(request);\n const response = await this.openai.chat.completions.create({\n model: this.config.openaiModel,\n messages: [\n {\n role: 'system',\n content: 'You are an expert at resolving code integration conflicts. Provide specific resolution strategies.'\n },\n {\n role: 'user',\n content: prompt\n }\n ],\n max_tokens: this.config.maxTokens,\n temperature: this.config.temperature\n });\n\n const content = response.choices[0]?.message?.content;\n if (content && typeof content === 'string') {\n return this.parseConflictResolutions(content);\n }\n return [];\n } catch (error) {\n console.warn('AI conflict resolution failed, using heuristic approach:', error instanceof Error ? error.message : 'Unknown error');\n }\n\n return this.resolveConflictsHeuristic(conflicts, framework);\n }\n\n /**\n * Generate optimizations using AI\n */\n async generateOptimizations(framework: FrameworkInfo, patterns: string[]): Promise<string[]> {\n const request: OptimizationRequest = {\n framework,\n patterns,\n projectContext: 'HumanBehavior SDK integration'\n };\n\n if (!this.openai) {\n return this.generateOptimizationsHeuristic(framework, patterns);\n }\n\n try {\n const prompt = this.buildOptimizationPrompt(request);\n const response = await this.openai.chat.completions.create({\n model: this.config.openaiModel,\n messages: [\n {\n role: 'system',\n content: 'You are an expert at optimizing code integration. Provide specific, actionable recommendations.'\n },\n {\n role: 'user',\n content: prompt\n }\n ],\n max_tokens: this.config.maxTokens,\n temperature: this.config.temperature\n });\n\n const content = response.choices[0]?.message?.content;\n if (content) {\n return this.parseOptimizations(content);\n }\n } catch (error) {\n console.warn('AI optimization generation failed, using heuristic approach:', error instanceof Error ? error.message : 'Unknown error');\n }\n\n return this.generateOptimizationsHeuristic(framework, patterns);\n }\n\n /**\n * Perform AI analysis\n */\n private async performAIAnalysis(request: AIAnalysisRequest): Promise<AICodeAnalysis> {\n if (!this.openai) {\n return this.performHeuristicAnalysis(request);\n }\n\n try {\n const prompt = this.buildAnalysisPrompt(request);\n const response = await this.openai.chat.completions.create({\n model: this.config.openaiModel,\n messages: [\n {\n role: 'system',\n content: 'You are an expert at analyzing code patterns and determining optimal integration strategies. Provide detailed analysis in JSON format.'\n },\n {\n role: 'user',\n content: prompt\n }\n ],\n max_tokens: this.config.maxTokens,\n temperature: this.config.temperature,\n response_format: { type: 'json_object' }\n });\n\n const content = response.choices[0]?.message?.content;\n if (content) {\n return this.parseAnalysisResult(content);\n }\n } catch (error) {\n console.warn('AI analysis failed, using heuristic approach:', error instanceof Error ? error.message : 'Unknown error');\n }\n\n return this.performHeuristicAnalysis(request);\n }\n\n /**\n * Build analysis prompt\n */\n private buildAnalysisPrompt(request: AIAnalysisRequest): string {\n return `Analyze these code samples to determine the framework and integration strategy:\n\n${request.codeSamples.join('\\n\\n')}\n\nProvide analysis in JSON format with:\n- framework: { name, type, confidence (0-1) }\n- patterns: array of detected patterns\n- conflicts: array of potential conflicts\n- recommendations: array of integration recommendations\n- integrationStrategy: \"provider\" | \"plugin\" | \"module\" | \"script\" | \"standalone\"\n- compatibilityMode: \"modern\" | \"legacy\" | \"hybrid\"\n\nFocus on:\n1. Framework detection beyond package.json\n2. Code patterns and architecture\n3. Integration compatibility\n4. Future-proof strategies\n5. Backward compatibility needs\n\nRespond with valid JSON only.`;\n }\n\n /**\n * Build conflict resolution prompt\n */\n private buildConflictResolutionPrompt(request: ConflictResolutionRequest): string {\n return `Resolve these integration conflicts for ${request.framework.name}:\n\nConflicts: ${request.conflicts.join(', ')}\n\nFramework: ${request.framework.name} (${request.framework.type})\nContext: ${request.codeContext}\n\nProvide specific resolution strategies for each conflict. Options:\n- update_existing_integration: Update existing code\n- merge_providers: Merge multiple providers\n- hybrid_module_support: Support both module systems\n- skip_conflict: Skip the modification\n- custom_resolution: Custom resolution strategy\n\nRespond with a JSON array of resolution strategies.`;\n }\n\n /**\n * Build optimization prompt\n */\n private buildOptimizationPrompt(request: OptimizationRequest): string {\n return `Generate optimizations for ${request.framework.name} integration:\n\nFramework: ${request.framework.name} (${request.framework.type})\nPatterns: ${request.patterns.join(', ')}\nContext: ${request.projectContext}\n\nProvide specific, actionable optimization recommendations for:\n1. Performance improvements\n2. Error handling\n3. Code organization\n4. Future-proofing\n5. Backward compatibility\n\nRespond with a JSON array of optimization recommendations.`;\n }\n\n /**\n * Parse analysis result\n */\n private parseAnalysisResult(content: string): AICodeAnalysis {\n try {\n const result = JSON.parse(content);\n return {\n framework: result.framework || { name: 'vanilla', type: 'vanilla' },\n confidence: result.confidence || 0.5,\n patterns: result.patterns || [],\n conflicts: result.conflicts || [],\n recommendations: result.recommendations || [],\n integrationStrategy: result.integrationStrategy || 'script',\n compatibilityMode: result.compatibilityMode || 'modern'\n };\n } catch (error) {\n console.warn('Failed to parse AI analysis result:', error);\n return this.getDefaultAnalysis();\n }\n }\n\n /**\n * Parse conflict resolutions\n */\n private parseConflictResolutions(content: string): string[] {\n try {\n const result = JSON.parse(content);\n return Array.isArray(result) ? result : [];\n } catch (error) {\n console.warn('Failed to parse conflict resolutions:', error);\n return [];\n }\n }\n\n /**\n * Parse optimizations\n */\n private parseOptimizations(content: string): string[] {\n try {\n const result = JSON.parse(content);\n return Array.isArray(result) ? result : [];\n } catch (error) {\n console.warn('Failed to parse optimizations:', error);\n return [];\n }\n }\n\n /**\n * Heuristic analysis fallback\n */\n private performHeuristicAnalysis(request: AIAnalysisRequest): AICodeAnalysis {\n const patterns = request.codeSamples.join(' ').toLowerCase();\n \n // Framework detection\n let framework: FrameworkInfo = { name: 'vanilla', type: 'vanilla' };\n let confidence = 0.5;\n \n if (patterns.includes('react')) {\n framework = { name: 'react', type: 'react' };\n confidence = 0.9;\n } else if (patterns.includes('vue')) {\n framework = { name: 'vue', type: 'vue' };\n confidence = 0.9;\n } else if (patterns.includes('angular')) {\n framework = { name: 'angular', type: 'angular' };\n confidence = 0.9;\n } else if (patterns.includes('svelte')) {\n framework = { name: 'svelte', type: 'svelte' };\n confidence = 0.9;\n } else if (patterns.includes('next')) {\n framework = { name: 'nextjs', type: 'nextjs' };\n confidence = 0.9;\n } else if (patterns.includes('nuxt')) {\n framework = { name: 'nuxt', type: 'nuxt' };\n confidence = 0.9;\n }\n \n // Integration strategy\n let integrationStrategy: 'provider' | 'plugin' | 'module' | 'script' | 'standalone' = 'script';\n if (framework.type === 'react' || framework.type === 'nextjs') {\n integrationStrategy = 'provider';\n } else if (framework.type === 'vue') {\n integrationStrategy = 'plugin';\n } else if (framework.type === 'angular') {\n integrationStrategy = 'module';\n }\n \n // Compatibility mode\n let compatibilityMode: 'modern' | 'legacy' | 'hybrid' = 'modern';\n if (patterns.includes('require(') || patterns.includes('var ')) {\n compatibilityMode = 'legacy';\n }\n \n return {\n framework,\n confidence,\n patterns: request.codeSamples,\n conflicts: [],\n recommendations: [],\n integrationStrategy,\n compatibilityMode\n };\n }\n\n /**\n * Heuristic conflict resolution\n */\n private resolveConflictsHeuristic(conflicts: string[], framework: FrameworkInfo): string[] {\n const resolutions: string[] = [];\n \n for (const conflict of conflicts) {\n switch (conflict) {\n case 'existing_humanbehavior_code':\n resolutions.push('update_existing_integration');\n break;\n case 'existing_provider':\n resolutions.push('merge_providers');\n break;\n case 'module_system_conflict':\n resolutions.push('hybrid_module_support');\n break;\n default:\n resolutions.push('skip_conflict');\n }\n }\n \n return resolutions;\n }\n\n /**\n * Heuristic optimization generation\n */\n private generateOptimizationsHeuristic(framework: FrameworkInfo, patterns: string[]): string[] {\n const optimizations: string[] = [];\n \n switch (framework.type) {\n case 'react':\n optimizations.push('Use React.memo for performance optimization');\n optimizations.push('Implement error boundaries for better error tracking');\n optimizations.push('Consider using React.lazy for code splitting');\n break;\n case 'vue':\n optimizations.push('Use Vue 3 Composition API for better performance');\n optimizations.push('Implement proper error handling in components');\n optimizations.push('Consider using Vue Router for navigation tracking');\n break;\n case 'angular':\n optimizations.push('Use Angular standalone components for better tree-shaking');\n optimizations.push('Implement proper error handling with ErrorHandler');\n optimizations.push('Consider using Angular signals for state management');\n break;\n default:\n optimizations.push('Enable performance tracking');\n optimizations.push('Implement error tracking');\n optimizations.push('Consider progressive enhancement');\n }\n \n return optimizations;\n }\n\n /**\n * Generate cache key\n */\n private generateCacheKey(request: AIAnalysisRequest): string {\n const content = JSON.stringify(request);\n return Buffer.from(content).toString('base64').substring(0, 32);\n }\n\n /**\n * Check if cache is valid\n */\n private isCacheValid(timestamp: number): boolean {\n const now = Date.now();\n const ttl = (this.config.cacheTTL || 3600) * 1000; // Convert to milliseconds\n return (now - timestamp) < ttl;\n }\n\n /**\n * Get default analysis\n */\n private getDefaultAnalysis(): AICodeAnalysis {\n return {\n framework: { name: 'vanilla', type: 'vanilla' },\n confidence: 0.5,\n patterns: [],\n conflicts: [],\n recommendations: [],\n integrationStrategy: 'script',\n compatibilityMode: 'modern'\n };\n }\n\n /**\n * Get service statistics\n */\n getStats() {\n return {\n cacheSize: this.cache.size,\n config: {\n model: this.config.openaiModel,\n maxTokens: this.config.maxTokens,\n temperature: this.config.temperature,\n caching: this.config.enableCaching\n },\n openaiAvailable: !!this.openai\n };\n }\n\n /**\n * Clear cache\n */\n clearCache() {\n this.cache.clear();\n }\n}\n\n/**\n * Express.js server implementation\n */\nexport function createAIServiceServer(config: CentralizedAIServiceConfig) {\n const express = require('express');\n const app = express();\n const aiService = new CentralizedAIService(config);\n\n app.use(express.json());\n\n // Health check endpoint\n app.get('/health', (req: any, res: any) => {\n res.json({ status: 'healthy', stats: aiService.getStats() });\n });\n\n // Analysis endpoint\n app.post('/analyze', async (req: any, res: any) => {\n try {\n const { codeSamples, projectType, userAgent } = req.body;\n \n if (!codeSamples || !Array.isArray(codeSamples)) {\n return res.status(400).json({ error: 'codeSamples array is required' });\n }\n\n const startTime = Date.now();\n const analysis = await aiService.analyzeCodePatterns(codeSamples);\n const processingTime = Date.now() - startTime;\n\n res.json({\n analysis,\n processingTime,\n modelUsed: config.openaiModel || 'heuristic'\n });\n } catch (error) {\n res.status(500).json({ error: 'Analysis failed', details: error instanceof Error ? error.message : 'Unknown error' });\n }\n });\n\n // Conflict resolution endpoint\n app.post('/resolve-conflicts', async (req: any, res: any) => {\n try {\n const { conflicts, framework } = req.body;\n \n if (!conflicts || !framework) {\n return res.status(400).json({ error: 'conflicts and framework are required' });\n }\n\n const resolutions = await aiService.resolveConflicts(conflicts, framework);\n res.json({ resolutions });\n } catch (error) {\n res.status(500).json({ error: 'Conflict resolution failed', details: error instanceof Error ? error.message : 'Unknown error' });\n }\n });\n\n // Optimization endpoint\n app.post('/optimize', async (req: any, res: any) => {\n try {\n const { framework, patterns } = req.body;\n \n if (!framework || !patterns) {\n return res.status(400).json({ error: 'framework and patterns are required' });\n }\n\n const optimizations = await aiService.generateOptimizations(framework, patterns);\n res.json({ optimizations });\n } catch (error) {\n res.status(500).json({ error: 'Optimization failed', details: error instanceof Error ? error.message : 'Unknown error' });\n }\n });\n\n return app;\n}\n\n/**\n * AWS Lambda handler\n */\nexport async function lambdaHandler(event: any, context: any) {\n const config: CentralizedAIServiceConfig = {\n openaiApiKey: process.env.OPENAI_API_KEY!,\n openaiModel: process.env.OPENAI_MODEL || 'gpt-4',\n maxTokens: parseInt(process.env.MAX_TOKENS || '2000'),\n temperature: parseFloat(process.env.TEMPERATURE || '0.3'),\n enableCaching: process.env.ENABLE_CACHING !== 'false',\n cacheTTL: parseInt(process.env.CACHE_TTL || '3600')\n };\n\n const aiService = new CentralizedAIService(config);\n\n try {\n const { path, httpMethod, body } = event;\n const parsedBody = body ? JSON.parse(body) : {};\n\n switch (path) {\n case '/analyze':\n if (httpMethod !== 'POST') {\n return { statusCode: 405, body: JSON.stringify({ error: 'Method not allowed' }) };\n }\n \n const analysis = await aiService.analyzeCodePatterns(parsedBody.codeSamples || []);\n return {\n statusCode: 200,\n body: JSON.stringify({ analysis })\n };\n\n case '/resolve-conflicts':\n if (httpMethod !== 'POST') {\n return { statusCode: 405, body: JSON.stringify({ error: 'Method not allowed' }) };\n }\n \n const resolutions = await aiService.resolveConflicts(\n parsedBody.conflicts || [],\n parsedBody.framework || { name: 'vanilla', type: 'vanilla' }\n );\n return {\n statusCode: 200,\n body: JSON.stringify({ resolutions })\n };\n\n default:\n return { statusCode: 404, body: JSON.stringify({ error: 'Not found' }) };\n }\n } catch (error) {\n return {\n statusCode: 500,\n body: JSON.stringify({ error: 'Internal server error', details: error instanceof Error ? error.message : 'Unknown error' })\n };\n }\n} "],"names":["AutoInstallationWizard","constructor","apiKey","projectRoot","process","cwd","this","framework","manualNotes","compareVersions","version1","version2","v1Parts","split","map","Number","v2Parts","i","Math","max","length","v1","v2","isVersionGte","version","target","getMajorVersion","parseInt","install","detectFramework","installPackage","modifications","generateModifications","applyModifications","nextSteps","generateNextSteps","success","errors","error","name","type","Error","message","packageJsonPath","path","join","fs","existsSync","packageJson","JSON","parse","readFileSync","dependencies","devDependencies","features","nuxt","nuxtVersion","isNuxt3","majorVersion","hasTypeScript","typescript","hasRouter","hasNuxt3","next","nextVersion","isNext13","hasNextAppRouter","remixVersion","react","reactVersion","isReact18","hasReact18","vue","vueVersion","isVue3","hasVue3","angularVersion","isAngular17","hasAngularStandalone","svelte","svelteVersion","isSvelteKit","hasSvelteKit","astro","astroVersion","gatsby","gatsbyVersion","vite","bundler","webpack","esbuild","rollup","packageManager","command","execSync","stdio","push","generateReactModifications","generateNextJSModifications","generateNuxtModifications","generateAstroModifications","generateGatsbyModifications","generateRemixModifications","generateVueModifications","generateAngularModifications","generateSvelteModifications","generateVanillaModifications","appFile","findReactAppFile","content","modifiedContent","injectReactProvider","filePath","action","description","createEnvironmentModification","mergeProvidersFile","hbProviderContent","existingContent","includes","replace","trimmed","trimEnd","appLayoutFileWithSrc","appLayoutFile","pagesLayoutFileWithSrc","pagesLayoutFile","actualAppLayoutFile","providersFilePath","providersImportPath","providersContent","fileExists","injectNextJSAppRouter","actualPagesLayoutFile","providersPath","importPath","injectNextJSPagesRouter","astroComponentPath","layoutFiles","layoutFile","file","injectAstroLayout","pluginFile","nuxtConfigFile","mod","applyOrNotify","c","injectNuxtConfig","rootFile","injectRemixProvider","mainFile","findVueMainFile","composableDir","composablePath","mkdirSync","recursive","injectVuePlugin","serviceDir","servicePath","envFile","envProdFile","envDir","dirname","appComponentPath","appContent","modifiedAppContent","svelteConfigFile","injectSvelteKitLayout","findSvelteMainFile","injectSvelteStore","htmlFile","findHTMLFile","injectVanillaScript","gatsbyBrowserFile","injectGatsbyBrowser","modification","dir","writeFileSync","appendFileSync","steps","n","transform","manualNote","relative","original","updated","possibleFiles","fullPath","endsWith","envVar","importStatement","match","bodyAttrs","bodyContent","trim","isVue3ByContent","importComposable","lastImportIndex","lastIndexOf","nextLineIndex","indexOf","slice","trackerImport","injectAngularModule","injectAngularStandaloneInit","envImport","hbImport","browserImport","initCode","initScript","frontmatterEndIndex","bodyCloseIndex","pattern","test","replaced","startIdx","braceIdx","insertion","injectGatsbyLayout","modified","findBestEnvFile","possibleEnvFiles","envVarName","nextjs","angular","remix","vanilla","node","auto","getEnvVarName","defaultFile","cleanApiKey","basename","DefaultAIService","analyzeCodePatterns","codeSamples","analyzeWithHeuristics","resolveConflicts","conflicts","resolutions","conflict","generateOptimizations","patterns","optimizations","toLowerCase","confidence","integrationStrategy","compatibilityMode","recommendations","AIEnhancedInstallationWizard","aiService","super","learningCache","Map","patternDatabase","loadLearningData","aiAnalysis","performAICodeAnalysis","detectFrameworkWithAI","generateAIOptimizedModifications","applyModificationsWithAI","generateAINextSteps","learnFromInstallation","learningData","projectFiles","scanProjectFiles","extractCodeSamples","files","scanDir","depth","items","readdirSync","item","stat","statSync","isDirectory","startsWith","isFile","isRelevantFile","filename","some","ext","samples","relativePath","extractCodePatterns","frameworkPatterns","regexes","Object","entries","regex","matches","toUpperCase","importMatches","exportMatches","traditionalFramework","enhancedModifications","enhanceModificationWithAI","aiOptimizations","generateAIOptimizations","enhancedContent","detectConflicts","resolvedModification","applyModification","resolvedContent","round","forEach","rec","timestamp","Date","toISOString","set","now","has","get","saveLearningData","getAIInsights","frameworkName","getLearningStats","stats","totalInstallations","size","frameworks","data","AIBrowserInstallationWizard","performBrowserAIAnalysis","generateAIBrowserModifications","detectBrowserFramework","analyzeBrowserPatterns","window","React","Vue","document","querySelector","querySelectorAll","script","src","RemoteAIService","config","timeout","response","fetch","apiEndpoint","method","headers","body","stringify","signal","AbortSignal","ok","status","statusText","json","analysis","console","warn","performHeuristicAnalysis","resolveConflictsHeuristic","generateOptimizationsHeuristic","ManualFrameworkInstallationWizard","selectedFramework","createFrameworkInfo","runFullDetection","detectedFramework","generateManualNextSteps","manualMode","tempWizard","substring","nuxtjs","sveltekit","getIntegrationStrategy","AIAutoInstallCLI","options","run","clack","intro","getApiKey","cancel","exit","projectPath","chooseFramework","yes","confirmInstallation","spinner","start","wizard","result","stop","displayResults","text","placeholder","validate","value","confirm","select","label","outro","note","showHelp","log","showInitHelp","args","argv","arg","dryRun","parseArgs","catch","AutoInstallCLI","url","CentralizedAIService","cache","openaiModel","maxTokens","temperature","enableCaching","cacheTTL","initializeOpenAI","OpenAI","require","openai","openaiApiKey","request","cacheKey","generateCacheKey","cached","isCacheValid","performAIAnalysis","codeContext","prompt","buildConflictResolutionPrompt","chat","completions","create","model","messages","role","max_tokens","choices","parseConflictResolutions","projectContext","buildOptimizationPrompt","parseOptimizations","buildAnalysisPrompt","response_format","parseAnalysisResult","getDefaultAnalysis","Array","isArray","Buffer","from","toString","getStats","cacheSize","caching","openaiAvailable","clearCache","clear"],"mappings":"4HA8CaA,EAMX,WAAAC,CAAYC,EAAgBC,EAAsBC,QAAQC,OAHhDC,KAAAC,UAAkC,KACpCD,KAAAE,YAAwB,GAG9BF,KAAKJ,OAASA,EACdI,KAAKH,YAAcA,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AarH,GAGnB,OAFYC,KAAKG,MAEHJ,EAD+B,KAAhC7S,KAAK2U,OAAO6E,UAAY,KAEvC,CAKQ,kBAAA8B,GACN,MAAO,CACLrb,UAAW,CAAEgC,KAAM,UAAWC,KAAM,WACpC6M,WAAY,GACZH,SAAU,GACVJ,UAAW,GACXU,gBAAiB,GACjBF,oBAAqB,SACrBC,kBAAmB,SAEvB,CAKA,QAAA2M,GACE,MAAO,CACLC,UAAW7b,KAAKmZ,MAAMzF,KACtBiB,OAAQ,CACN+F,MAAO1a,KAAK2U,OAAOyE,YACnBC,UAAWrZ,KAAK2U,OAAO0E,UACvBC,YAAatZ,KAAK2U,OAAO2E,YACzBwC,QAAS9b,KAAK2U,OAAO4E,eAEvBwC,kBAAmB/b,KAAK4Z,OAE5B,CAKA,UAAAoC,GACEhc,KAAKmZ,MAAM8C,OACb"}
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../src/core/install-wizard.ts","../src/ai/ai-install-wizard.ts","../src/services/remote-ai-service.ts","../src/ai/manual-framework-wizard.ts","../src/agent/claude-agent-installer.ts","../src/cli/ai-auto-install.ts","../src/cli/auto-install.ts","../src/services/centralized-ai-service.ts"],"sourcesContent":["/**\n * HumanBehavior SDK Auto-Installation Wizard\n * \n * This wizard automatically detects the user's framework and modifies their codebase\n * to integrate the SDK with minimal user intervention.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { execSync } from 'child_process';\n\nconst MIN_SUPPORTED_SDK_VERSION = '0.7.0';\nconst TESTED_SDK_VERSION = '0.7.0';\n\nexport interface FrameworkInfo {\n name: string;\n type: 'react' | 'vue' | 'angular' | 'svelte' | 'nextjs' | 'nuxt' | 'remix' | 'vanilla' | 'astro' | 'gatsby' | 'node' | 'auto';\n bundler?: 'vite' | 'webpack' | 'esbuild' | 'rollup';\n packageManager?: 'npm' | 'yarn' | 'pnpm' | 'bun';\n hasTypeScript?: boolean;\n hasRouter?: boolean;\n projectRoot?: string;\n version?: string;\n majorVersion?: number;\n features?: {\n hasReact18?: boolean;\n hasVue3?: boolean;\n hasNuxt3?: boolean;\n hasAngularStandalone?: boolean;\n hasNextAppRouter?: boolean;\n hasSvelteKit?: boolean;\n };\n}\n\nexport interface CodeModification {\n filePath: string;\n action: 'create' | 'modify' | 'append';\n content: string;\n description: string;\n}\n\nexport interface InstallationResult {\n success: boolean;\n framework: FrameworkInfo;\n modifications: CodeModification[];\n errors: string[];\n nextSteps: string[];\n dryRun?: boolean;\n installPlan?: PackageInstallPlan;\n agentPlan?: AgentInstallationPlan;\n}\n\nexport interface AgentInstallationPlan {\n summary: string;\n targetPackagePath?: string;\n framework?: string;\n packageManager?: string;\n recommendedChecks: string[];\n risks: string[];\n confidence: number;\n rawResult?: string;\n}\n\nexport interface InstallationWizardOptions {\n dryRun?: boolean;\n skipInstall?: boolean;\n upgrade?: boolean;\n agentPlan?: AgentInstallationPlan;\n}\n\nexport interface PackageInstallPlan {\n packageName: string;\n packageManager: 'npm' | 'yarn' | 'pnpm' | 'bun';\n command: string;\n cwd: string;\n targetPackagePath: string;\n workspaceRoot: string;\n isWorkspace: boolean;\n alreadyInstalled: boolean;\n installedVersion?: string;\n minimumSupportedVersion: string;\n testedVersion: string;\n versionStatus: 'not-installed' | 'compatible' | 'stale' | 'newer' | 'unknown';\n shouldInstall: boolean;\n reason: string;\n}\n\nexport class AutoInstallationWizard {\n protected apiKey: string;\n protected projectRoot: string;\n protected framework: FrameworkInfo | null = null;\n protected options: InstallationWizardOptions;\n private manualNotes: string[] = [];\n\n constructor(apiKey: string, projectRoot: string = process.cwd(), options: InstallationWizardOptions = {}) {\n this.apiKey = apiKey;\n this.projectRoot = path.resolve(projectRoot);\n this.options = options;\n }\n\n public setAgentPlan(agentPlan: AgentInstallationPlan): void {\n this.options.agentPlan = agentPlan;\n }\n\n /**\n * Simple version comparison utility\n */\n private compareVersions(version1: string, version2: string): number {\n const v1Parts = version1.split('.').map(Number);\n const v2Parts = version2.split('.').map(Number);\n \n for (let i = 0; i < Math.max(v1Parts.length, v2Parts.length); i++) {\n const v1 = v1Parts[i] || 0;\n const v2 = v2Parts[i] || 0;\n if (v1 > v2) return 1;\n if (v1 < v2) return -1;\n }\n return 0;\n }\n\n private isVersionGte(version: string, target: string): boolean {\n return this.compareVersions(version, target) >= 0;\n }\n\n private getMajorVersion(version: string): number {\n return parseInt(version.split('.')[0]) || 0;\n }\n\n /**\n * Main installation method - detects framework and auto-installs\n */\n async install(): Promise<InstallationResult> {\n try {\n // Step 1: Detect framework\n this.framework = await this.detectFramework();\n \n // Step 2: Plan and optionally install package\n const installPlan = await this.installPackage();\n \n // Step 3: Generate and apply code modifications\n const modifications = await this.generateModifications();\n if (!this.options.dryRun) {\n await this.applyModifications(modifications);\n }\n \n // Step 4: Generate next steps\n const nextSteps = this.generateNextSteps();\n \n return {\n success: true,\n framework: this.framework,\n modifications,\n errors: [],\n nextSteps,\n dryRun: this.options.dryRun,\n installPlan,\n agentPlan: this.options.agentPlan\n };\n } catch (error) {\n return {\n success: false,\n framework: this.framework || { name: 'unknown', type: 'vanilla' },\n modifications: [],\n errors: [error instanceof Error ? error.message : 'Unknown error'],\n nextSteps: [],\n dryRun: this.options.dryRun,\n agentPlan: this.options.agentPlan\n };\n }\n }\n\n /**\n * Detect the current framework and project setup\n */\n public async detectFramework(): Promise<FrameworkInfo> {\n const packageJsonPath = path.join(this.projectRoot, 'package.json');\n \n if (!fs.existsSync(packageJsonPath)) {\n return {\n name: 'vanilla',\n type: 'vanilla',\n projectRoot: this.projectRoot\n };\n }\n\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));\n const dependencies = {\n ...packageJson.dependencies,\n ...packageJson.devDependencies\n };\n\n // Detect framework with version information\n let framework: FrameworkInfo = {\n name: 'vanilla',\n type: 'vanilla',\n projectRoot: this.projectRoot,\n features: {}\n };\n\n if (dependencies.nuxt) {\n const nuxtVersion = dependencies.nuxt;\n const isNuxt3 = this.isVersionGte(nuxtVersion, '3.0.0');\n \n framework = {\n name: 'nuxt',\n type: 'nuxt',\n version: nuxtVersion,\n majorVersion: this.getMajorVersion(nuxtVersion),\n hasTypeScript: !!dependencies.typescript,\n hasRouter: true,\n projectRoot: this.projectRoot,\n features: {\n hasNuxt3: isNuxt3\n }\n };\n } else if (dependencies.next) {\n const nextVersion = dependencies.next;\n const isNext13 = this.isVersionGte(nextVersion, '13.0.0');\n \n framework = {\n name: 'nextjs',\n type: 'nextjs',\n version: nextVersion,\n majorVersion: this.getMajorVersion(nextVersion),\n hasTypeScript: !!dependencies.typescript || !!dependencies['@types/node'],\n hasRouter: true,\n projectRoot: this.projectRoot,\n features: {\n hasNextAppRouter: isNext13\n }\n };\n } else if (dependencies['@remix-run/react'] || dependencies['@remix-run/dev']) {\n const remixVersion = dependencies['@remix-run/react'] || dependencies['@remix-run/dev'];\n framework = {\n name: 'remix',\n type: 'remix',\n version: remixVersion,\n majorVersion: this.getMajorVersion(remixVersion),\n hasTypeScript: !!dependencies.typescript || !!dependencies['@types/react'],\n hasRouter: true,\n projectRoot: this.projectRoot,\n features: {}\n };\n } else if (dependencies.react) {\n const reactVersion = dependencies.react;\n const isReact18 = this.isVersionGte(reactVersion, '18.0.0');\n \n framework = {\n name: 'react',\n type: 'react',\n version: reactVersion,\n majorVersion: this.getMajorVersion(reactVersion),\n hasTypeScript: !!dependencies.typescript || !!dependencies['@types/react'],\n hasRouter: !!dependencies['react-router-dom'] || !!dependencies['react-router'],\n projectRoot: this.projectRoot,\n features: {\n hasReact18: isReact18\n }\n };\n } else if (dependencies.vue) {\n const vueVersion = dependencies.vue;\n const isVue3 = this.isVersionGte(vueVersion, '3.0.0');\n \n framework = {\n name: 'vue',\n type: 'vue',\n version: vueVersion,\n majorVersion: this.getMajorVersion(vueVersion),\n hasTypeScript: !!dependencies.typescript || !!dependencies['@vue/cli-service'],\n hasRouter: !!dependencies['vue-router'],\n projectRoot: this.projectRoot,\n features: {\n hasVue3: isVue3\n }\n };\n } else if (dependencies['@angular/core']) {\n const angularVersion = dependencies['@angular/core'];\n const isAngular17 = this.isVersionGte(angularVersion, '17.0.0');\n \n framework = {\n name: 'angular',\n type: 'angular',\n version: angularVersion,\n majorVersion: this.getMajorVersion(angularVersion),\n hasTypeScript: true,\n hasRouter: true,\n projectRoot: this.projectRoot,\n features: {\n hasAngularStandalone: isAngular17\n }\n };\n } else if (dependencies.svelte) {\n const svelteVersion = dependencies.svelte;\n const isSvelteKit = !!dependencies['@sveltejs/kit'];\n \n framework = {\n name: 'svelte',\n type: 'svelte',\n version: svelteVersion,\n majorVersion: this.getMajorVersion(svelteVersion),\n hasTypeScript: !!dependencies.typescript || !!dependencies['svelte-check'],\n hasRouter: !!dependencies['svelte-routing'] || !!dependencies['@sveltejs/kit'],\n projectRoot: this.projectRoot,\n features: {\n hasSvelteKit: isSvelteKit\n }\n };\n } else if (dependencies.astro) {\n const astroVersion = dependencies.astro;\n framework = {\n name: 'astro',\n type: 'astro',\n version: astroVersion,\n majorVersion: this.getMajorVersion(astroVersion),\n hasTypeScript: !!dependencies.typescript || !!dependencies['@astrojs/ts-plugin'],\n hasRouter: true,\n projectRoot: this.projectRoot,\n features: {}\n };\n } else if (dependencies.gatsby) {\n const gatsbyVersion = dependencies.gatsby;\n framework = {\n name: 'gatsby',\n type: 'gatsby',\n version: gatsbyVersion,\n majorVersion: this.getMajorVersion(gatsbyVersion),\n hasTypeScript: !!dependencies.typescript || !!dependencies['@types/react'],\n hasRouter: true,\n projectRoot: this.projectRoot,\n features: {}\n };\n }\n\n // Detect bundler\n if (dependencies.vite) {\n framework.bundler = 'vite';\n } else if (dependencies.webpack) {\n framework.bundler = 'webpack';\n } else if (dependencies.esbuild) {\n framework.bundler = 'esbuild';\n } else if (dependencies.rollup) {\n framework.bundler = 'rollup';\n }\n\n framework.packageManager = this.detectPackageManager(this.projectRoot);\n\n return framework;\n }\n\n /**\n * Install the SDK package with latest version range\n */\n protected async installPackage(): Promise<PackageInstallPlan> {\n const plan = this.planPackageInstall();\n\n if (!plan.shouldInstall || this.options.skipInstall || this.options.dryRun) {\n return plan;\n }\n\n try {\n execSync(plan.command, { cwd: plan.cwd, stdio: 'inherit' });\n } catch (error) {\n throw new Error(`Failed to install humanbehavior-js: ${error}`);\n }\n\n return plan;\n }\n\n public planPackageInstall(): PackageInstallPlan {\n const packageManager = this.framework?.packageManager || this.detectPackageManager(this.projectRoot);\n const workspaceRoot = this.findWorkspaceRoot(this.projectRoot);\n const packageJson = this.readPackageJson(this.projectRoot);\n const packageName = packageJson?.name;\n const installedVersion = this.getInstalledSDKVersion(packageJson);\n const alreadyInstalled = installedVersion !== undefined;\n const versionStatus = this.getSDKVersionStatus(installedVersion);\n const isWorkspace = workspaceRoot !== this.projectRoot;\n const targetRef = packageName || path.relative(workspaceRoot, this.projectRoot);\n const sdkPackage = 'humanbehavior-js@latest';\n const shouldInstall =\n !alreadyInstalled ||\n (versionStatus === 'stale' && this.options.upgrade === true);\n const command = this.buildInstallCommand(packageManager, sdkPackage, {\n isWorkspace,\n targetRef\n });\n\n return {\n packageName: 'humanbehavior-js',\n packageManager,\n command,\n cwd: isWorkspace ? workspaceRoot : this.projectRoot,\n targetPackagePath: this.projectRoot,\n workspaceRoot,\n isWorkspace,\n alreadyInstalled,\n installedVersion,\n minimumSupportedVersion: MIN_SUPPORTED_SDK_VERSION,\n testedVersion: TESTED_SDK_VERSION,\n versionStatus,\n shouldInstall,\n reason: this.getInstallPlanReason({\n alreadyInstalled,\n installedVersion,\n versionStatus,\n shouldInstall,\n isWorkspace,\n targetRef\n })\n };\n }\n\n private getInstallPlanReason(options: {\n alreadyInstalled: boolean;\n installedVersion?: string;\n versionStatus: PackageInstallPlan['versionStatus'];\n shouldInstall: boolean;\n isWorkspace: boolean;\n targetRef: string;\n }): string {\n if (options.alreadyInstalled) {\n switch (options.versionStatus) {\n case 'compatible':\n return `humanbehavior-js is already compatible (${options.installedVersion})`;\n case 'stale':\n return options.shouldInstall\n ? `humanbehavior-js ${options.installedVersion} is below ${MIN_SUPPORTED_SDK_VERSION}; upgrade requested`\n : `humanbehavior-js ${options.installedVersion} is below ${MIN_SUPPORTED_SDK_VERSION}; rerun with --upgrade to update`;\n case 'newer':\n return `humanbehavior-js ${options.installedVersion} is newer than tested ${TESTED_SDK_VERSION}; keeping existing version`;\n case 'unknown':\n return `humanbehavior-js is already declared with a non-semver range (${options.installedVersion}); keeping existing version`;\n }\n }\n\n return options.isWorkspace\n ? `Install scoped to workspace package ${options.targetRef}`\n : 'Install in selected project package';\n }\n\n private buildInstallCommand(\n packageManager: PackageInstallPlan['packageManager'],\n sdkPackage: string,\n options: { isWorkspace: boolean; targetRef: string }\n ): string {\n if (options.isWorkspace) {\n switch (packageManager) {\n case 'pnpm':\n return `pnpm --filter ${this.shellQuote(options.targetRef)} add ${sdkPackage}`;\n case 'yarn':\n return `yarn workspace ${this.shellQuote(options.targetRef)} add ${sdkPackage}`;\n case 'bun':\n return `bun add ${sdkPackage} --cwd ${this.shellQuote(options.targetRef)}`;\n case 'npm':\n default:\n return `npm install ${sdkPackage} --workspace ${this.shellQuote(options.targetRef)} --legacy-peer-deps`;\n }\n }\n\n switch (packageManager) {\n case 'pnpm':\n return `pnpm add ${sdkPackage}`;\n case 'yarn':\n return `yarn add ${sdkPackage}`;\n case 'bun':\n return `bun add ${sdkPackage}`;\n case 'npm':\n default:\n return `npm install ${sdkPackage} --legacy-peer-deps`;\n }\n }\n\n private detectPackageManager(startDir: string): PackageInstallPlan['packageManager'] {\n const root = this.findWorkspaceRoot(startDir);\n const lockfileChecks: Array<[string, PackageInstallPlan['packageManager']]> = [\n ['pnpm-lock.yaml', 'pnpm'],\n ['yarn.lock', 'yarn'],\n ['bun.lockb', 'bun'],\n ['bun.lock', 'bun'],\n ['package-lock.json', 'npm'],\n ['npm-shrinkwrap.json', 'npm']\n ];\n\n for (const dir of [startDir, root]) {\n for (const [lockfile, packageManager] of lockfileChecks) {\n if (fs.existsSync(path.join(dir, lockfile))) {\n return packageManager;\n }\n }\n }\n\n const packageJson = this.readPackageJson(root) || this.readPackageJson(startDir);\n const packageManager = packageJson?.packageManager;\n if (typeof packageManager === 'string') {\n if (packageManager.startsWith('pnpm@')) return 'pnpm';\n if (packageManager.startsWith('yarn@')) return 'yarn';\n if (packageManager.startsWith('bun@')) return 'bun';\n if (packageManager.startsWith('npm@')) return 'npm';\n }\n\n return 'npm';\n }\n\n private findWorkspaceRoot(startDir: string): string {\n let current = path.resolve(startDir);\n let bestRoot = current;\n\n while (true) {\n const packageJson = this.readPackageJson(current);\n const hasWorkspacePackageJson =\n !!packageJson &&\n (Array.isArray(packageJson.workspaces) ||\n (packageJson.workspaces && Array.isArray(packageJson.workspaces.packages)));\n const hasPnpmWorkspace = fs.existsSync(path.join(current, 'pnpm-workspace.yaml'));\n\n if (hasWorkspacePackageJson || hasPnpmWorkspace) {\n bestRoot = current;\n }\n\n const parent = path.dirname(current);\n if (parent === current) break;\n current = parent;\n }\n\n return bestRoot;\n }\n\n private readPackageJson(dir: string): any | null {\n const packageJsonPath = path.join(dir, 'package.json');\n if (!fs.existsSync(packageJsonPath)) return null;\n\n try {\n return JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));\n } catch {\n return null;\n }\n }\n\n private getInstalledSDKVersion(packageJson: any | null): string | undefined {\n if (!packageJson) return undefined;\n\n const dependencyFields = [\n 'dependencies',\n 'devDependencies',\n 'peerDependencies',\n 'optionalDependencies'\n ];\n\n for (const field of dependencyFields) {\n const version = packageJson[field]?.['humanbehavior-js'];\n if (typeof version === 'string') {\n return version;\n }\n }\n\n return undefined;\n }\n\n private getSDKVersionStatus(installedVersion?: string): PackageInstallPlan['versionStatus'] {\n if (!installedVersion) return 'not-installed';\n\n const normalized = this.extractSemver(installedVersion);\n if (!normalized) return 'unknown';\n\n if (this.compareVersions(normalized, MIN_SUPPORTED_SDK_VERSION) < 0) {\n return 'stale';\n }\n\n if (this.compareVersions(normalized, TESTED_SDK_VERSION) > 0) {\n return 'newer';\n }\n\n return 'compatible';\n }\n\n private extractSemver(versionRange: string): string | null {\n const match = versionRange.match(/\\d+\\.\\d+\\.\\d+/);\n return match ? match[0] : null;\n }\n\n private shellQuote(value: string): string {\n if (/^[A-Za-z0-9_@./:-]+$/.test(value)) {\n return value;\n }\n\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n }\n\n /**\n * Generate code modifications based on framework\n */\n protected async generateModifications(): Promise<CodeModification[]> {\n const modifications: CodeModification[] = [];\n\n switch (this.framework?.type) {\n case 'react':\n modifications.push(...await this.generateReactModifications());\n break;\n case 'nextjs':\n modifications.push(...await this.generateNextJSModifications());\n break;\n case 'nuxt':\n modifications.push(...await this.generateNuxtModifications());\n break;\n case 'astro':\n modifications.push(...await this.generateAstroModifications());\n break;\n case 'gatsby':\n modifications.push(...await this.generateGatsbyModifications());\n break;\n case 'remix':\n modifications.push(...await this.generateRemixModifications());\n break;\n case 'vue':\n modifications.push(...await this.generateVueModifications());\n break;\n case 'angular':\n modifications.push(...await this.generateAngularModifications());\n break;\n case 'svelte':\n modifications.push(...await this.generateSvelteModifications());\n break;\n default:\n modifications.push(...await this.generateVanillaModifications());\n }\n\n return modifications;\n }\n\n /**\n * Generate React-specific modifications\n */\n private async generateReactModifications(): Promise<CodeModification[]> {\n const modifications: CodeModification[] = [];\n \n // Find main App component or index file\n const appFile = this.findReactAppFile();\n if (appFile) {\n const content = fs.readFileSync(appFile, 'utf8');\n const modifiedContent = this.injectReactProvider(content, appFile);\n \n modifications.push({\n filePath: appFile,\n action: 'modify',\n content: modifiedContent,\n description: 'Added HumanBehaviorProvider to React app'\n });\n }\n\n // Create or append to environment file\n modifications.push(this.createEnvironmentModification(this.framework!));\n\n return modifications;\n }\n\n /**\n * Helper: Merge HBProvider into existing providers.tsx file\n */\n private mergeProvidersFile(filePath: string): string {\n const hbProviderContent = `export function HBProvider({ children }: { children: React.ReactNode }) {\n return (\n <HumanBehaviorProvider apiKey={process.env.NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY}>\n {children}\n </HumanBehaviorProvider>\n );\n}`;\n\n if (!fs.existsSync(filePath)) {\n // File doesn't exist, create new file\n return `'use client';\n\nimport { HumanBehaviorProvider } from 'humanbehavior-js/react';\n\n${hbProviderContent}`;\n }\n\n // File exists, read and merge\n const existingContent = fs.readFileSync(filePath, 'utf8');\n \n // Check if HBProvider already exists\n if (existingContent.includes('export function HBProvider') || existingContent.includes('export const HBProvider')) {\n // Already exists, return unchanged\n return existingContent;\n }\n\n // Check if HumanBehaviorProvider import exists\n let modifiedContent = existingContent;\n if (!existingContent.includes(\"from 'humanbehavior-js/react'\")) {\n // Add the import - try to add after 'use client' or at the top\n if (existingContent.includes(\"'use client'\")) {\n modifiedContent = existingContent.replace(\n /('use client';?)\\s*\\n/,\n `$1\\n\\nimport { HumanBehaviorProvider } from 'humanbehavior-js/react';\\n`\n );\n } else {\n // Add at the top\n modifiedContent = `import { HumanBehaviorProvider } from 'humanbehavior-js/react';\\n\\n${existingContent}`;\n }\n }\n\n // Add HBProvider export at the end\n // Ensure there's proper spacing before adding the export\n const trimmed = modifiedContent.trimEnd();\n if (trimmed === '') {\n // File is empty (after trimming trailing whitespace)\n modifiedContent = hbProviderContent;\n } else {\n // Add double newline for separation\n modifiedContent = `${trimmed}\\n\\n${hbProviderContent}`;\n }\n\n return modifiedContent;\n }\n\n /**\n * Generate Next.js-specific modifications\n */\n private async generateNextJSModifications(): Promise<CodeModification[]> {\n const modifications: CodeModification[] = [];\n \n // Check for App Router - try both with and without src directory\n const appLayoutFileWithSrc = path.join(this.projectRoot, 'src', 'app', 'layout.tsx');\n const appLayoutFile = path.join(this.projectRoot, 'app', 'layout.tsx');\n const pagesLayoutFileWithSrc = path.join(this.projectRoot, 'src', 'pages', '_app.tsx');\n const pagesLayoutFile = path.join(this.projectRoot, 'pages', '_app.tsx');\n \n // Determine which layout file exists and set paths accordingly\n let actualAppLayoutFile: string | null = null;\n let providersFilePath: string | null = null;\n let providersImportPath: string | null = null;\n \n if (fs.existsSync(appLayoutFileWithSrc)) {\n actualAppLayoutFile = appLayoutFileWithSrc;\n providersFilePath = path.join(this.projectRoot, 'src', 'app', 'providers.tsx');\n providersImportPath = '@/app/providers';\n } else if (fs.existsSync(appLayoutFile)) {\n actualAppLayoutFile = appLayoutFile;\n providersFilePath = path.join(this.projectRoot, 'app', 'providers.tsx');\n providersImportPath = '@/app/providers';\n }\n \n if (actualAppLayoutFile) {\n // Merge or create providers.tsx file\n const providersContent = this.mergeProvidersFile(providersFilePath!);\n const fileExists = fs.existsSync(providersFilePath!);\n \n modifications.push({\n filePath: providersFilePath!,\n action: fileExists ? 'modify' : 'create',\n content: providersContent,\n description: fileExists \n ? 'Merged HBProvider into existing providers.tsx file'\n : 'Created providers.tsx file with HBProvider for Next.js App Router'\n });\n\n // Modify layout.tsx to use the provider\n const content = fs.readFileSync(actualAppLayoutFile, 'utf8');\n const modifiedContent = this.injectNextJSAppRouter(content, providersImportPath!);\n \n modifications.push({\n filePath: actualAppLayoutFile,\n action: 'modify',\n content: modifiedContent,\n description: 'Added HumanBehavior provider wrapper to Next.js App Router layout'\n });\n } else if (fs.existsSync(pagesLayoutFileWithSrc) || fs.existsSync(pagesLayoutFile)) {\n const actualPagesLayoutFile = fs.existsSync(pagesLayoutFileWithSrc) ? pagesLayoutFileWithSrc : pagesLayoutFile;\n const providersPath = fs.existsSync(pagesLayoutFileWithSrc) \n ? path.join(this.projectRoot, 'src', 'components', 'HumanBehaviorProvider.tsx')\n : path.join(this.projectRoot, 'components', 'HumanBehaviorProvider.tsx');\n const importPath = fs.existsSync(pagesLayoutFileWithSrc) \n ? '../components/HumanBehaviorProvider'\n : './components/HumanBehaviorProvider';\n \n // Create dedicated HumanBehavior provider file for Pages Router\n modifications.push({\n filePath: providersPath,\n action: 'create',\n content: `'use client';\n\nimport { HumanBehaviorProvider } from 'humanbehavior-js/react';\n\nexport function HBProvider({ children }: { children: React.ReactNode }) {\n return (\n <HumanBehaviorProvider apiKey={process.env.NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY}>\n {children}\n </HumanBehaviorProvider>\n );\n}`,\n description: 'Created HumanBehavior provider file for Pages Router'\n });\n\n // Modify _app.tsx to use the provider\n const content = fs.readFileSync(actualPagesLayoutFile, 'utf8');\n const modifiedContent = this.injectNextJSPagesRouter(content, importPath);\n \n modifications.push({\n filePath: actualPagesLayoutFile,\n action: 'modify',\n content: modifiedContent,\n description: 'Added HumanBehavior provider wrapper to Next.js Pages Router'\n });\n }\n\n // Create or append to environment file\n modifications.push(this.createEnvironmentModification(this.framework!));\n\n return modifications;\n }\n\n /**\n * Generate Astro-specific modifications\n */\n private async generateAstroModifications(): Promise<CodeModification[]> {\n const modifications: CodeModification[] = [];\n\n // Create Astro component for HumanBehavior\n const astroComponentPath = path.join(this.projectRoot, 'src', 'components', 'HumanBehavior.astro');\n const astroComponentContent = `---\n// This component will only run on the client side\n---\n\n<script>\n import { HumanBehaviorTracker } from 'humanbehavior-js';\n const apiKey = import.meta.env.PUBLIC_HUMANBEHAVIOR_API_KEY;\n if (apiKey) {\n HumanBehaviorTracker.init(apiKey);\n }\n</script>`;\n\n modifications.push({\n filePath: astroComponentPath,\n action: 'create',\n content: astroComponentContent,\n description: 'Created Astro component for HumanBehavior SDK'\n });\n\n // Find and update layout file\n const layoutFiles = [\n path.join(this.projectRoot, 'src', 'layouts', 'Layout.astro'),\n path.join(this.projectRoot, 'src', 'layouts', 'layout.astro'),\n path.join(this.projectRoot, 'src', 'layouts', 'BaseLayout.astro')\n ];\n\n let layoutFile = null;\n for (const file of layoutFiles) {\n if (fs.existsSync(file)) {\n layoutFile = file;\n break;\n }\n }\n\n if (layoutFile) {\n const content = fs.readFileSync(layoutFile, 'utf8');\n const modifiedContent = this.injectAstroLayout(content);\n \n modifications.push({\n filePath: layoutFile,\n action: 'modify',\n content: modifiedContent,\n description: 'Added HumanBehavior component to Astro layout'\n });\n }\n\n // Add environment variable\n modifications.push(this.createEnvironmentModification(this.framework!));\n\n return modifications;\n }\n\n /**\n * Generate Nuxt-specific modifications\n */\n private async generateNuxtModifications(): Promise<CodeModification[]> {\n const modifications: CodeModification[] = [];\n \n // Create plugin file for Nuxt (in app directory)\n const pluginFile = path.join(this.projectRoot, 'app', 'plugins', 'humanbehavior.client.ts');\n modifications.push({\n filePath: pluginFile,\n action: 'create',\n content: `import { HumanBehaviorTracker } from 'humanbehavior-js';\n\nexport default defineNuxtPlugin(() => {\n const config = useRuntimeConfig();\n if (typeof window !== 'undefined') {\n const apiKey = config.public.humanBehaviorApiKey;\n if (apiKey) {\n HumanBehaviorTracker.init(apiKey);\n }\n }\n});`,\n description: 'Created Nuxt plugin for HumanBehavior SDK in app directory'\n });\n\n // Create environment configuration\n const nuxtConfigFile = path.join(this.projectRoot, 'nuxt.config.ts');\n {\n const mod = this.applyOrNotify(\n nuxtConfigFile,\n (c) => this.injectNuxtConfig(c),\n 'Added HumanBehavior runtime config to Nuxt config',\n 'Nuxt: Add inside defineNuxtConfig({ … }):\\nruntimeConfig: { public: { humanBehaviorApiKey: process.env.NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY } },'\n );\n if (mod) modifications.push(mod);\n }\n\n // Create or append to environment file\n modifications.push(this.createEnvironmentModification(this.framework!));\n\n return modifications;\n }\n\n /**\n * Generate Remix-specific modifications\n */\n private async generateRemixModifications(): Promise<CodeModification[]> {\n const modifications: CodeModification[] = [];\n \n // Find root.tsx file\n const rootFile = path.join(this.projectRoot, 'app', 'root.tsx');\n if (fs.existsSync(rootFile)) {\n const content = fs.readFileSync(rootFile, 'utf8');\n const modifiedContent = this.injectRemixProvider(content);\n \n modifications.push({\n filePath: rootFile,\n action: 'modify',\n content: modifiedContent,\n description: 'Added HumanBehaviorProvider to Remix root component'\n });\n }\n\n // Create or append to environment file\n modifications.push(this.createEnvironmentModification(this.framework!));\n\n return modifications;\n }\n\n /**\n * Generate Vue-specific modifications\n */\n private async generateVueModifications(): Promise<CodeModification[]> {\n const modifications: CodeModification[] = [];\n \n // Find main.js or main.ts\n const mainFile = this.findVueMainFile();\n // Create Vue composable per docs (idempotent)\n const composableDir = path.join(this.projectRoot, 'src', 'composables');\n const composablePath = path.join(composableDir, 'useHumanBehavior.ts');\n const composableContent = `import { HumanBehaviorTracker } from 'humanbehavior-js'\n\nexport function useHumanBehavior() {\n const apiKey = import.meta.env.VITE_HUMANBEHAVIOR_API_KEY\n \n if (apiKey) {\n const tracker = HumanBehaviorTracker.init(apiKey);\n \n return { tracker }\n }\n \n return { tracker: null }\n}\n`;\n if (!fs.existsSync(composablePath)) {\n modifications.push({\n filePath: composablePath,\n action: 'create',\n content: composableContent,\n description: 'Created Vue composable useHumanBehavior'\n });\n }\n if (mainFile) {\n const content = fs.readFileSync(mainFile, 'utf8');\n const modifiedContent = this.injectVuePlugin(content);\n \n modifications.push({\n filePath: mainFile,\n action: 'modify',\n content: modifiedContent,\n description: 'Added HumanBehaviorPlugin to Vue app'\n });\n }\n\n // Create or append to environment file\n modifications.push(this.createEnvironmentModification(this.framework!));\n\n return modifications;\n }\n\n /**\n * Generate Angular-specific modifications\n */\n private async generateAngularModifications(): Promise<CodeModification[]> {\n const modifications: CodeModification[] = [];\n \n // Create Angular service (docs pattern)\n const serviceDir = path.join(this.projectRoot, 'src', 'app', 'services');\n const servicePath = path.join(serviceDir, 'hb.service.ts');\n const serviceContent = `import { Injectable, NgZone, Inject, PLATFORM_ID } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\nimport { HumanBehaviorTracker } from 'humanbehavior-js';\nimport { environment } from '../../environments/environment';\n\n@Injectable({ providedIn: 'root' })\nexport class HumanBehavior {\n private tracker: ReturnType<typeof HumanBehaviorTracker.init> | null = null;\n\n constructor(private ngZone: NgZone, @Inject(PLATFORM_ID) private platformId: Object) {\n if (isPlatformBrowser(this.platformId)) {\n this.ngZone.runOutsideAngular(() => {\n this.tracker = HumanBehaviorTracker.init(environment.humanBehaviorApiKey);\n });\n }\n }\n\n capture(event: string, props?: Record<string, any>) {\n this.tracker?.customEvent(event, props);\n }\n\n identify(user: Record<string, any>) {\n this.tracker?.identifyUser({ userProperties: user });\n }\n\n trackPageView(path?: string) {\n this.tracker?.trackPageView(path);\n }\n}\n`;\n\n if (!fs.existsSync(servicePath)) {\n modifications.push({\n filePath: servicePath,\n action: 'create',\n content: serviceContent,\n description: 'Created Angular HumanBehavior service (singleton)'\n });\n }\n\n // Handle Angular environment files (proper Angular way)\n const envFile = path.join(this.projectRoot, 'src', 'environments', 'environment.ts');\n const envProdFile = path.join(this.projectRoot, 'src', 'environments', 'environment.prod.ts');\n \n // Create or update development environment\n if (fs.existsSync(envFile)) {\n const content = fs.readFileSync(envFile, 'utf8');\n if (!content.includes('humanBehaviorApiKey')) {\n const modifiedContent = content.replace(\n /export const environment = {([\\s\\S]*?)};/,\n `export const environment = {\n $1,\n humanBehaviorApiKey: '${this.apiKey}'\n};`\n );\n modifications.push({\n filePath: envFile,\n action: 'modify',\n content: modifiedContent,\n description: 'Added API key to Angular development environment'\n });\n }\n } else {\n // Create new development environment file\n modifications.push({\n filePath: envFile,\n action: 'create',\n content: `export const environment = {\n production: false,\n humanBehaviorApiKey: '${this.apiKey}'\n};`,\n description: 'Created Angular development environment file'\n });\n }\n \n // Create or update production environment\n if (fs.existsSync(envProdFile)) {\n const content = fs.readFileSync(envProdFile, 'utf8');\n if (!content.includes('humanBehaviorApiKey')) {\n const modifiedContent = content.replace(\n /export const environment = {([\\s\\S]*?)};/,\n `export const environment = {\n $1,\n humanBehaviorApiKey: '${this.apiKey}'\n};`\n );\n modifications.push({\n filePath: envProdFile,\n action: 'modify',\n content: modifiedContent,\n description: 'Added API key to Angular production environment'\n });\n }\n } else {\n // Create new production environment file\n modifications.push({\n filePath: envProdFile,\n action: 'create',\n content: `export const environment = {\n production: true,\n humanBehaviorApiKey: '${this.apiKey}'\n};`,\n description: 'Created Angular production environment file'\n });\n }\n\n // For Angular, we don't need .env files since we use environment.ts\n // The environment files are already created above\n\n // Inject service into app component\n const appComponentPath = path.join(this.projectRoot, 'src', 'app', 'app.ts');\n if (fs.existsSync(appComponentPath)) {\n const appContent = fs.readFileSync(appComponentPath, 'utf8');\n \n // Check if already has HumanBehavior service\n if (!appContent.includes('HumanBehavior')) {\n let modifiedAppContent = appContent\n .replace(\n /import { Component } from '@angular\\/core';/,\n `import { Component } from '@angular/core';\nimport { HumanBehavior } from './services/hb.service';`\n )\n .replace(\n /export class App {/,\n `export class App {\n constructor(private readonly humanBehavior: HumanBehavior) {}`\n );\n \n // Do not modify standalone setting; leave component decorator unchanged\n \n modifications.push({\n action: 'modify',\n filePath: appComponentPath,\n content: modifiedAppContent,\n description: 'Injected HumanBehavior service into Angular app component'\n });\n }\n }\n\n return modifications;\n }\n\n /**\n * Generate Svelte-specific modifications\n */\n private async generateSvelteModifications(): Promise<CodeModification[]> {\n const modifications: CodeModification[] = [];\n \n // Check for SvelteKit\n const svelteConfigFile = path.join(this.projectRoot, 'svelte.config.js');\n const isSvelteKit = fs.existsSync(svelteConfigFile);\n \n if (isSvelteKit) {\n // SvelteKit - create layout file\n const layoutFile = path.join(this.projectRoot, 'src', 'routes', '+layout.svelte');\n if (fs.existsSync(layoutFile)) {\n const content = fs.readFileSync(layoutFile, 'utf8');\n const modifiedContent = this.injectSvelteKitLayout(content);\n \n modifications.push({\n filePath: layoutFile,\n action: 'modify',\n content: modifiedContent,\n description: 'Added HumanBehavior tracker init to SvelteKit layout'\n });\n }\n } else {\n // Regular Svelte - modify main file\n const mainFile = this.findSvelteMainFile();\n if (mainFile) {\n const content = fs.readFileSync(mainFile, 'utf8');\n const modifiedContent = this.injectSvelteStore(content);\n \n modifications.push({\n filePath: mainFile,\n action: 'modify',\n content: modifiedContent,\n description: 'Added HumanBehavior tracker init to Svelte app'\n });\n }\n }\n\n // Create or append to environment file\n modifications.push(this.createEnvironmentModification(this.framework!));\n\n return modifications;\n }\n\n /**\n * Generate vanilla JS/TS modifications\n */\n private async generateVanillaModifications(): Promise<CodeModification[]> {\n const modifications: CodeModification[] = [];\n \n // Find HTML file to inject script\n const htmlFile = this.findHTMLFile();\n if (htmlFile) {\n const content = fs.readFileSync(htmlFile, 'utf8');\n const modifiedContent = this.injectVanillaScript(content);\n \n modifications.push({\n filePath: htmlFile,\n action: 'modify',\n content: modifiedContent,\n description: 'Added HumanBehavior CDN script to HTML file'\n });\n }\n\n // Create or append to environment file\n modifications.push(this.createEnvironmentModification(this.framework!));\n\n return modifications;\n }\n\n /**\n * Generate Gatsby-specific modifications\n */\n private async generateGatsbyModifications(): Promise<CodeModification[]> {\n const modifications: CodeModification[] = [];\n \n // Modify or create gatsby-browser.js for Gatsby\n const gatsbyBrowserFile = path.join(this.projectRoot, 'gatsby-browser.js');\n \n if (fs.existsSync(gatsbyBrowserFile)) {\n const content = fs.readFileSync(gatsbyBrowserFile, 'utf8');\n const modifiedContent = this.injectGatsbyBrowser(content);\n \n modifications.push({\n filePath: gatsbyBrowserFile,\n action: 'modify',\n content: modifiedContent,\n description: 'Added HumanBehavior initialization to Gatsby browser'\n });\n } else {\n // Create gatsby-browser.js if it doesn't exist\n modifications.push({\n filePath: gatsbyBrowserFile,\n action: 'create',\n content: `import { HumanBehaviorTracker } from 'humanbehavior-js';\n\nexport const onClientEntry = () => {\n const apiKey = process.env.GATSBY_HUMANBEHAVIOR_API_KEY;\n if (apiKey) {\n HumanBehaviorTracker.init(apiKey);\n }\n};`,\n description: 'Created gatsby-browser.js with HumanBehavior initialization'\n });\n }\n\n // Create or append to environment file\n modifications.push(this.createEnvironmentModification(this.framework!));\n\n return modifications;\n }\n\n\n\n /**\n * Apply modifications to the codebase\n */\n protected async applyModifications(modifications: CodeModification[]): Promise<void> {\n const snapshots = modifications.map((modification) => ({\n filePath: modification.filePath,\n existed: fs.existsSync(modification.filePath),\n content: fs.existsSync(modification.filePath)\n ? fs.readFileSync(modification.filePath, 'utf8')\n : null\n }));\n\n try {\n for (const modification of modifications) {\n const dir = path.dirname(modification.filePath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n\n switch (modification.action) {\n case 'create':\n fs.writeFileSync(modification.filePath, modification.content);\n break;\n case 'modify':\n fs.writeFileSync(modification.filePath, modification.content);\n break;\n case 'append':\n fs.appendFileSync(modification.filePath, '\\n' + modification.content);\n break;\n }\n }\n } catch (error) {\n this.rollbackModifications(snapshots);\n throw new Error(`Failed to apply modifications; rolled back file changes: ${error}`);\n }\n }\n\n private rollbackModifications(snapshots: Array<{ filePath: string; existed: boolean; content: string | null }>): void {\n for (const snapshot of snapshots.reverse()) {\n try {\n if (snapshot.existed && snapshot.content !== null) {\n fs.writeFileSync(snapshot.filePath, snapshot.content);\n } else if (!snapshot.existed && fs.existsSync(snapshot.filePath)) {\n fs.rmSync(snapshot.filePath, { force: true });\n }\n } catch {\n // Best-effort rollback. The original apply error is more actionable.\n }\n }\n }\n\n /**\n * Generate next steps for the user\n */\n private generateNextSteps(): string[] {\n if (this.options.dryRun) {\n return [\n 'Dry run complete. No packages were installed and no files were changed.',\n 'Review the planned install command and file modifications.',\n 'Run again without --dry-run to apply these changes.'\n ];\n }\n\n const steps = [\n '✅ SDK installed and configured automatically!',\n '🚀 Your app is now tracking user behavior',\n '📊 View sessions in your HumanBehavior dashboard',\n '🔧 Customize tracking in your code as needed'\n ];\n\n if (this.framework?.type === 'react' || this.framework?.type === 'nextjs') {\n steps.push('💡 Use the useHumanBehavior() hook to track custom events');\n }\n\n // Append any manual notes gathered during transformation\n if (this.manualNotes.length) {\n steps.push(...this.manualNotes.map((n) => `⚠️ ${n}`));\n }\n\n return steps;\n }\n\n /**\n * Helper: apply a file transform or record a manual instruction if unchanged/missing\n */\n private applyOrNotify(\n filePath: string,\n transform: (content: string) => string,\n description: string,\n manualNote: string\n ): CodeModification | null {\n if (!fs.existsSync(filePath)) {\n this.manualNotes.push(`${manualNote} (file missing: ${path.relative(this.projectRoot, filePath)})`);\n return null;\n }\n const original = fs.readFileSync(filePath, 'utf8');\n const updated = transform(original);\n if (updated !== original) {\n return {\n filePath,\n action: 'modify',\n content: updated,\n description\n };\n }\n this.manualNotes.push(manualNote);\n return null;\n }\n\n // Helper methods for file detection and content injection\n private findReactAppFile(): string | null {\n const possibleFiles = [\n 'src/App.jsx', 'src/App.js', 'src/App.tsx', 'src/App.ts',\n 'src/index.js', 'src/index.tsx', 'src/main.js', 'src/main.tsx'\n ];\n\n for (const file of possibleFiles) {\n const fullPath = path.join(this.projectRoot, file);\n if (fs.existsSync(fullPath)) {\n return fullPath;\n }\n }\n return null;\n }\n\n private findVueMainFile(): string | null {\n const possibleFiles = [\n 'src/main.js', 'src/main.ts', 'src/main.jsx', 'src/main.tsx'\n ];\n\n for (const file of possibleFiles) {\n const fullPath = path.join(this.projectRoot, file);\n if (fs.existsSync(fullPath)) {\n return fullPath;\n }\n }\n return null;\n }\n\n private findSvelteMainFile(): string | null {\n const possibleFiles = [\n 'src/main.js', 'src/main.ts', 'src/main.svelte'\n ];\n\n for (const file of possibleFiles) {\n const fullPath = path.join(this.projectRoot, file);\n if (fs.existsSync(fullPath)) {\n return fullPath;\n }\n }\n return null;\n }\n\n private findHTMLFile(): string | null {\n const possibleFiles = ['index.html', 'public/index.html', 'dist/index.html'];\n\n for (const file of possibleFiles) {\n const fullPath = path.join(this.projectRoot, file);\n if (fs.existsSync(fullPath)) {\n return fullPath;\n }\n }\n return null;\n }\n\n private injectReactProvider(content: string, filePath: string): string {\n const isTypeScript = filePath.endsWith('.tsx') || filePath.endsWith('.ts');\n \n // Check if already has HumanBehaviorProvider\n if (content.includes('HumanBehaviorProvider')) {\n return content;\n }\n\n // Determine the correct environment variable syntax based on bundler\n const isVite = this.framework?.bundler === 'vite';\n const envVar = isVite \n ? 'import.meta.env.VITE_HUMANBEHAVIOR_API_KEY!' \n : 'process.env.REACT_APP_HUMANBEHAVIOR_API_KEY!';\n\n const importStatement = `import { HumanBehaviorProvider } from 'humanbehavior-js/react';`;\n\n // Enhanced parsing for React 18+ features\n const hasReact18 = this.framework?.features?.hasReact18;\n \n // Handle different React patterns\n if (content.includes('function App()') || content.includes('const App =')) {\n // Add import statement\n let modifiedContent = content.replace(\n /(import.*?from.*?['\"]react['\"];?)/,\n `$1\\n${importStatement}`\n );\n \n // If no React import found, add it at the top\n if (!modifiedContent.includes(importStatement)) {\n modifiedContent = `${importStatement}\\n\\n${modifiedContent}`;\n }\n \n // Wrap the App component return with HumanBehaviorProvider\n modifiedContent = modifiedContent.replace(\n /return\\s*\\(([\\s\\S]*?)\\)\\s*;/,\n `return (\n <HumanBehaviorProvider apiKey={${envVar}}>\n $1\n </HumanBehaviorProvider>\n );`\n );\n \n return modifiedContent;\n }\n \n // Handle React 18+ createRoot pattern\n if (hasReact18 && content.includes('createRoot')) {\n let modifiedContent = content.replace(\n /(import.*?from.*?['\"]react['\"];?)/,\n `$1\\n${importStatement}`\n );\n \n if (!modifiedContent.includes(importStatement)) {\n modifiedContent = `${importStatement}\\n\\n${modifiedContent}`;\n }\n \n // Wrap the root render with HumanBehaviorProvider\n modifiedContent = modifiedContent.replace(\n /(root\\.render\\s*\\([\\s\\S]*?\\)\\s*;)/,\n `root.render(\n <HumanBehaviorProvider apiKey={${envVar}}>\n $1\n </HumanBehaviorProvider>\n );`\n );\n \n return modifiedContent;\n }\n\n // Fallback: simple injection\n return `${importStatement}\\n\\n${content}`;\n }\n\n private injectNextJSAppRouter(content: string, importPath: string = '@/app/providers'): string {\n if (content.includes('HBProvider')) {\n return content;\n }\n\n const importStatement = `import { HBProvider } from '${importPath}';`;\n \n // First, add the import statement\n let modifiedContent = content.replace(\n /export default function RootLayout/,\n `${importStatement}\\n\\nexport default function RootLayout`\n );\n \n // Then wrap the body content with Providers\n // Use a more specific approach to handle the body content\n modifiedContent = modifiedContent.replace(\n /<body([^>]*)>([\\s\\S]*?)<\\/body>/,\n (match, bodyAttrs, bodyContent) => {\n // Trim whitespace and newlines from bodyContent\n const trimmedContent = bodyContent.trim();\n return `<body${bodyAttrs}>\n <HBProvider>\n ${trimmedContent}\n </HBProvider>\n </body>`;\n }\n );\n \n return modifiedContent;\n }\n\n private injectNextJSPagesRouter(content: string, importPath: string = '../components/HumanBehaviorProvider'): string {\n if (content.includes('HBProvider')) {\n return content;\n }\n\n const importStatement = `import { HBProvider } from '${importPath}';`;\n \n return content.replace(\n /function MyApp/,\n `${importStatement}\\n\\nfunction MyApp`\n ).replace(\n /return \\(([\\s\\S]*?)\\);/,\n `return (\n <HBProvider>\n $1\n </HBProvider>\n );`\n );\n }\n\n private injectRemixProvider(content: string): string {\n if (content.includes('HumanBehaviorProvider')) {\n return content;\n }\n\n let modifiedContent = content;\n \n // Step 1: Add useLoaderData import\n if (!content.includes('useLoaderData')) {\n modifiedContent = modifiedContent.replace(\n /(} from ['\"]@remix-run\\/react['\"];?\\s*)/,\n `$1import { useLoaderData } from '@remix-run/react';\n`\n );\n }\n \n // Step 2: Add HumanBehaviorProvider import\n if (!content.includes('HumanBehaviorProvider')) {\n modifiedContent = modifiedContent.replace(\n /(} from ['\"]@remix-run\\/react['\"];?\\s*)/,\n `$1import { HumanBehaviorProvider } from 'humanbehavior-js/react';\n`\n );\n }\n \n // Step 3: Add LoaderFunctionArgs import\n if (!content.includes('LoaderFunctionArgs')) {\n modifiedContent = modifiedContent.replace(\n /(} from ['\"]@remix-run\\/node['\"];?\\s*)/,\n `$1import type { LoaderFunctionArgs } from '@remix-run/node';\n`\n );\n }\n\n // Step 4: Add loader function before Layout function\n if (!content.includes('export const loader')) {\n modifiedContent = modifiedContent.replace(\n /(export function Layout)/,\n `export const loader = async ({ request }: LoaderFunctionArgs) => {\n return {\n ENV: {\n HUMANBEHAVIOR_API_KEY: process.env.HUMANBEHAVIOR_API_KEY,\n },\n };\n};\n\n$1`\n );\n }\n\n // Step 5: Add useLoaderData call and wrap App function's return content with HumanBehaviorProvider\n if (!content.includes('const data = useLoaderData')) {\n modifiedContent = modifiedContent.replace(\n /(export default function App\\(\\) \\{\\s*)(return \\(\\s*<div[^>]*>[\\s\\S]*?<\\/div>\\s*\\);\\s*\\})/,\n `$1const data = useLoaderData<typeof loader>();\n \n return (\n <HumanBehaviorProvider apiKey={data.ENV.HUMANBEHAVIOR_API_KEY}>\n <div className=\"min-h-screen bg-gray-50\">\n <Navigation />\n <Outlet />\n </div>\n </HumanBehaviorProvider>\n );\n}`\n );\n }\n\n return modifiedContent;\n }\n\n private injectVuePlugin(content: string): string {\n // New: use composable/tracker pattern per docs; idempotent and migrates from plugin\n if (content.includes('useHumanBehavior')) {\n return content;\n }\n\n const hasVue3 = this.framework?.features?.hasVue3;\n const isVue3ByContent = content.includes('createApp') || content.includes('import { createApp }');\n \n let modifiedContent = content\n .replace(/import\\s*\\{\\s*HumanBehaviorPlugin\\s*\\}\\s*from\\s*['\\\"]humanbehavior-js\\/vue['\\\"];?/g, '')\n .replace(/app\\.use\\(\\s*HumanBehaviorPlugin[\\s\\S]*?\\);?/g, '');\n\n if (hasVue3 || isVue3ByContent) {\n const importComposable = `import { useHumanBehavior } from './composables/useHumanBehavior';`;\n if (!modifiedContent.includes(importComposable)) {\n const lastImportIndex = modifiedContent.lastIndexOf('import');\n if (lastImportIndex !== -1) {\n const nextLineIndex = modifiedContent.indexOf('\\n', lastImportIndex);\n if (nextLineIndex !== -1) {\n modifiedContent = modifiedContent.slice(0, nextLineIndex + 1) + importComposable + '\\n' + modifiedContent.slice(nextLineIndex + 1);\n } else {\n modifiedContent = modifiedContent + '\\n' + importComposable;\n }\n } else {\n modifiedContent = importComposable + '\\n' + modifiedContent;\n }\n }\n if (modifiedContent.includes('createApp')) {\n modifiedContent = modifiedContent.replace(\n /(const\\s+app\\s*=\\s*createApp\\([^)]*\\))/,\n `$1\\nconst { tracker } = useHumanBehavior();`\n );\n }\n return modifiedContent;\n } else {\n const trackerImport = `import { HumanBehaviorTracker } from 'humanbehavior-js';`;\n if (!modifiedContent.includes(trackerImport)) {\n modifiedContent = `${trackerImport}\\n${modifiedContent}`;\n }\n if (modifiedContent.includes('new Vue')) {\n modifiedContent = modifiedContent.replace(\n /(new\\s+Vue\\s*\\()/,\n `HumanBehaviorTracker.init(process.env.VUE_APP_HUMANBEHAVIOR_API_KEY || import.meta?.env?.VITE_HUMANBEHAVIOR_API_KEY);\\n$1`\n );\n }\n return modifiedContent;\n }\n }\n\n private injectAngularModule(content: string): string {\n if (content.includes('HumanBehaviorModule')) {\n return content;\n }\n\n const importStatement = `import { HumanBehaviorModule } from 'humanbehavior-js/angular';`;\n const environmentImport = `import { environment } from '../environments/environment';`;\n \n // Add environment import if not present\n let modifiedContent = content;\n if (!content.includes('environment')) {\n modifiedContent = content.replace(\n /import.*from.*['\"]@angular/,\n `${environmentImport}\\n$&`\n );\n }\n \n return modifiedContent.replace(\n /imports:\\s*\\[([\\s\\S]*?)\\]/,\n `imports: [\n $1,\n HumanBehaviorModule.forRoot({\n apiKey: environment.humanBehaviorApiKey\n })\n ]`\n ).replace(\n /import.*from.*['\"]@angular/,\n `$&\\n${importStatement}`\n );\n }\n\n private injectAngularStandaloneInit(content: string): string {\n if (content.includes('initializeHumanBehavior')) {\n return content;\n }\n\n const importStatement = `import { initializeHumanBehavior } from 'humanbehavior-js/angular';`;\n const environmentImport = `import { environment } from './environments/environment';`;\n \n // Add imports at the top\n let modifiedContent = content.replace(\n /import.*from.*['\"]@angular/,\n `${importStatement}\\n${environmentImport}\\n$&`\n );\n\n // Add initialization after bootstrapApplication\n modifiedContent = modifiedContent.replace(\n /(bootstrapApplication\\([^}]+\\}?\\)(?:\\s*\\.catch[^;]+;)?)/,\n `$1\n\n// Initialize HumanBehavior SDK (client-side only)\nif (typeof window !== 'undefined') {\n const tracker = initializeHumanBehavior(environment.humanBehaviorApiKey);\n}`\n );\n\n return modifiedContent;\n }\n\n private injectSvelteStore(content: string): string {\n // Direct tracker init for non-SSR Svelte\n if (content.includes('HumanBehaviorTracker.init')) {\n return content;\n }\n const importStatement = `import { HumanBehaviorTracker } from 'humanbehavior-js';`;\n const initCode = `// Initialize HumanBehavior SDK\\nHumanBehaviorTracker.init(import.meta.env?.VITE_HUMANBEHAVIOR_API_KEY || process.env.PUBLIC_HUMANBEHAVIOR_API_KEY || '');`;\n return `${importStatement}\\n${initCode}\\n\\n${content}`;\n }\n\n private injectSvelteKitLayout(content: string): string {\n // Direct tracker init with browser guard for SvelteKit\n if (content.includes('HumanBehaviorTracker.init')) {\n return content;\n }\n const envImport = `import { PUBLIC_HUMANBEHAVIOR_API_KEY } from '$env/static/public';`;\n const hbImport = `import { HumanBehaviorTracker } from 'humanbehavior-js';`;\n const browserImport = `import { browser } from '$app/environment';`;\n const initCode = `if (browser) {\\n const apiKey = PUBLIC_HUMANBEHAVIOR_API_KEY || import.meta.env.VITE_HUMANBEHAVIOR_API_KEY;\\n if (apiKey) {\\n HumanBehaviorTracker.init(apiKey);\\n }\\n}`;\n\n if (content.includes('<script lang=\"ts\">')) {\n return content.replace(\n /<script lang=\"ts\">/,\n `<script lang=\"ts\">\\n\\t${browserImport}\\n\\t${envImport}\\n\\t${hbImport}\\n\\t${initCode}`\n );\n } else if (content.includes('<script>')) {\n return content.replace(\n /<script>/,\n `<script>\\n\\t${browserImport}\\n\\t${envImport}\\n\\t${hbImport}\\n\\t${initCode}`\n );\n } else {\n return `<script lang=\"ts\">\\n${browserImport}\\n${envImport}\\n${hbImport}\\n${initCode}\\n</script>\\n\\n${content}`;\n }\n }\n\n private injectVanillaScript(content: string): string {\n if (content.includes('humanbehavior-js')) {\n return content;\n }\n\n const cdnScript = `<script src=\"https://unpkg.com/humanbehavior-js@latest/dist/index.min.js\"></script>`;\n const initScript = `<script>\n // Initialize HumanBehavior SDK\n // Note: For vanilla HTML, the API key must be hardcoded since env vars aren't available\n const tracker = HumanBehaviorTracker.init('${this.apiKey}');\n</script>`;\n \n return content.replace(\n /<\\/head>/,\n ` ${cdnScript}\\n ${initScript}\\n</head>`\n );\n }\n\n /**\n * Inject Astro layout with HumanBehavior component\n */\n private injectAstroLayout(content: string): string {\n // Check if HumanBehavior component is already imported\n if (content.includes('HumanBehavior') || content.includes('humanbehavior-js')) {\n return content; // Already has HumanBehavior\n }\n\n // Add import inside frontmatter if not present\n let modifiedContent = content;\n if (!content.includes('import HumanBehavior')) {\n const importStatement = 'import HumanBehavior from \\'../components/HumanBehavior.astro\\';';\n const frontmatterEndIndex = content.indexOf('---', 3);\n if (frontmatterEndIndex !== -1) {\n // Insert import inside frontmatter, before the closing ---\n modifiedContent = content.slice(0, frontmatterEndIndex) + '\\n' + importStatement + '\\n' + content.slice(frontmatterEndIndex);\n } else {\n // No frontmatter, add at the very beginning\n modifiedContent = '---\\n' + importStatement + '\\n---\\n\\n' + content;\n }\n }\n\n // Find the closing </body> tag and add HumanBehavior component before it\n const bodyCloseIndex = modifiedContent.lastIndexOf('</body>');\n if (bodyCloseIndex === -1) {\n // No body tag found, append to end\n return modifiedContent + '\\n\\n<HumanBehavior />';\n }\n\n // Add component before closing body tag\n return modifiedContent.slice(0, bodyCloseIndex) + ' <HumanBehavior />\\n' + modifiedContent.slice(bodyCloseIndex);\n }\n\n private injectNuxtConfig(content: string): string {\n if (content.includes('humanBehaviorApiKey')) {\n return content;\n }\n\n // Enhanced Nuxt 3 support with version detection\n const hasNuxt3 = this.framework?.features?.hasNuxt3;\n \n if (hasNuxt3) {\n // Nuxt 3 with runtime config (robust match for opening object)\n const pattern = /export\\s+default\\s+defineNuxtConfig\\s*\\(\\s*\\{/;\n if (pattern.test(content)) {\n const replaced = content.replace(\n pattern,\n `export default defineNuxtConfig({\\n runtimeConfig: {\\n public: {\\n humanBehaviorApiKey: process.env.NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY\\n }\\n },`\n );\n if (replaced !== content) return replaced;\n }\n\n // Fallback: insert runtimeConfig after opening brace of defineNuxtConfig\n const startIdx = content.indexOf('defineNuxtConfig(');\n if (startIdx !== -1) {\n const braceIdx = content.indexOf('{', startIdx);\n if (braceIdx !== -1) {\n const insertion = `\\n runtimeConfig: {\\n public: {\\n humanBehaviorApiKey: process.env.NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY\\n }\\n },`;\n const before = content.slice(0, braceIdx + 1);\n const after = content.slice(braceIdx + 1);\n return `${before}${insertion}${after}`;\n }\n }\n return content;\n } else {\n // Nuxt 2 with env config\n return content.replace(\n /export default \\{/,\n `export default {\n env: {\n humanBehaviorApiKey: process.env.HUMANBEHAVIOR_API_KEY\n },`\n );\n }\n }\n\n private injectGatsbyLayout(content: string): string {\n if (content.includes('HumanBehavior')) {\n return content;\n }\n\n const importStatement = `import HumanBehavior from './HumanBehavior';`;\n const componentUsage = `<HumanBehavior apiKey={process.env.GATSBY_HUMANBEHAVIOR_API_KEY || ''} />`;\n\n // Add import at the top\n let modifiedContent = content.replace(\n /import.*from.*['\"]\\./,\n `${importStatement}\\n$&`\n );\n\n // Add component before closing body tag\n modifiedContent = modifiedContent.replace(\n /(\\s*<\\/body>)/,\n `\\n ${componentUsage}\\n$1`\n );\n\n return modifiedContent;\n }\n\n private injectGatsbyBrowser(content: string): string {\n const importStatement = `import { HumanBehaviorTracker } from 'humanbehavior-js';`;\n\n // If an onClientEntry already exists, merge init into it idempotently\n if (/export\\s+const\\s+onClientEntry\\s*=\\s*\\(/.test(content)) {\n let modified = content;\n\n // Ensure import exists\n if (!modified.includes(\"from 'humanbehavior-js'\")) {\n modified = `${importStatement}\\n${modified}`;\n }\n\n // If init already present, return as-is\n if (modified.includes('HumanBehaviorTracker.init(')) {\n return modified;\n }\n\n // Inject minimal init at start of onClientEntry body\n modified = modified.replace(\n /(export\\s+const\\s+onClientEntry\\s*=\\s*\\([^)]*\\)\\s*=>\\s*\\{)/,\n `$1\\n const apiKey = process.env.GATSBY_HUMANBEHAVIOR_API_KEY;\\n if (apiKey) {\\n HumanBehaviorTracker.init(apiKey);\\n }\\n`\n );\n\n return modified;\n }\n\n // No existing onClientEntry: create minimal file content or prepend to existing\n const block = `export const onClientEntry = () => {\\n const apiKey = process.env.GATSBY_HUMANBEHAVIOR_API_KEY;\\n if (apiKey) {\\n HumanBehaviorTracker.init(apiKey);\\n }\\n};`;\n\n const header = content.trim() ? `${importStatement}\\n` : `${importStatement}\\n`;\n return `${header}${block}${content.trim() ? `\\n\\n${content}` : ''}`;\n }\n\n\n\n /**\n * Helper method to find the best environment file for a framework\n */\n private findBestEnvFile(framework: FrameworkInfo): { filePath: string; envVarName: string } {\n const possibleEnvFiles = [\n '.env.local',\n '.env.development.local',\n '.env.development',\n '.env.local.development',\n '.env',\n '.env.production',\n '.env.staging'\n ];\n\n // Framework-specific environment variable names\n const getEnvVarName = (framework: FrameworkInfo) => {\n // Handle React+Vite specifically\n if (framework.type === 'react' && framework.bundler === 'vite') {\n return 'VITE_HUMANBEHAVIOR_API_KEY';\n }\n \n // Framework-specific mappings\n const envVarNames = {\n react: 'REACT_APP_HUMANBEHAVIOR_API_KEY',\n nextjs: 'NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY',\n vue: 'VITE_HUMANBEHAVIOR_API_KEY',\n svelte: 'PUBLIC_HUMANBEHAVIOR_API_KEY',\n angular: 'HUMANBEHAVIOR_API_KEY',\n nuxt: 'NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY',\n remix: 'HUMANBEHAVIOR_API_KEY',\n vanilla: 'HUMANBEHAVIOR_API_KEY',\n astro: 'PUBLIC_HUMANBEHAVIOR_API_KEY',\n gatsby: 'GATSBY_HUMANBEHAVIOR_API_KEY',\n node: 'HUMANBEHAVIOR_API_KEY',\n auto: 'HUMANBEHAVIOR_API_KEY'\n };\n \n return envVarNames[framework.type] || 'HUMANBEHAVIOR_API_KEY';\n };\n\n const envVarName = getEnvVarName(framework);\n\n // Check for existing files\n for (const envFile of possibleEnvFiles) {\n const fullPath = path.join(this.projectRoot, envFile);\n if (fs.existsSync(fullPath)) {\n return { filePath: fullPath, envVarName };\n }\n }\n\n // Framework-specific default file creation\n const defaultFiles = {\n react: '.env.local',\n nextjs: '.env.local',\n vue: '.env.local',\n svelte: '.env',\n angular: '.env',\n nuxt: '.env',\n remix: '.env.local',\n vanilla: '.env',\n astro: '.env',\n gatsby: '.env.development',\n node: '.env',\n auto: '.env'\n };\n\n const defaultFile = defaultFiles[framework.type] || '.env';\n return {\n filePath: path.join(this.projectRoot, defaultFile),\n envVarName\n };\n }\n\n /**\n * Helper method to create or append to environment files\n */\n private createEnvironmentModification(framework: FrameworkInfo): CodeModification {\n const { filePath, envVarName } = this.findBestEnvFile(framework);\n\n // Clean the API key to prevent formatting issues\n const cleanApiKey = this.apiKey.trim();\n\n if (fs.existsSync(filePath)) {\n // Check if the variable already exists\n const content = fs.readFileSync(filePath, 'utf8');\n if (content.includes(envVarName)) {\n // Variable exists, don't modify\n return {\n filePath,\n action: 'modify',\n content: content, // No change\n description: `API key already exists in ${path.basename(filePath)}`\n };\n } else {\n // Append to existing file\n return {\n filePath,\n action: 'append',\n content: `\\n${envVarName}=${cleanApiKey}`,\n description: `Added API key to existing ${path.basename(filePath)}`\n };\n }\n } else {\n // Create new file\n return {\n filePath,\n action: 'create',\n content: `${envVarName}=${cleanApiKey}`,\n description: `Created ${path.basename(filePath)} with API key`\n };\n }\n }\n}\n\n/**\n * Browser-based auto-installation wizard\n */\nexport class BrowserAutoInstallationWizard {\n private apiKey: string;\n\n constructor(apiKey: string) {\n this.apiKey = apiKey;\n }\n\n async install(): Promise<InstallationResult> {\n try {\n // Detect framework in browser\n const framework = this.detectFramework();\n \n // Generate installation instructions\n const modifications = this.generateBrowserModifications(framework);\n \n return {\n success: true,\n framework,\n modifications,\n errors: [],\n nextSteps: [\n '✅ Framework detected automatically',\n '📋 Copy the generated code to your project',\n '🚀 Your app will be ready to track user behavior'\n ]\n };\n } catch (error) {\n return {\n success: false,\n framework: { name: 'unknown', type: 'vanilla' },\n modifications: [],\n errors: [error instanceof Error ? error.message : 'Unknown error'],\n nextSteps: []\n };\n }\n }\n\n private detectFramework(): FrameworkInfo {\n if (typeof window !== 'undefined') {\n if ((window as any).React) {\n return { name: 'react', type: 'react' };\n }\n if ((window as any).Vue) {\n return { name: 'vue', type: 'vue' };\n }\n if ((window as any).angular) {\n return { name: 'angular', type: 'angular' };\n }\n }\n \n return { name: 'vanilla', type: 'vanilla' };\n }\n\n private generateBrowserModifications(framework: FrameworkInfo): CodeModification[] {\n // Return code snippets for browser environment\n const modifications: CodeModification[] = [];\n \n switch (framework.type) {\n case 'react':\n modifications.push({\n filePath: 'App.jsx',\n action: 'create',\n content: `import { HumanBehaviorProvider } from 'humanbehavior-js/react';\n\nfunction App() {\n return (\n <HumanBehaviorProvider apiKey=\"${this.apiKey}\">\n {/* Your app components */}\n </HumanBehaviorProvider>\n );\n}\n\nexport default App;`,\n description: 'React component with HumanBehaviorProvider'\n });\n break;\n \n case 'remix':\n modifications.push({\n filePath: 'app/root.tsx',\n action: 'create',\n content: `import {\n Links,\n Meta,\n Outlet,\n Scripts,\n ScrollRestoration,\n useLoaderData,\n} from \"@remix-run/react\";\nimport { HumanBehaviorProvider } from 'humanbehavior-js/react';\nimport type { LoaderFunctionArgs } from \"@remix-run/node\";\n\nexport async function loader({ request }: LoaderFunctionArgs) {\n return {\n ENV: {\n HUMANBEHAVIOR_API_KEY: process.env.HUMANBEHAVIOR_API_KEY,\n },\n };\n}\n\nexport function Layout({ children }: { children: React.ReactNode }) {\n return (\n <html lang=\"en\">\n <head>\n <meta charSet=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <Meta />\n <Links />\n </head>\n <body>\n {children}\n <ScrollRestoration />\n <Scripts />\n </body>\n </html>\n );\n}\n\nexport default function App() {\n const data = useLoaderData<typeof loader>();\n \n return (\n <HumanBehaviorProvider apiKey={data.ENV.HUMANBEHAVIOR_API_KEY}>\n <div className=\"min-h-screen bg-gray-50\">\n {/* Your app content */}\n <Outlet />\n </div>\n </HumanBehaviorProvider>\n );\n}`,\n description: 'Remix root component with HumanBehaviorProvider'\n });\n break;\n \n case 'vue':\n modifications.push({\n filePath: 'main.js',\n action: 'create',\n content: `import { createApp } from 'vue';\nimport { HumanBehaviorPlugin } from 'humanbehavior-js/vue';\nimport App from './App.vue';\n\nconst app = createApp(App);\napp.use(HumanBehaviorPlugin, {\n apiKey: '${this.apiKey}'\n});\napp.mount('#app');`,\n description: 'Vue app with HumanBehaviorPlugin'\n });\n break;\n \n default:\n modifications.push({\n filePath: 'humanbehavior-init.js',\n action: 'create',\n content: `import { HumanBehaviorTracker } from 'humanbehavior-js';\n\nconst tracker = HumanBehaviorTracker.init('${this.apiKey}');`,\n description: 'Vanilla JS initialization'\n });\n }\n \n return modifications;\n }\n} \n","/**\n * AI-Enhanced HumanBehavior SDK Auto-Installation Wizard\n * \n * This wizard uses AI to intelligently detect frameworks, analyze code patterns,\n * and generate optimal integration code that's both future-proof and backward-compatible.\n * \n * 🚀 KEY FEATURES:\n * - AI-powered framework detection beyond package.json\n * - Intelligent code pattern analysis\n * - Future-proof integration strategies\n * - Backward compatibility with legacy frameworks\n * - Adaptive code generation for new frameworks\n * - Smart conflict resolution\n * - Learning from user feedback\n * - Centralized AI service (no user API keys required)\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { AutoInstallationWizard, FrameworkInfo, CodeModification, InstallationResult, InstallationWizardOptions } from '../core/install-wizard';\n\nexport interface AICodeAnalysis {\n framework: FrameworkInfo;\n confidence: number;\n patterns: string[];\n conflicts: string[];\n recommendations: string[];\n integrationStrategy: 'provider' | 'plugin' | 'module' | 'script' | 'standalone';\n compatibilityMode: 'modern' | 'legacy' | 'hybrid';\n}\n\nexport interface AIInstallationResult extends InstallationResult {\n aiAnalysis: AICodeAnalysis;\n learningData: {\n patterns: string[];\n framework: string;\n success: boolean;\n userFeedback?: string;\n };\n}\n\n/**\n * Centralized AI Service Interface\n * This runs on your backend infrastructure, not in the user's environment\n */\ninterface CentralizedAIService {\n analyzeCodePatterns(codeSamples: string[]): Promise<AICodeAnalysis>;\n resolveConflicts(conflicts: string[], framework: FrameworkInfo): Promise<string[]>;\n generateOptimizations(framework: FrameworkInfo, patterns: string[]): Promise<string[]>;\n}\n\n/**\n * Default AI Service Implementation\n * Uses heuristic analysis when centralized service is not available\n */\nclass DefaultAIService implements CentralizedAIService {\n async analyzeCodePatterns(codeSamples: string[]): Promise<AICodeAnalysis> {\n return this.analyzeWithHeuristics(codeSamples);\n }\n\n async resolveConflicts(conflicts: string[], framework: FrameworkInfo): Promise<string[]> {\n // Default conflict resolution strategies\n const resolutions: string[] = [];\n \n for (const conflict of conflicts) {\n switch (conflict) {\n case 'existing_humanbehavior_code':\n resolutions.push('update_existing_integration');\n break;\n case 'existing_provider':\n resolutions.push('merge_providers');\n break;\n case 'module_system_conflict':\n resolutions.push('hybrid_module_support');\n break;\n default:\n resolutions.push('skip_conflict');\n }\n }\n \n return resolutions;\n }\n\n async generateOptimizations(framework: FrameworkInfo, patterns: string[]): Promise<string[]> {\n const optimizations: string[] = [];\n \n // Framework-specific optimizations\n switch (framework.type) {\n case 'react':\n optimizations.push('Use React.memo for performance optimization');\n optimizations.push('Implement error boundaries for better error tracking');\n optimizations.push('Consider using React.lazy for code splitting');\n break;\n case 'vue':\n optimizations.push('Use Vue 3 Composition API for better performance');\n optimizations.push('Implement proper error handling in components');\n optimizations.push('Consider using Vue Router for navigation tracking');\n break;\n case 'angular':\n optimizations.push('Use Angular standalone components for better tree-shaking');\n optimizations.push('Implement proper error handling with ErrorHandler');\n optimizations.push('Consider using Angular signals for state management');\n break;\n default:\n optimizations.push('Enable performance tracking');\n optimizations.push('Implement error tracking');\n optimizations.push('Consider progressive enhancement');\n }\n \n return optimizations;\n }\n\n private analyzeWithHeuristics(codeSamples: string[]): AICodeAnalysis {\n const patterns = codeSamples.join(' ').toLowerCase();\n \n // Framework detection\n let framework: FrameworkInfo = { name: 'vanilla', type: 'vanilla' };\n let confidence = 0.5;\n \n if (patterns.includes('nuxt') || patterns.includes('nuxtjs') || patterns.includes('defineNuxtConfig') || patterns.includes('nuxt.config') || patterns.includes('@nuxt/') || patterns.includes('useNuxtApp') || patterns.includes('useRuntimeConfig') || patterns.includes('useSeoMeta') || patterns.includes('useHead') || patterns.includes('useLazyFetch') || patterns.includes('useFetch') || patterns.includes('useAsyncData') || patterns.includes('#app')) {\n framework = { name: 'nuxt', type: 'nuxt' };\n confidence = 0.95;\n } else if (patterns.includes('next') || patterns.includes('nextjs') || patterns.includes('next/link') || patterns.includes('next/image') || patterns.includes('next/navigation') || patterns.includes('next/router') || patterns.includes('getserverSideProps') || patterns.includes('getstaticProps') || patterns.includes('getstaticPaths') || patterns.includes('app/layout') || patterns.includes('app/page') || patterns.includes('pages/')) {\n framework = { name: 'nextjs', type: 'nextjs' };\n confidence = 0.95;\n } else if (patterns.includes('gatsby') || patterns.includes('gatsby-browser') || patterns.includes('gatsby-ssr') || patterns.includes('gatsby-node') || patterns.includes('gatsby-config') || patterns.includes('useStaticQuery') || patterns.includes('graphql')) {\n framework = { name: 'gatsby', type: 'gatsby' };\n confidence = 0.95;\n } else if (patterns.includes('react')) {\n framework = { name: 'react', type: 'react' };\n confidence = 0.9;\n } else if (patterns.includes('vue')) {\n framework = { name: 'vue', type: 'vue' };\n confidence = 0.9;\n } else if (patterns.includes('angular')) {\n framework = { name: 'angular', type: 'angular' };\n confidence = 0.9;\n } else if (patterns.includes('svelte')) {\n framework = { name: 'svelte', type: 'svelte' };\n confidence = 0.9;\n }\n \n // Integration strategy\n let integrationStrategy: 'provider' | 'plugin' | 'module' | 'script' | 'standalone' = 'script';\n if (framework.type === 'react' || framework.type === 'nextjs' || framework.type === 'gatsby') {\n integrationStrategy = 'provider';\n } else if (framework.type === 'vue') {\n integrationStrategy = 'plugin';\n } else if (framework.type === 'angular') {\n integrationStrategy = 'module';\n }\n \n // Compatibility mode\n let compatibilityMode: 'modern' | 'legacy' | 'hybrid' = 'modern';\n if (patterns.includes('require(') || patterns.includes('var ')) {\n compatibilityMode = 'legacy';\n }\n \n return {\n framework,\n confidence,\n patterns: codeSamples,\n conflicts: [],\n recommendations: [],\n integrationStrategy,\n compatibilityMode\n };\n }\n}\n\nexport class AIEnhancedInstallationWizard extends AutoInstallationWizard {\n private aiService: CentralizedAIService;\n private learningCache: Map<string, any> = new Map();\n private patternDatabase: Map<string, any[]> = new Map();\n\n constructor(apiKey: string, projectRoot: string = process.cwd(), aiService?: CentralizedAIService, options: InstallationWizardOptions = {}) {\n super(apiKey, projectRoot, options);\n this.aiService = aiService || new DefaultAIService();\n this.loadLearningData();\n }\n\n /**\n * AI-enhanced installation with intelligent analysis\n */\n async install(): Promise<AIInstallationResult> {\n try {\n // Step 1: AI-powered framework detection\n const aiAnalysis = await this.performAICodeAnalysis();\n \n // Step 2: Smart framework detection with AI validation\n this.framework = await this.detectFrameworkWithAI(aiAnalysis);\n \n // Step 3: Generate AI-optimized modifications\n const modifications = await this.generateAIOptimizedModifications(aiAnalysis);\n \n // Step 4: Apply modifications with conflict resolution\n if (!this.options.dryRun) {\n await this.applyModificationsWithAI(modifications, aiAnalysis);\n }\n \n // Step 5: Generate intelligent next steps\n const nextSteps = this.generateAINextSteps(aiAnalysis);\n \n // Step 6: Learn from this installation\n await this.learnFromInstallation(aiAnalysis, modifications);\n \n return {\n success: true,\n framework: this.framework,\n modifications,\n errors: [],\n nextSteps,\n dryRun: this.options.dryRun,\n aiAnalysis,\n learningData: {\n patterns: aiAnalysis.patterns,\n framework: this.framework.name,\n success: true\n }\n };\n } catch (error) {\n return {\n success: false,\n framework: this.framework || { name: 'unknown', type: 'vanilla' },\n modifications: [],\n errors: [error instanceof Error ? error.message : 'Unknown error'],\n nextSteps: [],\n dryRun: this.options.dryRun,\n aiAnalysis: {\n framework: { name: 'unknown', type: 'vanilla' },\n confidence: 0,\n patterns: [],\n conflicts: [],\n recommendations: [],\n integrationStrategy: 'script',\n compatibilityMode: 'legacy'\n },\n learningData: {\n patterns: [],\n framework: 'unknown',\n success: false\n }\n };\n }\n }\n\n /**\n * AI-powered code analysis using centralized service\n */\n public async performAICodeAnalysis(): Promise<AICodeAnalysis> {\n const projectFiles = await this.scanProjectFiles();\n const codeSamples = await this.extractCodeSamples(projectFiles);\n \n // Use centralized AI service (no user API key required)\n return await this.aiService.analyzeCodePatterns(codeSamples);\n }\n\n /**\n * Scan project files for analysis\n */\n private async scanProjectFiles(): Promise<string[]> {\n const files: string[] = [];\n const scanDir = (dir: string, depth: number = 0) => {\n if (depth > 3) return; // Limit depth\n \n try {\n const items = fs.readdirSync(dir);\n for (const item of items) {\n const fullPath = path.join(dir, item);\n const stat = fs.statSync(fullPath);\n \n if (stat.isDirectory() && !item.startsWith('.') && item !== 'node_modules') {\n scanDir(fullPath, depth + 1);\n } else if (stat.isFile() && this.isRelevantFile(item)) {\n files.push(fullPath);\n }\n }\n } catch (error) {\n // Skip inaccessible directories\n }\n };\n \n scanDir(this.projectRoot);\n return files;\n }\n\n /**\n * Check if file is relevant for analysis\n */\n private isRelevantFile(filename: string): boolean {\n const relevantExtensions = [\n '.js', '.jsx', '.ts', '.tsx', '.vue', '.svelte', '.html',\n '.json', '.config.js', '.config.ts', '.babelrc', '.eslintrc'\n ];\n \n const relevantNames = [\n 'package.json', 'tsconfig.json', 'vite.config', 'webpack.config',\n 'next.config', 'nuxt.config', 'angular.json', 'svelte.config',\n 'app/layout', 'app/page', 'pages/index', 'pages/_app', 'pages/_document'\n ];\n \n return relevantExtensions.some(ext => filename.endsWith(ext)) ||\n relevantNames.some(name => filename.includes(name));\n }\n\n /**\n * Extract code samples for AI analysis\n */\n private async extractCodeSamples(files: string[]): Promise<string[]> {\n const samples: string[] = [];\n \n for (const file of files.slice(0, 20)) { // Limit to 20 files\n try {\n const content = fs.readFileSync(file, 'utf8');\n const relativePath = path.relative(this.projectRoot, file);\n \n // Extract relevant code patterns\n const patterns = this.extractCodePatterns(content);\n if (patterns.length > 0) {\n samples.push(`File: ${relativePath}\\n${patterns.join('\\n')}`);\n }\n } catch (error) {\n // Skip unreadable files\n }\n }\n \n return samples;\n }\n\n /**\n * Extract relevant code patterns\n */\n private extractCodePatterns(content: string): string[] {\n const patterns: string[] = [];\n \n // Framework-specific patterns\n const frameworkPatterns = {\n react: [\n /import\\s+React\\s+from\\s+['\"]react['\"]/gi,\n /from\\s+['\"]react['\"]/gi,\n /function\\s+\\w+\\s*\\(\\s*\\)\\s*{/gi,\n /const\\s+\\w+\\s*=\\s*\\(\\s*\\)\\s*=>\\s*{/gi\n ],\n vue: [\n /import\\s+{\\s*createApp\\s*}\\s+from\\s+['\"]vue['\"]/gi,\n /from\\s+['\"]vue['\"]/gi,\n /<template>/gi,\n /<script\\s+setup>/gi\n ],\n angular: [\n /import\\s+{\\s*Component\\s*}\\s+from\\s+['\"]@angular\\/core['\"]/gi,\n /@Component\\s*\\(\\s*{/gi,\n /from\\s+['\"]@angular/gi\n ],\n svelte: [\n /<script>/gi,\n /import\\s+.*\\s+from\\s+['\"]svelte/gi,\n /from\\s+['\"]svelte/gi\n ],\n nextjs: [\n /import\\s+.*\\s+from\\s+['\"]next/gi,\n /from\\s+['\"]next/gi,\n /export\\s+default\\s+function\\s+Page/gi,\n /export\\s+default\\s+function\\s+Layout/gi,\n /export\\s+default\\s+function\\s+Loading/gi,\n /export\\s+default\\s+function\\s+Error/gi,\n /export\\s+default\\s+function\\s+Not-found/gi,\n /useRouter\\s+from\\s+['\"]next\\/navigation['\"]/gi,\n /useRouter\\s+from\\s+['\"]next\\/router['\"]/gi,\n /Link\\s+from\\s+['\"]next\\/link['\"]/gi,\n /Image\\s+from\\s+['\"]next\\/image['\"]/gi,\n /getServerSideProps/gi,\n /getStaticProps/gi,\n /getStaticPaths/gi,\n /next\\.config/gi,\n /app\\/layout\\.tsx/gi,\n /app\\/page\\.tsx/gi,\n /pages\\/.*\\.tsx/gi,\n /pages\\/.*\\.jsx/gi,\n /pages\\/.*\\.ts/gi,\n /pages\\/.*\\.js/gi\n ],\n nuxt: [\n /import\\s+.*\\s+from\\s+['\"]nuxt/gi,\n /from\\s+['\"]nuxt/gi,\n /export\\s+default\\s+defineNuxtConfig/gi,\n /defineNuxtConfig/gi,\n /nuxt\\.config\\.ts/gi,\n /nuxt\\.config\\.js/gi,\n /@nuxt\\//gi,\n /#app/gi,\n /useNuxtApp/gi,\n /useRuntimeConfig/gi,\n /useSeoMeta/gi,\n /useHead/gi,\n /useLazyFetch/gi,\n /useFetch/gi,\n /useAsyncData/gi,\n /<NuxtLayout/gi,\n /<NuxtPage/gi,\n /NuxtLayout/gi,\n /NuxtPage/gi,\n /pages\\/.*\\.vue/gi,\n /layouts\\/.*\\.vue/gi,\n /components\\/.*\\.vue/gi,\n /composables\\/.*\\.ts/gi,\n /middleware\\/.*\\.ts/gi,\n /server\\/.*\\.ts/gi,\n /plugins\\/.*\\.ts/gi,\n /public\\//gi,\n /assets\\//gi,\n /content\\//gi\n ]\n };\n \n // Extract patterns for each framework\n for (const [framework, regexes] of Object.entries(frameworkPatterns)) {\n for (const regex of regexes) {\n const matches = content.match(regex);\n if (matches) {\n // Add raw patterns for heuristic analysis\n patterns.push(...matches.slice(0, 3));\n // Also add formatted patterns for debugging\n patterns.push(`${framework.toUpperCase()}: ${matches.slice(0, 3).join(', ')}`);\n }\n }\n }\n \n // Extract import patterns\n const importMatches = content.match(/import\\s+.*\\s+from\\s+['\"][^'\"]+['\"]/gi);\n if (importMatches) {\n patterns.push(`IMPORTS: ${importMatches.slice(0, 5).join(', ')}`);\n }\n \n // Extract export patterns\n const exportMatches = content.match(/export\\s+.*/gi);\n if (exportMatches) {\n patterns.push(`EXPORTS: ${exportMatches.slice(0, 3).join(', ')}`);\n }\n \n return patterns;\n }\n\n /**\n * AI-enhanced framework detection\n */\n private async detectFrameworkWithAI(aiAnalysis: AICodeAnalysis): Promise<FrameworkInfo> {\n // Combine AI analysis with traditional detection\n const traditionalFramework = await super.detectFramework();\n \n // Use AI analysis if confidence is high, but preserve bundler info\n if (aiAnalysis.confidence > 0.8) {\n return {\n ...aiAnalysis.framework,\n bundler: traditionalFramework.bundler, // Preserve bundler detection\n packageManager: traditionalFramework.packageManager, // Preserve package manager\n hasTypeScript: traditionalFramework.hasTypeScript, // Preserve TypeScript detection\n hasRouter: traditionalFramework.hasRouter, // Preserve router detection\n projectRoot: this.projectRoot\n };\n }\n \n // Merge AI insights with traditional detection\n return {\n ...traditionalFramework,\n // Override with AI insights if available\n ...(aiAnalysis.framework.type !== 'vanilla' && {\n type: aiAnalysis.framework.type,\n name: aiAnalysis.framework.name\n })\n };\n }\n\n /**\n * Generate AI-optimized modifications\n */\n private async generateAIOptimizedModifications(aiAnalysis: AICodeAnalysis): Promise<CodeModification[]> {\n const baseModifications = await super.generateModifications();\n \n // Enhance with AI recommendations\n const enhancedModifications = baseModifications.map(mod => {\n return this.enhanceModificationWithAI(mod, aiAnalysis);\n });\n \n // Add AI-specific optimizations\n const aiOptimizations = this.generateAIOptimizations(aiAnalysis);\n enhancedModifications.push(...aiOptimizations);\n \n return enhancedModifications;\n }\n\n /**\n * Enhance modification with AI insights\n */\n private enhanceModificationWithAI(mod: CodeModification, aiAnalysis: AICodeAnalysis): CodeModification {\n let enhancedContent = mod.content;\n \n // Add compatibility comments\n if (aiAnalysis.compatibilityMode === 'legacy') {\n enhancedContent = `// HumanBehavior SDK - Legacy Compatibility Mode\\n${enhancedContent}`;\n }\n \n // Add future-proofing comments\n if (aiAnalysis.integrationStrategy === 'provider') {\n enhancedContent = `// HumanBehavior SDK - Provider Pattern (Future-proof)\\n${enhancedContent}`;\n }\n \n // Add conflict resolution\n if (aiAnalysis.conflicts.length > 0) {\n enhancedContent = `// Conflict Resolution: ${aiAnalysis.conflicts.join(', ')}\\n${enhancedContent}`;\n }\n \n return {\n ...mod,\n content: enhancedContent,\n description: `${mod.description} (AI-optimized)`\n };\n }\n\n /**\n * Generate AI-specific optimizations\n */\n private generateAIOptimizations(aiAnalysis: AICodeAnalysis): CodeModification[] {\n const optimizations: CodeModification[] = [];\n \n // AI optimizations are now handled through environment variables and code injection\n // No separate config file needed - everything is integrated into the existing codebase\n \n return optimizations;\n }\n\n /**\n * Apply modifications with AI conflict resolution\n */\n private async applyModificationsWithAI(modifications: CodeModification[], aiAnalysis: AICodeAnalysis): Promise<void> {\n for (const modification of modifications) {\n try {\n // Check for conflicts\n const conflicts = await this.detectConflicts(modification);\n \n if (conflicts.length > 0) {\n // Resolve conflicts using centralized AI service\n const resolutions = await this.aiService.resolveConflicts(conflicts, aiAnalysis.framework);\n const resolvedModification = await this.resolveConflicts(modification, conflicts, resolutions, aiAnalysis);\n await this.applyModification(resolvedModification);\n } else {\n await this.applyModification(modification);\n }\n } catch (error) {\n throw new Error(`Failed to apply AI-optimized modification to ${modification.filePath}: ${error}`);\n }\n }\n }\n\n /**\n * Detect potential conflicts\n */\n private async detectConflicts(modification: CodeModification): Promise<string[]> {\n const conflicts: string[] = [];\n \n if (fs.existsSync(modification.filePath)) {\n const existingContent = fs.readFileSync(modification.filePath, 'utf8');\n \n // Check for existing HumanBehavior code\n if (existingContent.includes('HumanBehavior') || existingContent.includes('humanbehavior')) {\n conflicts.push('existing_humanbehavior_code');\n }\n \n // Check for conflicting providers/plugins\n if (modification.content.includes('Provider') && existingContent.includes('Provider')) {\n conflicts.push('existing_provider');\n }\n \n // Check for TypeScript conflicts\n if (modification.content.includes('import') && existingContent.includes('require(')) {\n conflicts.push('module_system_conflict');\n }\n }\n \n return conflicts;\n }\n\n /**\n * Resolve conflicts with AI\n */\n private async resolveConflicts(modification: CodeModification, conflicts: string[], resolutions: string[], aiAnalysis: AICodeAnalysis): Promise<CodeModification> {\n let resolvedContent = modification.content;\n \n for (let i = 0; i < conflicts.length; i++) {\n const conflict = conflicts[i];\n const resolution = resolutions[i];\n \n switch (resolution) {\n case 'update_existing_integration':\n resolvedContent = `// Updated HumanBehavior Integration\\n${resolvedContent}`;\n break;\n case 'merge_providers':\n resolvedContent = resolvedContent.replace(/<HumanBehaviorProvider/g, '<HumanBehaviorProvider key=\"updated\"');\n break;\n case 'hybrid_module_support':\n resolvedContent = `// Hybrid module system support\\n${resolvedContent}`;\n break;\n case 'skip_conflict':\n // Skip this modification\n return { ...modification, content: '', description: `${modification.description} (skipped due to conflict)` };\n default:\n // Default resolution\n resolvedContent = `// Conflict resolved: ${conflict}\\n${resolvedContent}`;\n }\n }\n \n return {\n ...modification,\n content: resolvedContent,\n description: `${modification.description} (conflict-resolved)`\n };\n }\n\n /**\n * Apply single modification\n */\n private async applyModification(modification: CodeModification): Promise<void> {\n if (!modification.content) return; // Skip empty modifications\n \n const dir = path.dirname(modification.filePath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n\n switch (modification.action) {\n case 'create':\n fs.writeFileSync(modification.filePath, modification.content);\n break;\n case 'modify':\n fs.writeFileSync(modification.filePath, modification.content);\n break;\n case 'append':\n fs.appendFileSync(modification.filePath, '\\n' + modification.content);\n break;\n }\n }\n\n /**\n * Generate AI-enhanced next steps\n */\n private generateAINextSteps(aiAnalysis: AICodeAnalysis): string[] {\n const steps = [\n '✅ AI-optimized SDK installation completed!',\n `🎯 Framework detected: ${aiAnalysis.framework.name} (confidence: ${Math.round(aiAnalysis.confidence * 100)}%)`,\n `🔧 Integration strategy: ${aiAnalysis.integrationStrategy}`,\n `🔄 Compatibility mode: ${aiAnalysis.compatibilityMode}`,\n '🚀 Your app is now tracking user behavior with AI-optimized configuration'\n ];\n \n if (aiAnalysis.recommendations.length > 0) {\n steps.push('💡 AI Recommendations:');\n aiAnalysis.recommendations.forEach(rec => steps.push(` • ${rec}`));\n }\n \n return steps;\n }\n\n /**\n * Learn from installation for future improvements\n */\n private async learnFromInstallation(aiAnalysis: AICodeAnalysis, modifications: CodeModification[]): Promise<void> {\n const learningData = {\n timestamp: new Date().toISOString(),\n framework: aiAnalysis.framework.name,\n patterns: aiAnalysis.patterns,\n integrationStrategy: aiAnalysis.integrationStrategy,\n compatibilityMode: aiAnalysis.compatibilityMode,\n modifications: modifications.length,\n success: true\n };\n \n // Store learning data\n this.learningCache.set(`${aiAnalysis.framework.name}_${Date.now()}`, learningData);\n \n // Update pattern database\n if (!this.patternDatabase.has(aiAnalysis.framework.name)) {\n this.patternDatabase.set(aiAnalysis.framework.name, []);\n }\n this.patternDatabase.get(aiAnalysis.framework.name)!.push(learningData);\n \n // Save to disk\n await this.saveLearningData();\n }\n\n /**\n * Load learning data from disk\n */\n private loadLearningData(): void {\n // Don't load learning data from user's project - keep it in memory only\n // This prevents cluttering the user's project with internal files\n }\n\n /**\n * Save learning data to disk\n */\n private async saveLearningData(): Promise<void> {\n // Don't save learning data to user's project - keep it in memory only\n // This prevents cluttering the user's project with internal files\n }\n\n /**\n * Get AI insights for a specific framework\n */\n public getAIInsights(frameworkName: string): any[] {\n return this.patternDatabase.get(frameworkName) || [];\n }\n\n /**\n * Get learning statistics\n */\n public getLearningStats(): any {\n const stats = {\n totalInstallations: this.learningCache.size,\n frameworks: {} as any,\n patterns: {} as any\n };\n \n for (const [framework, data] of this.patternDatabase.entries()) {\n stats.frameworks[framework] = data.length;\n }\n \n return stats;\n }\n}\n\n/**\n * Browser-based AI installation wizard\n */\nexport class AIBrowserInstallationWizard {\n private apiKey: string;\n private aiService: CentralizedAIService;\n\n constructor(apiKey: string, aiService?: CentralizedAIService) {\n this.apiKey = apiKey;\n this.aiService = aiService || new DefaultAIService();\n }\n\n async install(): Promise<AIInstallationResult> {\n try {\n // AI-powered browser detection\n const aiAnalysis = await this.performBrowserAIAnalysis();\n \n // Generate AI-optimized browser modifications\n const modifications = this.generateAIBrowserModifications(aiAnalysis);\n \n return {\n success: true,\n framework: aiAnalysis.framework,\n modifications,\n errors: [],\n nextSteps: [\n '✅ AI-optimized browser integration ready!',\n `🎯 Framework detected: ${aiAnalysis.framework.name}`,\n `🔧 Integration strategy: ${aiAnalysis.integrationStrategy}`,\n '📋 Copy the generated code to your project',\n '🚀 Your app will be ready to track user behavior'\n ],\n aiAnalysis,\n learningData: {\n patterns: aiAnalysis.patterns,\n framework: aiAnalysis.framework.name,\n success: true\n }\n };\n } catch (error) {\n return {\n success: false,\n framework: { name: 'unknown', type: 'vanilla' },\n modifications: [],\n errors: [error instanceof Error ? error.message : 'Unknown error'],\n nextSteps: [],\n aiAnalysis: {\n framework: { name: 'unknown', type: 'vanilla' },\n confidence: 0,\n patterns: [],\n conflicts: [],\n recommendations: [],\n integrationStrategy: 'script',\n compatibilityMode: 'legacy'\n },\n learningData: {\n patterns: [],\n framework: 'unknown',\n success: false\n }\n };\n }\n }\n\n private async performBrowserAIAnalysis(): Promise<AICodeAnalysis> {\n // Browser-based framework detection\n const framework = this.detectBrowserFramework();\n \n // Analyze browser environment\n const patterns = this.analyzeBrowserPatterns();\n \n // Use centralized AI service for analysis\n const codeSamples = [`Browser Environment: ${patterns.join(', ')}`];\n return await this.aiService.analyzeCodePatterns(codeSamples);\n }\n\n private detectBrowserFramework(): FrameworkInfo {\n if (typeof window !== 'undefined') {\n if ((window as any).React) {\n return { name: 'react', type: 'react' };\n }\n if ((window as any).Vue) {\n return { name: 'vue', type: 'vue' };\n }\n if ((window as any).angular) {\n return { name: 'angular', type: 'angular' };\n }\n }\n \n return { name: 'vanilla', type: 'vanilla' };\n }\n\n private analyzeBrowserPatterns(): string[] {\n const patterns: string[] = [];\n \n if (typeof window !== 'undefined') {\n // Analyze global objects\n if ((window as any).React) patterns.push('React global detected');\n if ((window as any).Vue) patterns.push('Vue global detected');\n if ((window as any).angular) patterns.push('Angular global detected');\n \n // Analyze DOM patterns\n if (document.querySelector('[data-reactroot]')) patterns.push('React DOM detected');\n if (document.querySelector('[data-vue]')) patterns.push('Vue DOM detected');\n \n // Analyze script patterns\n const scripts = document.querySelectorAll('script');\n scripts.forEach(script => {\n if (script.src.includes('react')) patterns.push('React script detected');\n if (script.src.includes('vue')) patterns.push('Vue script detected');\n });\n }\n \n return patterns;\n }\n\n private generateAIBrowserModifications(aiAnalysis: AICodeAnalysis): CodeModification[] {\n const modifications: CodeModification[] = [];\n \n switch (aiAnalysis.framework.type) {\n case 'react':\n modifications.push({\n filePath: 'App.jsx',\n action: 'create',\n content: `// AI-Optimized React Integration\nimport { HumanBehaviorProvider } from 'humanbehavior-js/react';\n\nfunction App() {\n return (\n <HumanBehaviorProvider \n apiKey=\"${this.apiKey}\"\n config={{\n // AI-generated optimizations\n enablePerformanceTracking: true,\n enableErrorTracking: true,\n framework: '${aiAnalysis.framework.name}',\n integrationStrategy: '${aiAnalysis.integrationStrategy}'\n }}\n >\n {/* Your app components */}\n </HumanBehaviorProvider>\n );\n}\n\nexport default App;`,\n description: 'AI-optimized React component with HumanBehaviorProvider'\n });\n break;\n \n default:\n modifications.push({\n filePath: 'humanbehavior-init.js',\n action: 'create',\n content: `// AI-Optimized Vanilla JS Integration\nimport { HumanBehaviorTracker } from 'humanbehavior-js';\n\nconst tracker = HumanBehaviorTracker.init('${this.apiKey}', {\n // AI-generated configuration\n framework: '${aiAnalysis.framework.name}',\n integrationStrategy: '${aiAnalysis.integrationStrategy}',\n compatibilityMode: '${aiAnalysis.compatibilityMode}',\n enablePerformanceTracking: true,\n enableErrorTracking: true\n});`,\n description: 'AI-optimized vanilla JS initialization'\n });\n }\n \n return modifications;\n }\n} ","/**\n * Remote AI Service Implementation\n * \n * This connects to your deployed Lambda function via API Gateway\n */\n\nimport { AICodeAnalysis } from '../ai/ai-install-wizard';\n\nexport interface FrameworkInfo {\n name: string;\n type: 'react' | 'vue' | 'angular' | 'svelte' | 'nextjs' | 'nuxt' | 'remix' | 'vanilla' | 'astro' | 'gatsby' | 'node';\n bundler?: 'vite' | 'webpack' | 'esbuild' | 'rollup';\n packageManager?: 'npm' | 'yarn' | 'pnpm';\n hasTypeScript?: boolean;\n hasRouter?: boolean;\n projectRoot?: string;\n version?: string;\n majorVersion?: number;\n features?: {\n hasReact18?: boolean;\n hasVue3?: boolean;\n hasNuxt3?: boolean;\n hasAngularStandalone?: boolean;\n hasNextAppRouter?: boolean;\n hasSvelteKit?: boolean;\n };\n}\n\nexport interface RemoteAIServiceConfig {\n apiEndpoint: string;\n timeout?: number;\n}\n\nexport class RemoteAIService {\n private config: RemoteAIServiceConfig;\n\n constructor(config: RemoteAIServiceConfig) {\n this.config = {\n timeout: 10000, // 10 seconds\n ...config\n };\n }\n\n /**\n * Analyze code patterns using your deployed AI service\n */\n async analyzeCodePatterns(codeSamples: string[]): Promise<AICodeAnalysis> {\n try {\n const response = await fetch(`${this.config.apiEndpoint}/analyze`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ codeSamples }),\n signal: AbortSignal.timeout(this.config.timeout || 10000)\n });\n\n if (!response.ok) {\n throw new Error(`AI service returned ${response.status}: ${response.statusText}`);\n }\n\n const result = await response.json();\n return result.analysis;\n } catch (error) {\n console.warn('Remote AI service failed, falling back to heuristic analysis:', error);\n return this.performHeuristicAnalysis(codeSamples);\n }\n }\n\n /**\n * Resolve conflicts using your deployed AI service\n */\n async resolveConflicts(conflicts: string[], framework: FrameworkInfo): Promise<string[]> {\n try {\n const response = await fetch(`${this.config.apiEndpoint}/resolve-conflicts`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ conflicts, framework }),\n signal: AbortSignal.timeout(this.config.timeout || 10000)\n });\n\n if (!response.ok) {\n throw new Error(`AI service returned ${response.status}: ${response.statusText}`);\n }\n\n const result = await response.json();\n return result.resolutions || [];\n } catch (error) {\n console.warn('Remote AI conflict resolution failed, using heuristic approach:', error);\n return this.resolveConflictsHeuristic(conflicts, framework);\n }\n }\n\n /**\n * Generate optimizations using your deployed AI service\n */\n async generateOptimizations(framework: FrameworkInfo, patterns: string[]): Promise<string[]> {\n try {\n const response = await fetch(`${this.config.apiEndpoint}/optimize`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ framework, patterns }),\n signal: AbortSignal.timeout(this.config.timeout || 10000)\n });\n\n if (!response.ok) {\n throw new Error(`AI service returned ${response.status}: ${response.statusText}`);\n }\n\n const result = await response.json();\n return result.optimizations || [];\n } catch (error) {\n console.warn('Remote AI optimization generation failed, using heuristic approach:', error);\n return this.generateOptimizationsHeuristic(framework, patterns);\n }\n }\n\n /**\n * Heuristic analysis fallback\n */\n private performHeuristicAnalysis(codeSamples: string[]): AICodeAnalysis {\n const patterns = codeSamples.join(' ').toLowerCase();\n \n // Framework detection\n let framework: FrameworkInfo = { name: 'vanilla', type: 'vanilla' };\n let confidence = 0.5;\n \n if (patterns.includes('nuxt') || patterns.includes('nuxtjs') || patterns.includes('defineNuxtConfig') || patterns.includes('nuxt.config') || patterns.includes('@nuxt/') || patterns.includes('useNuxtApp') || patterns.includes('useRuntimeConfig') || patterns.includes('useSeoMeta') || patterns.includes('useHead') || patterns.includes('useLazyFetch') || patterns.includes('useFetch') || patterns.includes('useAsyncData') || patterns.includes('#app')) {\n framework = { name: 'nuxt', type: 'nuxt' };\n confidence = 0.95;\n } else if (patterns.includes('next') || patterns.includes('nextjs') || patterns.includes('next/link') || patterns.includes('next/image') || patterns.includes('next/navigation') || patterns.includes('next/router') || patterns.includes('getserverSideProps') || patterns.includes('getstaticProps') || patterns.includes('getstaticPaths') || patterns.includes('app/layout') || patterns.includes('app/page') || patterns.includes('pages/')) {\n framework = { name: 'nextjs', type: 'nextjs' };\n confidence = 0.95;\n } else if (patterns.includes('gatsby') || patterns.includes('gatsby-browser') || patterns.includes('gatsby-ssr') || patterns.includes('gatsby-node') || patterns.includes('gatsby-config') || patterns.includes('useStaticQuery') || patterns.includes('graphql')) {\n framework = { name: 'gatsby', type: 'gatsby' };\n confidence = 0.95;\n } else if (patterns.includes('react')) {\n framework = { name: 'react', type: 'react' };\n confidence = 0.9;\n } else if (patterns.includes('vue')) {\n framework = { name: 'vue', type: 'vue' };\n confidence = 0.9;\n } else if (patterns.includes('angular')) {\n framework = { name: 'angular', type: 'angular' };\n confidence = 0.9;\n } else if (patterns.includes('svelte')) {\n framework = { name: 'svelte', type: 'svelte' };\n confidence = 0.9;\n } else if (patterns.includes('astro')) {\n framework = { name: 'astro', type: 'astro' };\n confidence = 0.9;\n }\n \n // Integration strategy\n let integrationStrategy: 'provider' | 'plugin' | 'module' | 'script' | 'standalone' = 'script';\n if (framework.type === 'react' || framework.type === 'nextjs' || framework.type === 'gatsby') {\n integrationStrategy = 'provider';\n } else if (framework.type === 'vue') {\n integrationStrategy = 'plugin';\n } else if (framework.type === 'angular') {\n integrationStrategy = 'module';\n }\n \n // Compatibility mode\n let compatibilityMode: 'modern' | 'legacy' | 'hybrid' = 'modern';\n if (patterns.includes('require(') || patterns.includes('var ')) {\n compatibilityMode = 'legacy';\n }\n \n return {\n framework,\n confidence,\n patterns: codeSamples,\n conflicts: [],\n recommendations: [],\n integrationStrategy,\n compatibilityMode\n };\n }\n\n /**\n * Heuristic conflict resolution\n */\n private resolveConflictsHeuristic(conflicts: string[], framework: FrameworkInfo): string[] {\n const resolutions: string[] = [];\n \n for (const conflict of conflicts) {\n switch (conflict) {\n case 'existing_humanbehavior_code':\n resolutions.push('update_existing_integration');\n break;\n case 'existing_provider':\n resolutions.push('merge_providers');\n break;\n case 'module_system_conflict':\n resolutions.push('hybrid_module_support');\n break;\n default:\n resolutions.push('skip_conflict');\n }\n }\n \n return resolutions;\n }\n\n /**\n * Heuristic optimization generation\n */\n private generateOptimizationsHeuristic(framework: FrameworkInfo, patterns: string[]): string[] {\n const optimizations: string[] = [];\n \n switch (framework.type) {\n case 'react':\n optimizations.push('Use React.memo for performance optimization');\n optimizations.push('Implement error boundaries for better error tracking');\n optimizations.push('Consider using React.lazy for code splitting');\n break;\n case 'vue':\n optimizations.push('Use Vue 3 Composition API for better performance');\n optimizations.push('Implement proper error handling in components');\n optimizations.push('Consider using Vue Router for navigation tracking');\n break;\n case 'angular':\n optimizations.push('Use Angular standalone components for better tree-shaking');\n optimizations.push('Implement proper error handling with ErrorHandler');\n optimizations.push('Consider using Angular signals for state management');\n break;\n default:\n optimizations.push('Enable performance tracking');\n optimizations.push('Implement error tracking');\n optimizations.push('Consider progressive enhancement');\n }\n \n return optimizations;\n }\n} ","/**\n * Manual Framework Installation Wizard\n * \n * This wizard allows users to manually specify their framework instead of auto-detection.\n * Useful when auto-detection fails or users want more control.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { AutoInstallationWizard, FrameworkInfo, CodeModification, InstallationResult, InstallationWizardOptions } from '../core/install-wizard';\nimport { RemoteAIService } from '../services/remote-ai-service';\n\nexport interface ManualInstallationResult extends InstallationResult {\n selectedFramework: string;\n manualMode: boolean;\n}\n\nexport class ManualFrameworkInstallationWizard extends AutoInstallationWizard {\n private selectedFramework: string;\n\n constructor(apiKey: string, projectRoot: string = process.cwd(), framework: string, options: InstallationWizardOptions = {}) {\n super(apiKey, projectRoot, options);\n this.selectedFramework = framework.toLowerCase();\n this.framework = this.createFrameworkInfo(this.selectedFramework);\n }\n\n /**\n * Manual installation with user-specified framework\n */\n async install(): Promise<ManualInstallationResult> {\n try {\n // Step 1: Handle framework selection\n if (this.selectedFramework === 'auto') {\n // Use full AI detection for \"Other\" option\n this.framework = await this.runFullDetection();\n } else {\n // Set framework based on user selection\n this.framework = this.createFrameworkInfo(this.selectedFramework);\n if (!this.framework) {\n this.framework = { name: 'unknown', type: 'vanilla' };\n }\n \n // Step 2: Run full detection logic to find entry points, file names, etc.\n const detectedFramework = await this.runFullDetection();\n \n // Step 3: Merge manual framework with detected details\n this.framework = {\n ...detectedFramework,\n name: this.framework.name,\n type: this.framework.type\n };\n }\n \n // Step 4: Install package\n const installPlan = await this.installPackage();\n \n // Step 5: Generate and apply code modifications\n const modifications = await this.generateModifications();\n if (!this.options.dryRun) {\n await this.applyModifications(modifications);\n }\n \n // Step 6: Generate next steps\n const nextSteps = this.generateManualNextSteps();\n \n return {\n success: true,\n framework: this.framework,\n modifications,\n errors: [],\n nextSteps,\n dryRun: this.options.dryRun,\n installPlan,\n selectedFramework: this.selectedFramework,\n manualMode: true\n };\n } catch (error) {\n return {\n success: false,\n framework: this.framework || { name: 'unknown', type: 'vanilla' },\n modifications: [],\n errors: [error instanceof Error ? error.message : 'Unknown error'],\n nextSteps: [],\n dryRun: this.options.dryRun,\n selectedFramework: this.selectedFramework,\n manualMode: true\n };\n }\n }\n\n /**\n * Run full detection logic to find entry points, file names, bundler, etc.\n */\n private async runFullDetection(): Promise<FrameworkInfo> {\n if (this.selectedFramework === 'auto') {\n // Use AI service for auto-detection\n const aiService = new RemoteAIService({\n apiEndpoint: 'https://ik3zxh4790.execute-api.us-east-1.amazonaws.com/prod'\n });\n \n // Use AI service directly for detection\n const projectFiles = await this.scanProjectFiles();\n const codeSamples = await this.extractCodeSamples(projectFiles);\n const aiAnalysis = await aiService.analyzeCodePatterns(codeSamples);\n return aiAnalysis.framework;\n } else {\n // Use traditional detection for manual frameworks\n const tempWizard = new AutoInstallationWizard(this.apiKey, this.projectRoot);\n const detected = await tempWizard.detectFramework();\n return detected;\n }\n }\n\n /**\n * Scan project files for analysis\n */\n private async scanProjectFiles(): Promise<string[]> {\n const files: string[] = [];\n const scanDir = (dir: string, depth: number = 0) => {\n if (depth > 3) return; // Limit depth\n \n try {\n const items = fs.readdirSync(dir);\n for (const item of items) {\n const fullPath = path.join(dir, item);\n const stat = fs.statSync(fullPath);\n \n if (stat.isDirectory() && !item.startsWith('.') && item !== 'node_modules') {\n scanDir(fullPath, depth + 1);\n } else if (stat.isFile() && this.isRelevantFile(item)) {\n files.push(fullPath);\n }\n }\n } catch (error) {\n // Skip inaccessible directories\n }\n };\n \n scanDir(this.projectRoot);\n return files;\n }\n\n /**\n * Check if file is relevant for analysis\n */\n private isRelevantFile(filename: string): boolean {\n const relevantExtensions = [\n '.js', '.jsx', '.ts', '.tsx', '.vue', '.svelte', '.html',\n '.json', '.config.js', '.config.ts', '.babelrc', '.eslintrc'\n ];\n \n const relevantNames = [\n 'package.json', 'tsconfig.json', 'vite.config', 'webpack.config',\n 'next.config', 'nuxt.config', 'angular.json', 'svelte.config'\n ];\n \n return relevantExtensions.some(ext => filename.endsWith(ext)) ||\n relevantNames.some(name => filename.includes(name));\n }\n\n /**\n * Extract code samples for AI analysis\n */\n private async extractCodeSamples(files: string[]): Promise<string[]> {\n const samples: string[] = [];\n \n for (const file of files.slice(0, 20)) { // Limit to 20 files\n try {\n const content = fs.readFileSync(file, 'utf8');\n const relativePath = path.relative(this.projectRoot, file);\n samples.push(`File: ${relativePath}\\n${content.substring(0, 1000)}`);\n } catch (error) {\n // Skip unreadable files\n }\n }\n \n return samples;\n }\n\n /**\n * Create framework info based on user selection\n */\n private createFrameworkInfo(framework: string): FrameworkInfo {\n const frameworkMap: Record<string, FrameworkInfo> = {\n 'react': { name: 'react', type: 'react' },\n 'nextjs': { name: 'nextjs', type: 'nextjs' },\n 'next': { name: 'nextjs', type: 'nextjs' },\n 'vue': { name: 'vue', type: 'vue' },\n 'nuxt': { name: 'nuxt', type: 'nuxt' },\n 'nuxtjs': { name: 'nuxt', type: 'nuxt' },\n 'angular': { name: 'angular', type: 'angular' },\n 'svelte': { name: 'svelte', type: 'svelte' },\n 'sveltekit': { name: 'svelte', type: 'svelte' },\n 'remix': { name: 'remix', type: 'remix' },\n 'astro': { name: 'astro', type: 'astro' },\n 'gatsby': { name: 'gatsby', type: 'gatsby' },\n 'vanilla': { name: 'vanilla', type: 'vanilla' },\n 'node': { name: 'node', type: 'node' },\n 'auto': { name: 'auto-detected', type: 'auto' }\n };\n\n return frameworkMap[framework] || { name: framework, type: 'vanilla' };\n }\n\n /**\n * Override framework detection to use manual selection\n */\n public async detectFramework(): Promise<FrameworkInfo> {\n return this.framework || { name: 'unknown', type: 'vanilla' };\n }\n\n /**\n * Generate next steps with manual mode info\n */\n private generateManualNextSteps(): string[] {\n if (this.options.dryRun) {\n return [\n 'Dry run complete. No packages were installed and no files were changed.',\n `Selected framework: ${this.framework?.name || 'unknown'}`,\n 'Review the planned install command and file modifications.',\n 'Run again without --dry-run to apply these changes.'\n ];\n }\n\n return [\n '✅ Manual framework installation completed!',\n `🎯 Selected framework: ${this.framework?.name || 'unknown'}`,\n `🔧 Integration strategy: ${this.getIntegrationStrategy()}`,\n '🚀 Your app is now ready to track user behavior',\n '📊 View sessions in your HumanBehavior dashboard'\n ];\n }\n\n /**\n * Get integration strategy based on framework\n */\n private getIntegrationStrategy(): string {\n if (!this.framework?.type) return 'script';\n \n switch (this.framework.type) {\n case 'react':\n case 'nextjs':\n return 'provider';\n case 'vue':\n return 'plugin';\n case 'angular':\n return 'module';\n default:\n return 'script';\n }\n }\n} ","import { query } from '@anthropic-ai/claude-agent-sdk';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { AgentInstallationPlan, PackageInstallPlan } from '../core/install-wizard';\n\nexport interface ClaudeAgentInstallerOptions {\n projectRoot: string;\n installPlan: PackageInstallPlan;\n framework: string;\n dryRun?: boolean;\n}\n\nexport interface ClaudeAgentApplyResult {\n success: boolean;\n agentPlan?: AgentInstallationPlan;\n result?: string;\n error?: string;\n rolledBack: boolean;\n}\n\nconst AGENT_PLAN_SCHEMA = {\n type: 'object',\n properties: {\n summary: { type: 'string' },\n targetPackagePath: { type: 'string' },\n framework: { type: 'string' },\n packageManager: { type: 'string' },\n recommendedChecks: {\n type: 'array',\n items: { type: 'string' }\n },\n risks: {\n type: 'array',\n items: { type: 'string' }\n },\n confidence: {\n type: 'number',\n minimum: 0,\n maximum: 1\n }\n },\n required: ['summary', 'recommendedChecks', 'risks', 'confidence'],\n additionalProperties: false\n};\n\nexport async function runClaudeAgentInstaller(\n options: ClaudeAgentInstallerOptions\n): Promise<AgentInstallationPlan> {\n const prompt = `You are the HumanBehavior setup wizard agent.\n\nInspect this repository in read-only planning mode and produce a JSON setup plan.\nDo not edit files. Do not install packages. Do not include API keys or secrets.\n\nKnown deterministic install plan:\n- Target package path: ${options.installPlan.targetPackagePath}\n- Workspace root: ${options.installPlan.workspaceRoot}\n- Package manager: ${options.installPlan.packageManager}\n- Install command: ${options.installPlan.command}\n- Framework guess: ${options.framework}\n- Dry run: ${options.dryRun === true}\n\nReturn only the structured JSON matching the requested schema. Focus on:\n1. Whether the target package looks correct.\n2. Which files should be instrumented.\n3. Which checks should run after deterministic mutation.\n4. Risks or ambiguities the deterministic wizard should surface.`;\n\n let resultText = '';\n\n for await (const message of query({\n prompt,\n options: {\n cwd: options.projectRoot,\n permissionMode: 'plan',\n allowedTools: ['Read', 'Glob', 'Grep', 'LS'],\n disallowedTools: ['Edit', 'MultiEdit', 'Write', 'NotebookEdit', 'Bash'],\n maxTurns: 6,\n outputFormat: {\n type: 'json_schema',\n schema: AGENT_PLAN_SCHEMA\n },\n persistSession: false\n }\n })) {\n if (message.type === 'result' && message.subtype === 'success') {\n resultText = message.result || '';\n }\n }\n\n return validateAgentPlan(resultText);\n}\n\nexport async function runClaudeAgentFullFlow(\n options: ClaudeAgentInstallerOptions\n): Promise<ClaudeAgentApplyResult> {\n const snapshot = snapshotProject(options.projectRoot);\n\n try {\n const prompt = `You are the HumanBehavior setup wizard agent.\n\nRun the full setup flow for this app:\n1. Scan the codebase.\n2. Install the SDK using exactly this command if install is needed: ${options.installPlan.command}\n3. Instrument the client entrypoint using HumanBehavior SDK best practices.\n4. Use environment-variable based API key access only. Never write a raw API key.\n5. Run safe local checks if package scripts exist.\n6. Return a concise JSON summary matching the requested schema.\n\nHard constraints:\n- Work only in this target package: ${options.installPlan.targetPackagePath}\n- Do not edit files outside the target package.\n- Do not run destructive commands.\n- Do not include secrets in output.\n- If unsure, stop and report risks instead of guessing.\n\nFramework guess: ${options.framework}\nPackage manager: ${options.installPlan.packageManager}\nWorkspace root: ${options.installPlan.workspaceRoot}`;\n\n let resultText = '';\n for await (const message of query({\n prompt,\n options: {\n cwd: options.installPlan.targetPackagePath,\n permissionMode: 'acceptEdits',\n allowedTools: ['Read', 'Glob', 'Grep', 'LS', 'Edit', 'Bash'],\n disallowedTools: ['Write', 'NotebookEdit', 'MultiEdit'],\n maxTurns: 12,\n outputFormat: {\n type: 'json_schema',\n schema: AGENT_PLAN_SCHEMA\n },\n persistSession: false,\n canUseTool: async (toolName: string, input: Record<string, unknown>) => {\n if (toolName === 'Bash') {\n const command = String(input.command || '');\n return isAllowedBash(command, options.installPlan.command)\n ? { behavior: 'allow' }\n : { behavior: 'deny', message: `Command is outside setup wizard allowlist: ${command}` };\n }\n return { behavior: 'allow' };\n }\n }\n })) {\n if (message.type === 'result') {\n if (message.subtype === 'success') {\n resultText = message.result || '';\n } else {\n throw new Error(message.subtype);\n }\n }\n }\n\n const agentPlan = validateAgentPlan(resultText);\n return {\n success: true,\n agentPlan,\n result: resultText,\n rolledBack: false\n };\n } catch (error) {\n restoreProject(options.projectRoot, snapshot);\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n rolledBack: true\n };\n }\n}\n\nfunction validateAgentPlan(rawResult: string): AgentInstallationPlan {\n let parsed: any;\n try {\n parsed = JSON.parse(rawResult);\n } catch {\n throw new Error('Claude agent did not return valid JSON');\n }\n\n if (typeof parsed.summary !== 'string') {\n throw new Error('Claude agent plan missing summary');\n }\n if (!Array.isArray(parsed.recommendedChecks) || !parsed.recommendedChecks.every((item: any) => typeof item === 'string')) {\n throw new Error('Claude agent plan has invalid recommendedChecks');\n }\n if (!Array.isArray(parsed.risks) || !parsed.risks.every((item: any) => typeof item === 'string')) {\n throw new Error('Claude agent plan has invalid risks');\n }\n if (typeof parsed.confidence !== 'number' || parsed.confidence < 0 || parsed.confidence > 1) {\n throw new Error('Claude agent plan has invalid confidence');\n }\n\n return {\n summary: parsed.summary,\n targetPackagePath: typeof parsed.targetPackagePath === 'string' ? parsed.targetPackagePath : undefined,\n framework: typeof parsed.framework === 'string' ? parsed.framework : undefined,\n packageManager: typeof parsed.packageManager === 'string' ? parsed.packageManager : undefined,\n recommendedChecks: parsed.recommendedChecks,\n risks: parsed.risks,\n confidence: parsed.confidence,\n rawResult\n };\n}\n\nfunction isAllowedBash(command: string, installCommand: string): boolean {\n if (!command) return false;\n const trimmed = command.trim();\n if (trimmed === installCommand) return true;\n if (/^(npm|pnpm|yarn|bun) run (build|test|lint|typecheck|check)(\\s|$)/.test(trimmed)) return true;\n if (/^(npm|pnpm|yarn|bun) (test|lint)(\\s|$)/.test(trimmed)) return true;\n return false;\n}\n\nfunction snapshotProject(root: string): Map<string, string | null> {\n const snapshot = new Map<string, string | null>();\n for (const filePath of listProjectFiles(root)) {\n snapshot.set(filePath, fs.readFileSync(filePath, 'utf8'));\n }\n return snapshot;\n}\n\nfunction restoreProject(root: string, snapshot: Map<string, string | null>): void {\n const currentFiles = new Set(listProjectFiles(root));\n for (const filePath of currentFiles) {\n if (!snapshot.has(filePath)) {\n fs.rmSync(filePath, { force: true });\n }\n }\n for (const [filePath, content] of snapshot.entries()) {\n if (content !== null) {\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n fs.writeFileSync(filePath, content);\n }\n }\n}\n\nfunction listProjectFiles(root: string): string[] {\n const out: string[] = [];\n const ignored = new Set(['node_modules', '.git', 'dist', 'build', '.next', '.nuxt', '.svelte-kit']);\n const walk = (dir: string) => {\n if (!fs.existsSync(dir)) return;\n for (const entry of fs.readdirSync(dir)) {\n if (ignored.has(entry)) continue;\n const fullPath = path.join(dir, entry);\n const stat = fs.statSync(fullPath);\n if (stat.isDirectory()) {\n walk(fullPath);\n } else if (stat.isFile() && stat.size <= 1024 * 1024) {\n out.push(fullPath);\n }\n }\n };\n walk(root);\n return out;\n}\n","#!/usr/bin/env node\n\n/**\n * AI-Enhanced HumanBehavior SDK Auto-Installation CLI\n * \n * Usage: npx humanbehavior-js ai-auto-install [api-key]\n * \n * This tool uses AI to intelligently detect frameworks, analyze code patterns,\n * and generate optimal integration code that's both future-proof and backward-compatible.\n */\n\nimport { AIEnhancedInstallationWizard, AIBrowserInstallationWizard } from '../ai/ai-install-wizard';\nimport { ManualFrameworkInstallationWizard } from '../ai/manual-framework-wizard';\nimport { AutoInstallationWizard } from '../core/install-wizard';\nimport { RemoteAIService } from '../services/remote-ai-service';\nimport { runClaudeAgentFullFlow, runClaudeAgentInstaller } from '../agent/claude-agent-installer';\nimport * as clack from '@clack/prompts';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\ninterface AICLIOptions {\n apiKey?: string;\n apiKeyFile?: string;\n reportJson?: string;\n projectPath?: string;\n yes?: boolean;\n dryRun?: boolean;\n upgrade?: boolean;\n agent?: boolean;\n agentApply?: boolean;\n framework?: string;\n}\n\nclass AIAutoInstallCLI {\n private options: AICLIOptions;\n\n constructor(options: AICLIOptions) {\n this.options = options;\n }\n\n async run() {\n clack.intro('🤖 AI-Enhanced HumanBehavior SDK Auto-Installation');\n\n try {\n // Get API key\n const apiKey = await this.getApiKey();\n if (!apiKey) {\n clack.cancel('API key is required');\n process.exit(1);\n }\n\n // Get project path\n const projectPath = this.options.projectPath || process.cwd();\n \n // Choose framework\n const framework = await this.chooseFramework();\n if (!framework) {\n clack.cancel('Installation cancelled.');\n process.exit(0);\n }\n \n // Confirm installation\n if (!this.options.yes) {\n const confirmed = await this.confirmInstallation(projectPath, framework);\n if (!confirmed) {\n clack.cancel('Installation cancelled.');\n process.exit(0);\n }\n }\n\n // Run installation\n const spinner = clack.spinner();\n spinner.start('🔍 Analyzing your project with AI...');\n \n const wizard = new ManualFrameworkInstallationWizard(apiKey, projectPath, framework, {\n dryRun: this.options.dryRun,\n upgrade: this.options.upgrade\n });\n if (this.options.agent) {\n const detected = await wizard.detectFramework();\n const installPlan = wizard.planPackageInstall();\n const agentResult = this.options.agentApply && !this.options.dryRun\n ? await runClaudeAgentFullFlow({\n projectRoot: projectPath,\n installPlan,\n framework: detected.name,\n dryRun: this.options.dryRun\n })\n : { success: true, agentPlan: await runClaudeAgentInstaller({\n projectRoot: projectPath,\n installPlan,\n framework: detected.name,\n dryRun: this.options.dryRun\n }), rolledBack: false };\n\n if (agentResult.success && agentResult.agentPlan) {\n wizard.setAgentPlan(agentResult.agentPlan);\n if (this.options.agentApply && !this.options.dryRun) {\n clack.outro('Claude agent completed setup successfully.');\n this.writeReport({\n success: true,\n framework: detected,\n modifications: [],\n errors: [],\n nextSteps: agentResult.agentPlan.recommendedChecks,\n dryRun: false,\n installPlan,\n agentPlan: agentResult.agentPlan\n }, framework);\n return;\n }\n } else {\n clack.note(\n `${agentResult.error || 'Unknown agent error'}\\nRolled back: ${agentResult.rolledBack ? 'yes' : 'no'}\\nContinuing with deterministic fallback.`,\n 'Claude Agent Fallback'\n );\n }\n }\n const result = await wizard.install();\n\n spinner.stop(this.options.dryRun ? 'Dry run complete!' : 'Analysis complete!');\n\n // Display results\n this.displayResults(result, framework);\n this.writeReport(result, framework);\n\n } catch (error) {\n clack.cancel(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exit(1);\n }\n }\n\n private async getApiKey(): Promise<string> {\n if (this.options.apiKey) {\n return this.options.apiKey;\n }\n\n if (this.options.apiKeyFile) {\n return fs.readFileSync(this.options.apiKeyFile, 'utf8').trim();\n }\n\n if (process.env.HB_API_KEY) {\n return process.env.HB_API_KEY;\n }\n\n const apiKey = await clack.text({\n message: 'Enter your HumanBehavior API key:',\n placeholder: 'hb_...',\n validate: (value) => {\n if (!value) return 'API key is required';\n if (!value.startsWith('hb_')) return 'API key should start with \"hb_\"';\n return undefined;\n }\n });\n\n return apiKey as string;\n }\n\n\n\n\n\n private async confirmInstallation(projectPath: string, framework: string): Promise<boolean> {\n const confirmed = await clack.confirm({\n message: `Ready to install HumanBehavior SDK in ${projectPath} for ${framework}?`\n });\n\n return confirmed as boolean;\n }\n\n private async chooseFramework(): Promise<string> {\n if (this.options.framework) {\n return this.options.framework;\n }\n\n const framework = await clack.select({\n message: 'Select your framework:',\n options: [\n { label: 'React', value: 'react' },\n { label: 'Next.js', value: 'nextjs' },\n { label: 'Vue', value: 'vue' },\n { label: 'Angular', value: 'angular' },\n { label: 'Svelte', value: 'svelte' },\n { label: 'Nuxt.js', value: 'nuxt' },\n { label: 'Remix', value: 'remix' },\n { label: 'Astro', value: 'astro' },\n { label: 'Gatsby', value: 'gatsby' },\n { label: 'Vanilla JS/TS', value: 'vanilla' }\n ]\n });\n\n return framework as string;\n }\n\n private displayResults(result: any, framework: string) {\n if (result.success) {\n clack.outro(result.dryRun\n ? 'Dry run completed successfully. No packages were installed and no files were changed.'\n : '🎉 Installation completed successfully!');\n\n // Display framework info\n clack.note(`Framework detected: ${result.framework.name} (${result.framework.type})`, 'Framework Info');\n\n // Display modifications\n if (result.installPlan) {\n clack.note(\n [\n `Command: ${result.installPlan.command}`,\n `Run from: ${result.installPlan.cwd}`,\n `Target package: ${result.installPlan.targetPackagePath}`,\n `Workspace: ${result.installPlan.isWorkspace ? 'yes' : 'no'}`,\n `Version status: ${result.installPlan.versionStatus}`,\n result.installPlan.alreadyInstalled\n ? `Already installed: ${result.installPlan.installedVersion}`\n : `Reason: ${result.installPlan.reason}`\n ].join('\\n'),\n result.dryRun ? 'Planned Package Install' : 'Package Install'\n );\n }\n\n if (result.modifications && result.modifications.length > 0) {\n const modifications = result.modifications.map((mod: any) => \n `${mod.action}: ${mod.filePath} - ${mod.description}`\n );\n clack.note(modifications.join('\\n'), result.dryRun ? 'Planned File Changes' : 'Files Modified');\n }\n\n if (result.agentPlan) {\n clack.note(\n [\n result.agentPlan.summary,\n `Confidence: ${Math.round(result.agentPlan.confidence * 100)}%`,\n result.agentPlan.recommendedChecks.length\n ? `Checks: ${result.agentPlan.recommendedChecks.join(', ')}`\n : 'Checks: none',\n result.agentPlan.risks.length\n ? `Risks: ${result.agentPlan.risks.join(', ')}`\n : 'Risks: none'\n ].join('\\n'),\n 'Claude Agent Plan'\n );\n }\n\n // Display next steps\n if (result.nextSteps && result.nextSteps.length > 0) {\n clack.note(result.nextSteps.join('\\n'), 'Next Steps');\n }\n\n // Display AI insights if available\n if (result.aiAnalysis) {\n clack.note(`Confidence: ${Math.round(result.aiAnalysis.confidence * 100)}%`, 'AI Analysis');\n if (result.aiAnalysis.recommendations && result.aiAnalysis.recommendations.length > 0) {\n clack.note(result.aiAnalysis.recommendations.join('\\n'), 'AI Recommendations');\n }\n }\n\n } else {\n clack.cancel('Installation failed');\n \n if (result.errors && result.errors.length > 0) {\n clack.note(result.errors.join('\\n'), 'Errors');\n }\n }\n }\n\n private writeReport(result: any, selectedFramework: string) {\n if (!this.options.reportJson) return;\n\n const report = {\n schemaVersion: 1,\n status: result.success ? (result.dryRun ? 'dry-run' : 'completed') : 'failed',\n selectedFramework,\n framework: result.framework,\n dryRun: result.dryRun === true,\n installPlan: result.installPlan,\n agentPlan: result.agentPlan\n ? {\n summary: result.agentPlan.summary,\n targetPackagePath: result.agentPlan.targetPackagePath,\n framework: result.agentPlan.framework,\n packageManager: result.agentPlan.packageManager,\n recommendedChecks: result.agentPlan.recommendedChecks,\n risks: result.agentPlan.risks,\n confidence: result.agentPlan.confidence\n }\n : undefined,\n modifications: (result.modifications || []).map((mod: any) => ({\n filePath: mod.filePath,\n action: mod.action,\n description: mod.description\n })),\n errors: result.errors || [],\n nextSteps: result.nextSteps || []\n };\n\n fs.writeFileSync(this.options.reportJson, JSON.stringify(report, null, 2));\n }\n}\n\nfunction parseArgs(): AICLIOptions {\n const args = process.argv.slice(2);\n const options: AICLIOptions = {};\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n \n switch (arg) {\n case '--help':\n case '-h':\n showHelp();\n process.exit(0);\n break;\n case '--yes':\n case '-y':\n options.yes = true;\n break;\n case '--dry-run':\n options.dryRun = true;\n break;\n case '--upgrade':\n options.upgrade = true;\n break;\n case '--agent':\n options.agent = true;\n break;\n case '--agent-apply':\n options.agent = true;\n options.agentApply = true;\n break;\n case '--project':\n case '-p':\n options.projectPath = args[++i];\n break;\n case '--api-key-file':\n options.apiKeyFile = args[++i];\n break;\n case '--report-json':\n options.reportJson = args[++i];\n break;\n case '--framework':\n case '-f':\n options.framework = args[++i];\n break;\n case 'init':\n if (args[i + 1] && !args[i + 1].startsWith('-')) {\n options.apiKey = args[++i];\n }\n break;\n default:\n if (!options.apiKey && !arg.startsWith('-')) {\n options.apiKey = arg;\n }\n break;\n }\n }\n\n return options;\n}\n\nfunction showHelp() {\n console.log(`\n🤖 HumanBehavior SDK AI Auto-Installation\n\nUsage: npx humanbehavior-js ai-auto-install [api-key] [options]\n\nOptions:\n -h, --help Show this help message\n -y, --yes Skip all prompts and use defaults\n --dry-run Show what would be changed without making changes\n --upgrade Upgrade stale existing SDK versions\n --agent Use Claude Agent SDK to inspect and plan before deterministic changes\n --agent-apply Let Claude attempt guarded install/edit/check before deterministic fallback\n\n --api-key-file <path> Read API key from a local file\n --report-json <path> Write a structured install report without file contents\n -p, --project <path> Specify project directory\n -f, --framework <name> Specify framework manually\n\nExamples:\n npx humanbehavior-js ai-auto-install\n npx humanbehavior-js ai-auto-install hb_your_api_key_here\n npx humanbehavior-js ai-auto-install --project ./my-app --ai\n npx humanbehavior-js ai-auto-install --framework react --yes\n`);\n}\n\nfunction showInitHelp() {\n console.log(`\nUsage: npx humanbehavior-js init [api-key]\n\nArguments:\n api-key Your HumanBehavior API key (optional; prefer HB_API_KEY or --api-key-file)\n\nExamples:\n HB_API_KEY=hb_your_api_key_here npx humanbehavior-js init\n npx humanbehavior-js init --api-key-file .humanbehavior-key\n`);\n}\n\nconst isMain = import.meta.url === `file://${process.argv[1]}`;\nif (isMain) {\n const options = parseArgs();\n const cli = new AIAutoInstallCLI(options);\n cli.run().catch((error) => {\n clack.cancel(`Unexpected error: ${error.message}`);\n process.exit(1);\n });\n}\n\nexport { AIAutoInstallCLI }; ","#!/usr/bin/env node\n\n/**\n * HumanBehavior SDK Auto-Installation CLI\n * \n * Usage: npx humanbehavior-js auto-install [api-key]\n * \n * This tool automatically detects the user's framework and modifies their codebase\n * to integrate the SDK with minimal user intervention.\n */\n\nimport { AutoInstallationWizard } from '../core/install-wizard';\nimport * as clack from '@clack/prompts';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\ninterface CLIOptions {\n apiKey?: string;\n apiKeyFile?: string;\n reportJson?: string;\n projectPath?: string;\n yes?: boolean;\n dryRun?: boolean;\n upgrade?: boolean;\n}\n\nclass AutoInstallCLI {\n private options: CLIOptions;\n\n constructor(options: CLIOptions) {\n this.options = options;\n }\n\n async run() {\n clack.intro('🚀 HumanBehavior SDK Auto-Installation');\n\n try {\n // Get API key\n const apiKey = await this.getApiKey();\n if (!apiKey) {\n clack.cancel('API key is required');\n process.exit(1);\n }\n\n // Get project path\n const projectPath = this.options.projectPath || process.cwd();\n \n // Confirm installation\n if (!this.options.yes) {\n const confirmed = await this.confirmInstallation(projectPath);\n if (!confirmed) {\n clack.cancel('Installation cancelled.');\n process.exit(0);\n }\n }\n\n // Run installation\n const spinner = clack.spinner();\n spinner.start('🔍 Detecting framework and applying integration...');\n \n const wizard = new AutoInstallationWizard(apiKey, projectPath, {\n dryRun: this.options.dryRun,\n upgrade: this.options.upgrade\n });\n const result = await wizard.install();\n\n spinner.stop(this.options.dryRun ? 'Dry run complete!' : 'Installation complete!');\n\n // Display results\n this.displayResults(result);\n this.writeReport(result);\n\n } catch (error) {\n clack.cancel(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exit(1);\n }\n }\n\n private async getApiKey(): Promise<string> {\n if (this.options.apiKey) {\n return this.options.apiKey;\n }\n\n if (this.options.apiKeyFile) {\n return fs.readFileSync(this.options.apiKeyFile, 'utf8').trim();\n }\n\n if (process.env.HB_API_KEY) {\n return process.env.HB_API_KEY;\n }\n\n const apiKey = await clack.text({\n message: 'Enter your HumanBehavior API key:',\n placeholder: 'hb_...',\n validate: (value) => {\n if (!value) return 'API key is required';\n if (!value.startsWith('hb_')) return 'API key should start with \"hb_\"';\n return undefined;\n }\n });\n\n return apiKey as string;\n }\n\n\n\n // Framework selection no longer needed; AutoInstallationWizard auto-detects\n\n private async confirmInstallation(projectPath: string): Promise<boolean> {\n const confirmed = await clack.confirm({\n message: `Ready to install HumanBehavior SDK in ${projectPath}?`\n });\n\n return confirmed as boolean;\n }\n\n private displayResults(result: any) {\n if (result.success) {\n clack.outro(result.dryRun\n ? 'Dry run completed successfully. No packages were installed and no files were changed.'\n : '🎉 Installation completed successfully!');\n\n // Display framework info\n clack.note(`Framework detected: ${result.framework.name} (${result.framework.type})`, 'Framework Info');\n\n // Display modifications\n if (result.installPlan) {\n clack.note(\n [\n `Command: ${result.installPlan.command}`,\n `Run from: ${result.installPlan.cwd}`,\n `Target package: ${result.installPlan.targetPackagePath}`,\n `Workspace: ${result.installPlan.isWorkspace ? 'yes' : 'no'}`,\n `Version status: ${result.installPlan.versionStatus}`,\n result.installPlan.alreadyInstalled\n ? `Already installed: ${result.installPlan.installedVersion}`\n : `Reason: ${result.installPlan.reason}`\n ].join('\\n'),\n result.dryRun ? 'Planned Package Install' : 'Package Install'\n );\n }\n\n if (result.modifications && result.modifications.length > 0) {\n const modifications = result.modifications.map((mod: any) => \n `${mod.action}: ${mod.filePath} - ${mod.description}`\n );\n clack.note(modifications.join('\\n'), result.dryRun ? 'Planned File Changes' : 'Files Modified');\n }\n\n // Display next steps\n if (result.nextSteps && result.nextSteps.length > 0) {\n clack.note(result.nextSteps.join('\\n'), 'Next Steps');\n }\n\n } else {\n clack.cancel('Installation failed');\n \n if (result.errors && result.errors.length > 0) {\n clack.note(result.errors.join('\\n'), 'Errors');\n }\n }\n }\n\n private writeReport(result: any) {\n if (!this.options.reportJson) return;\n\n const report = {\n schemaVersion: 1,\n status: result.success ? (result.dryRun ? 'dry-run' : 'completed') : 'failed',\n framework: result.framework,\n dryRun: result.dryRun === true,\n installPlan: result.installPlan,\n modifications: (result.modifications || []).map((mod: any) => ({\n filePath: mod.filePath,\n action: mod.action,\n description: mod.description\n })),\n errors: result.errors || [],\n nextSteps: result.nextSteps || []\n };\n\n fs.writeFileSync(this.options.reportJson, JSON.stringify(report, null, 2));\n }\n}\n\nfunction parseArgs(): CLIOptions {\n const args = process.argv.slice(2);\n const options: CLIOptions = {};\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n \n switch (arg) {\n case '--help':\n case '-h':\n showHelp();\n process.exit(0);\n break;\n case '--yes':\n case '-y':\n options.yes = true;\n break;\n case '--dry-run':\n options.dryRun = true;\n break;\n case '--upgrade':\n options.upgrade = true;\n break;\n case '--project':\n case '-p':\n options.projectPath = args[++i];\n break;\n case '--api-key-file':\n options.apiKeyFile = args[++i];\n break;\n case '--report-json':\n options.reportJson = args[++i];\n break;\n default:\n if (!options.apiKey && !arg.startsWith('-')) {\n options.apiKey = arg;\n }\n break;\n }\n }\n\n return options;\n}\n\nfunction showHelp() {\n console.log(`\n🚀 HumanBehavior SDK Auto-Installation\n\nUsage: npx humanbehavior-js auto-install [api-key] [options]\n\nThis tool automatically detects your framework and integrates the HumanBehavior SDK.\n\nOptions:\n -h, --help Show this help message\n -y, --yes Skip all prompts and use defaults\n --dry-run Show what would be changed without making changes\n --upgrade Upgrade stale existing SDK versions\n --api-key-file <path> Read API key from a local file\n --report-json <path> Write a structured install report without file contents\n -p, --project <path> Specify project directory\n\nExamples:\n npx humanbehavior-js auto-install\n npx humanbehavior-js auto-install hb_your_api_key_here\n npx humanbehavior-js auto-install --project ./my-app --yes\n`);\n}\n\n// Main execution (ES module compatible)\n// Check if this file is being run directly\nconst isMain = import.meta.url === `file://${process.argv[1]}`;\nif (isMain) {\n const options = parseArgs();\n const cli = new AutoInstallCLI(options);\n cli.run().catch((error) => {\n clack.cancel(`Unexpected error: ${error.message}`);\n process.exit(1);\n });\n}\n\nexport { AutoInstallCLI }; ","/**\n * Centralized AI Service Implementation\n * \n * This service runs on your backend infrastructure and provides AI-powered\n * code analysis without requiring users to provide their own API keys.\n * \n * The service can be deployed as:\n * - AWS Lambda function\n * - Docker container\n * - Express.js server\n * - Cloud function\n */\n\nimport { AICodeAnalysis } from '../ai/ai-install-wizard';\n\nexport interface FrameworkInfo {\n name: string;\n type: 'react' | 'vue' | 'angular' | 'svelte' | 'nextjs' | 'nuxt' | 'remix' | 'vanilla' | 'astro' | 'node';\n bundler?: 'vite' | 'webpack' | 'esbuild' | 'rollup';\n packageManager?: 'npm' | 'yarn' | 'pnpm';\n hasTypeScript?: boolean;\n hasRouter?: boolean;\n projectRoot?: string;\n}\n\nexport interface CentralizedAIServiceConfig {\n openaiApiKey: string;\n openaiModel?: string;\n maxTokens?: number;\n temperature?: number;\n enableCaching?: boolean;\n cacheTTL?: number;\n}\n\nexport interface AIAnalysisRequest {\n codeSamples: string[];\n projectType?: string;\n userAgent?: string;\n timestamp: string;\n}\n\nexport interface AIAnalysisResponse {\n analysis: AICodeAnalysis;\n processingTime: number;\n cacheHit?: boolean;\n modelUsed: string;\n}\n\nexport interface ConflictResolutionRequest {\n conflicts: string[];\n framework: FrameworkInfo;\n codeContext?: string;\n}\n\nexport interface OptimizationRequest {\n framework: FrameworkInfo;\n patterns: string[];\n projectContext?: string;\n}\n\n/**\n * Centralized AI Service Implementation\n * This runs on your backend infrastructure\n */\nexport class CentralizedAIService {\n private config: CentralizedAIServiceConfig;\n private cache: Map<string, any> = new Map();\n private openai: any; // OpenAI client\n\n constructor(config: CentralizedAIServiceConfig) {\n this.config = {\n openaiModel: 'gpt-4',\n maxTokens: 2000,\n temperature: 0.3,\n enableCaching: true,\n cacheTTL: 3600, // 1 hour\n ...config\n };\n \n this.initializeOpenAI();\n }\n\n /**\n * Initialize OpenAI client\n */\n private initializeOpenAI() {\n try {\n // Import OpenAI dynamically to avoid bundling issues\n const { OpenAI } = require('openai');\n this.openai = new OpenAI({\n apiKey: this.config.openaiApiKey\n });\n } catch (error) {\n console.warn('OpenAI not available, falling back to heuristic analysis');\n this.openai = null;\n }\n }\n\n /**\n * Analyze code patterns using AI\n */\n async analyzeCodePatterns(codeSamples: string[]): Promise<AICodeAnalysis> {\n const request: AIAnalysisRequest = {\n codeSamples,\n timestamp: new Date().toISOString()\n };\n\n // Check cache first\n const cacheKey = this.generateCacheKey(request);\n if (this.config.enableCaching) {\n const cached = this.cache.get(cacheKey);\n if (cached && this.isCacheValid(cached.timestamp)) {\n return cached.analysis;\n }\n }\n\n // Perform AI analysis\n const startTime = Date.now();\n const analysis = await this.performAIAnalysis(request);\n const processingTime = Date.now() - startTime;\n\n // Cache the result\n if (this.config.enableCaching) {\n this.cache.set(cacheKey, {\n analysis,\n timestamp: Date.now()\n });\n }\n\n return analysis;\n }\n\n /**\n * Resolve conflicts using AI\n */\n async resolveConflicts(conflicts: string[], framework: FrameworkInfo): Promise<string[]> {\n const request: ConflictResolutionRequest = {\n conflicts,\n framework,\n codeContext: 'HumanBehavior SDK integration'\n };\n\n if (!this.openai) {\n return this.resolveConflictsHeuristic(conflicts, framework);\n }\n\n try {\n const prompt = this.buildConflictResolutionPrompt(request);\n const response = await this.openai.chat.completions.create({\n model: this.config.openaiModel,\n messages: [\n {\n role: 'system',\n content: 'You are an expert at resolving code integration conflicts. Provide specific resolution strategies.'\n },\n {\n role: 'user',\n content: prompt\n }\n ],\n max_tokens: this.config.maxTokens,\n temperature: this.config.temperature\n });\n\n const content = response.choices[0]?.message?.content;\n if (content && typeof content === 'string') {\n return this.parseConflictResolutions(content);\n }\n return [];\n } catch (error) {\n console.warn('AI conflict resolution failed, using heuristic approach:', error instanceof Error ? error.message : 'Unknown error');\n }\n\n return this.resolveConflictsHeuristic(conflicts, framework);\n }\n\n /**\n * Generate optimizations using AI\n */\n async generateOptimizations(framework: FrameworkInfo, patterns: string[]): Promise<string[]> {\n const request: OptimizationRequest = {\n framework,\n patterns,\n projectContext: 'HumanBehavior SDK integration'\n };\n\n if (!this.openai) {\n return this.generateOptimizationsHeuristic(framework, patterns);\n }\n\n try {\n const prompt = this.buildOptimizationPrompt(request);\n const response = await this.openai.chat.completions.create({\n model: this.config.openaiModel,\n messages: [\n {\n role: 'system',\n content: 'You are an expert at optimizing code integration. Provide specific, actionable recommendations.'\n },\n {\n role: 'user',\n content: prompt\n }\n ],\n max_tokens: this.config.maxTokens,\n temperature: this.config.temperature\n });\n\n const content = response.choices[0]?.message?.content;\n if (content) {\n return this.parseOptimizations(content);\n }\n } catch (error) {\n console.warn('AI optimization generation failed, using heuristic approach:', error instanceof Error ? error.message : 'Unknown error');\n }\n\n return this.generateOptimizationsHeuristic(framework, patterns);\n }\n\n /**\n * Perform AI analysis\n */\n private async performAIAnalysis(request: AIAnalysisRequest): Promise<AICodeAnalysis> {\n if (!this.openai) {\n return this.performHeuristicAnalysis(request);\n }\n\n try {\n const prompt = this.buildAnalysisPrompt(request);\n const response = await this.openai.chat.completions.create({\n model: this.config.openaiModel,\n messages: [\n {\n role: 'system',\n content: 'You are an expert at analyzing code patterns and determining optimal integration strategies. Provide detailed analysis in JSON format.'\n },\n {\n role: 'user',\n content: prompt\n }\n ],\n max_tokens: this.config.maxTokens,\n temperature: this.config.temperature,\n response_format: { type: 'json_object' }\n });\n\n const content = response.choices[0]?.message?.content;\n if (content) {\n return this.parseAnalysisResult(content);\n }\n } catch (error) {\n console.warn('AI analysis failed, using heuristic approach:', error instanceof Error ? error.message : 'Unknown error');\n }\n\n return this.performHeuristicAnalysis(request);\n }\n\n /**\n * Build analysis prompt\n */\n private buildAnalysisPrompt(request: AIAnalysisRequest): string {\n return `Analyze these code samples to determine the framework and integration strategy:\n\n${request.codeSamples.join('\\n\\n')}\n\nProvide analysis in JSON format with:\n- framework: { name, type, confidence (0-1) }\n- patterns: array of detected patterns\n- conflicts: array of potential conflicts\n- recommendations: array of integration recommendations\n- integrationStrategy: \"provider\" | \"plugin\" | \"module\" | \"script\" | \"standalone\"\n- compatibilityMode: \"modern\" | \"legacy\" | \"hybrid\"\n\nFocus on:\n1. Framework detection beyond package.json\n2. Code patterns and architecture\n3. Integration compatibility\n4. Future-proof strategies\n5. Backward compatibility needs\n\nRespond with valid JSON only.`;\n }\n\n /**\n * Build conflict resolution prompt\n */\n private buildConflictResolutionPrompt(request: ConflictResolutionRequest): string {\n return `Resolve these integration conflicts for ${request.framework.name}:\n\nConflicts: ${request.conflicts.join(', ')}\n\nFramework: ${request.framework.name} (${request.framework.type})\nContext: ${request.codeContext}\n\nProvide specific resolution strategies for each conflict. Options:\n- update_existing_integration: Update existing code\n- merge_providers: Merge multiple providers\n- hybrid_module_support: Support both module systems\n- skip_conflict: Skip the modification\n- custom_resolution: Custom resolution strategy\n\nRespond with a JSON array of resolution strategies.`;\n }\n\n /**\n * Build optimization prompt\n */\n private buildOptimizationPrompt(request: OptimizationRequest): string {\n return `Generate optimizations for ${request.framework.name} integration:\n\nFramework: ${request.framework.name} (${request.framework.type})\nPatterns: ${request.patterns.join(', ')}\nContext: ${request.projectContext}\n\nProvide specific, actionable optimization recommendations for:\n1. Performance improvements\n2. Error handling\n3. Code organization\n4. Future-proofing\n5. Backward compatibility\n\nRespond with a JSON array of optimization recommendations.`;\n }\n\n /**\n * Parse analysis result\n */\n private parseAnalysisResult(content: string): AICodeAnalysis {\n try {\n const result = JSON.parse(content);\n return {\n framework: result.framework || { name: 'vanilla', type: 'vanilla' },\n confidence: result.confidence || 0.5,\n patterns: result.patterns || [],\n conflicts: result.conflicts || [],\n recommendations: result.recommendations || [],\n integrationStrategy: result.integrationStrategy || 'script',\n compatibilityMode: result.compatibilityMode || 'modern'\n };\n } catch (error) {\n console.warn('Failed to parse AI analysis result:', error);\n return this.getDefaultAnalysis();\n }\n }\n\n /**\n * Parse conflict resolutions\n */\n private parseConflictResolutions(content: string): string[] {\n try {\n const result = JSON.parse(content);\n return Array.isArray(result) ? result : [];\n } catch (error) {\n console.warn('Failed to parse conflict resolutions:', error);\n return [];\n }\n }\n\n /**\n * Parse optimizations\n */\n private parseOptimizations(content: string): string[] {\n try {\n const result = JSON.parse(content);\n return Array.isArray(result) ? result : [];\n } catch (error) {\n console.warn('Failed to parse optimizations:', error);\n return [];\n }\n }\n\n /**\n * Heuristic analysis fallback\n */\n private performHeuristicAnalysis(request: AIAnalysisRequest): AICodeAnalysis {\n const patterns = request.codeSamples.join(' ').toLowerCase();\n \n // Framework detection\n let framework: FrameworkInfo = { name: 'vanilla', type: 'vanilla' };\n let confidence = 0.5;\n \n if (patterns.includes('react')) {\n framework = { name: 'react', type: 'react' };\n confidence = 0.9;\n } else if (patterns.includes('vue')) {\n framework = { name: 'vue', type: 'vue' };\n confidence = 0.9;\n } else if (patterns.includes('angular')) {\n framework = { name: 'angular', type: 'angular' };\n confidence = 0.9;\n } else if (patterns.includes('svelte')) {\n framework = { name: 'svelte', type: 'svelte' };\n confidence = 0.9;\n } else if (patterns.includes('next')) {\n framework = { name: 'nextjs', type: 'nextjs' };\n confidence = 0.9;\n } else if (patterns.includes('nuxt')) {\n framework = { name: 'nuxt', type: 'nuxt' };\n confidence = 0.9;\n }\n \n // Integration strategy\n let integrationStrategy: 'provider' | 'plugin' | 'module' | 'script' | 'standalone' = 'script';\n if (framework.type === 'react' || framework.type === 'nextjs') {\n integrationStrategy = 'provider';\n } else if (framework.type === 'vue') {\n integrationStrategy = 'plugin';\n } else if (framework.type === 'angular') {\n integrationStrategy = 'module';\n }\n \n // Compatibility mode\n let compatibilityMode: 'modern' | 'legacy' | 'hybrid' = 'modern';\n if (patterns.includes('require(') || patterns.includes('var ')) {\n compatibilityMode = 'legacy';\n }\n \n return {\n framework,\n confidence,\n patterns: request.codeSamples,\n conflicts: [],\n recommendations: [],\n integrationStrategy,\n compatibilityMode\n };\n }\n\n /**\n * Heuristic conflict resolution\n */\n private resolveConflictsHeuristic(conflicts: string[], framework: FrameworkInfo): string[] {\n const resolutions: string[] = [];\n \n for (const conflict of conflicts) {\n switch (conflict) {\n case 'existing_humanbehavior_code':\n resolutions.push('update_existing_integration');\n break;\n case 'existing_provider':\n resolutions.push('merge_providers');\n break;\n case 'module_system_conflict':\n resolutions.push('hybrid_module_support');\n break;\n default:\n resolutions.push('skip_conflict');\n }\n }\n \n return resolutions;\n }\n\n /**\n * Heuristic optimization generation\n */\n private generateOptimizationsHeuristic(framework: FrameworkInfo, patterns: string[]): string[] {\n const optimizations: string[] = [];\n \n switch (framework.type) {\n case 'react':\n optimizations.push('Use React.memo for performance optimization');\n optimizations.push('Implement error boundaries for better error tracking');\n optimizations.push('Consider using React.lazy for code splitting');\n break;\n case 'vue':\n optimizations.push('Use Vue 3 Composition API for better performance');\n optimizations.push('Implement proper error handling in components');\n optimizations.push('Consider using Vue Router for navigation tracking');\n break;\n case 'angular':\n optimizations.push('Use Angular standalone components for better tree-shaking');\n optimizations.push('Implement proper error handling with ErrorHandler');\n optimizations.push('Consider using Angular signals for state management');\n break;\n default:\n optimizations.push('Enable performance tracking');\n optimizations.push('Implement error tracking');\n optimizations.push('Consider progressive enhancement');\n }\n \n return optimizations;\n }\n\n /**\n * Generate cache key\n */\n private generateCacheKey(request: AIAnalysisRequest): string {\n const content = JSON.stringify(request);\n return Buffer.from(content).toString('base64').substring(0, 32);\n }\n\n /**\n * Check if cache is valid\n */\n private isCacheValid(timestamp: number): boolean {\n const now = Date.now();\n const ttl = (this.config.cacheTTL || 3600) * 1000; // Convert to milliseconds\n return (now - timestamp) < ttl;\n }\n\n /**\n * Get default analysis\n */\n private getDefaultAnalysis(): AICodeAnalysis {\n return {\n framework: { name: 'vanilla', type: 'vanilla' },\n confidence: 0.5,\n patterns: [],\n conflicts: [],\n recommendations: [],\n integrationStrategy: 'script',\n compatibilityMode: 'modern'\n };\n }\n\n /**\n * Get service statistics\n */\n getStats() {\n return {\n cacheSize: this.cache.size,\n config: {\n model: this.config.openaiModel,\n maxTokens: this.config.maxTokens,\n temperature: this.config.temperature,\n caching: this.config.enableCaching\n },\n openaiAvailable: !!this.openai\n };\n }\n\n /**\n * Clear cache\n */\n clearCache() {\n this.cache.clear();\n }\n}\n\n/**\n * Express.js server implementation\n */\nexport function createAIServiceServer(config: CentralizedAIServiceConfig) {\n const express = require('express');\n const app = express();\n const aiService = new CentralizedAIService(config);\n\n app.use(express.json());\n\n // Health check endpoint\n app.get('/health', (req: any, res: any) => {\n res.json({ status: 'healthy', stats: aiService.getStats() });\n });\n\n // Analysis endpoint\n app.post('/analyze', async (req: any, res: any) => {\n try {\n const { codeSamples, projectType, userAgent } = req.body;\n \n if (!codeSamples || !Array.isArray(codeSamples)) {\n return res.status(400).json({ error: 'codeSamples array is required' });\n }\n\n const startTime = Date.now();\n const analysis = await aiService.analyzeCodePatterns(codeSamples);\n const processingTime = Date.now() - startTime;\n\n res.json({\n analysis,\n processingTime,\n modelUsed: config.openaiModel || 'heuristic'\n });\n } catch (error) {\n res.status(500).json({ error: 'Analysis failed', details: error instanceof Error ? error.message : 'Unknown error' });\n }\n });\n\n // Conflict resolution endpoint\n app.post('/resolve-conflicts', async (req: any, res: any) => {\n try {\n const { conflicts, framework } = req.body;\n \n if (!conflicts || !framework) {\n return res.status(400).json({ error: 'conflicts and framework are required' });\n }\n\n const resolutions = await aiService.resolveConflicts(conflicts, framework);\n res.json({ resolutions });\n } catch (error) {\n res.status(500).json({ error: 'Conflict resolution failed', details: error instanceof Error ? error.message : 'Unknown error' });\n }\n });\n\n // Optimization endpoint\n app.post('/optimize', async (req: any, res: any) => {\n try {\n const { framework, patterns } = req.body;\n \n if (!framework || !patterns) {\n return res.status(400).json({ error: 'framework and patterns are required' });\n }\n\n const optimizations = await aiService.generateOptimizations(framework, patterns);\n res.json({ optimizations });\n } catch (error) {\n res.status(500).json({ error: 'Optimization failed', details: error instanceof Error ? error.message : 'Unknown error' });\n }\n });\n\n return app;\n}\n\n/**\n * AWS Lambda handler\n */\nexport async function lambdaHandler(event: any, context: any) {\n const config: CentralizedAIServiceConfig = {\n openaiApiKey: process.env.OPENAI_API_KEY!,\n openaiModel: process.env.OPENAI_MODEL || 'gpt-4',\n maxTokens: parseInt(process.env.MAX_TOKENS || '2000'),\n temperature: parseFloat(process.env.TEMPERATURE || '0.3'),\n enableCaching: process.env.ENABLE_CACHING !== 'false',\n cacheTTL: parseInt(process.env.CACHE_TTL || '3600')\n };\n\n const aiService = new CentralizedAIService(config);\n\n try {\n const { path, httpMethod, body } = event;\n const parsedBody = body ? JSON.parse(body) : {};\n\n switch (path) {\n case '/analyze':\n if (httpMethod !== 'POST') {\n return { statusCode: 405, body: JSON.stringify({ error: 'Method not allowed' }) };\n }\n \n const analysis = await aiService.analyzeCodePatterns(parsedBody.codeSamples || []);\n return {\n statusCode: 200,\n body: JSON.stringify({ analysis })\n };\n\n case '/resolve-conflicts':\n if (httpMethod !== 'POST') {\n return { statusCode: 405, body: JSON.stringify({ error: 'Method not allowed' }) };\n }\n \n const resolutions = await aiService.resolveConflicts(\n parsedBody.conflicts || [],\n parsedBody.framework || { name: 'vanilla', type: 'vanilla' }\n );\n return {\n statusCode: 200,\n body: JSON.stringify({ resolutions })\n };\n\n default:\n return { statusCode: 404, body: JSON.stringify({ error: 'Not found' }) };\n }\n } catch (error) {\n return {\n statusCode: 500,\n body: JSON.stringify({ error: 'Internal server error', details: error instanceof Error ? error.message : 'Unknown error' })\n };\n }\n} "],"names":["MIN_SUPPORTED_SDK_VERSION","TESTED_SDK_VERSION","AutoInstallationWizard","constructor","apiKey","projectRoot","process","cwd","options","this","framework","manualNotes","path","resolve","setAgentPlan","agentPlan","compareVersions","version1","version2","v1Parts","split","map","Number","v2Parts","i","Math","max","length","v1","v2","isVersionGte","version","target","getMajorVersion","parseInt","install","detectFramework","installPlan","installPackage","modifications","generateModifications","dryRun","applyModifications","nextSteps","generateNextSteps","success","errors","error","name","type","Error","message","packageJsonPath","join","fs","existsSync","packageJson","JSON","parse","readFileSync","dependencies","devDependencies","features","nuxt","nuxtVersion","isNuxt3","majorVersion","hasTypeScript","typescript","hasRouter","hasNuxt3","next","nextVersion","isNext13","hasNextAppRouter","remixVersion","react","reactVersion","isReact18","hasReact18","vue","vueVersion","isVue3","hasVue3","angularVersion","isAngular17","hasAngularStandalone","svelte","svelteVersion","isSvelteKit","hasSvelteKit","astro","astroVersion","gatsby","gatsbyVersion","vite","bundler","webpack","esbuild","rollup","packageManager","detectPackageManager","plan","planPackageInstall","shouldInstall","skipInstall","execSync","command","stdio","workspaceRoot","findWorkspaceRoot","readPackageJson","packageName","installedVersion","getInstalledSDKVersion","alreadyInstalled","undefined","versionStatus","getSDKVersionStatus","isWorkspace","targetRef","relative","upgrade","buildInstallCommand","targetPackagePath","minimumSupportedVersion","testedVersion","reason","getInstallPlanReason","sdkPackage","shellQuote","startDir","root","lockfileChecks","dir","lockfile","startsWith","current","bestRoot","hasWorkspacePackageJson","Array","isArray","workspaces","packages","hasPnpmWorkspace","parent","dirname","dependencyFields","field","normalized","extractSemver","versionRange","match","value","test","replace","push","generateReactModifications","generateNextJSModifications","generateNuxtModifications","generateAstroModifications","generateGatsbyModifications","generateRemixModifications","generateVueModifications","generateAngularModifications","generateSvelteModifications","generateVanillaModifications","appFile","findReactAppFile","content","modifiedContent","injectReactProvider","filePath","action","description","createEnvironmentModification","mergeProvidersFile","hbProviderContent","existingContent","includes","trimmed","trimEnd","appLayoutFileWithSrc","appLayoutFile","pagesLayoutFileWithSrc","pagesLayoutFile","actualAppLayoutFile","providersFilePath","providersImportPath","providersContent","fileExists","injectNextJSAppRouter","actualPagesLayoutFile","providersPath","importPath","injectNextJSPagesRouter","astroComponentPath","layoutFiles","layoutFile","file","injectAstroLayout","pluginFile","nuxtConfigFile","mod","applyOrNotify","c","injectNuxtConfig","rootFile","injectRemixProvider","mainFile","findVueMainFile","composableDir","composablePath","injectVuePlugin","serviceDir","servicePath","envFile","envProdFile","appComponentPath","appContent","modifiedAppContent","svelteConfigFile","injectSvelteKitLayout","findSvelteMainFile","injectSvelteStore","htmlFile","findHTMLFile","injectVanillaScript","gatsbyBrowserFile","injectGatsbyBrowser","snapshots","modification","existed","mkdirSync","recursive","writeFileSync","appendFileSync","rollbackModifications","snapshot","reverse","rmSync","force","steps","n","transform","manualNote","original","updated","possibleFiles","fullPath","endsWith","envVar","importStatement","bodyAttrs","bodyContent","trim","isVue3ByContent","importComposable","lastImportIndex","lastIndexOf","nextLineIndex","indexOf","slice","trackerImport","injectAngularModule","injectAngularStandaloneInit","envImport","hbImport","browserImport","initCode","initScript","frontmatterEndIndex","bodyCloseIndex","pattern","replaced","startIdx","braceIdx","insertion","injectGatsbyLayout","modified","findBestEnvFile","possibleEnvFiles","envVarName","nextjs","angular","remix","vanilla","node","auto","getEnvVarName","defaultFile","cleanApiKey","basename","DefaultAIService","analyzeCodePatterns","codeSamples","analyzeWithHeuristics","resolveConflicts","conflicts","resolutions","conflict","generateOptimizations","patterns","optimizations","toLowerCase","confidence","integrationStrategy","compatibilityMode","recommendations","AIEnhancedInstallationWizard","aiService","super","learningCache","Map","patternDatabase","loadLearningData","aiAnalysis","performAICodeAnalysis","detectFrameworkWithAI","generateAIOptimizedModifications","applyModificationsWithAI","generateAINextSteps","learnFromInstallation","learningData","projectFiles","scanProjectFiles","extractCodeSamples","files","scanDir","depth","items","readdirSync","item","stat","statSync","isDirectory","isFile","isRelevantFile","filename","some","ext","samples","relativePath","extractCodePatterns","frameworkPatterns","regexes","Object","entries","regex","matches","toUpperCase","importMatches","exportMatches","traditionalFramework","enhancedModifications","enhanceModificationWithAI","aiOptimizations","generateAIOptimizations","enhancedContent","detectConflicts","resolvedModification","applyModification","resolvedContent","round","forEach","rec","timestamp","Date","toISOString","set","now","has","get","saveLearningData","getAIInsights","frameworkName","getLearningStats","stats","totalInstallations","size","frameworks","data","AIBrowserInstallationWizard","performBrowserAIAnalysis","generateAIBrowserModifications","detectBrowserFramework","analyzeBrowserPatterns","window","React","Vue","document","querySelector","querySelectorAll","script","src","RemoteAIService","config","timeout","response","fetch","apiEndpoint","method","headers","body","stringify","signal","AbortSignal","ok","status","statusText","json","analysis","console","warn","performHeuristicAnalysis","resolveConflictsHeuristic","generateOptimizationsHeuristic","ManualFrameworkInstallationWizard","selectedFramework","createFrameworkInfo","runFullDetection","detectedFramework","generateManualNextSteps","manualMode","tempWizard","substring","nuxtjs","sveltekit","getIntegrationStrategy","AGENT_PLAN_SCHEMA","properties","summary","recommendedChecks","risks","minimum","maximum","required","additionalProperties","async","runClaudeAgentInstaller","prompt","resultText","query","permissionMode","allowedTools","disallowedTools","maxTurns","outputFormat","schema","persistSession","subtype","result","validateAgentPlan","runClaudeAgentFullFlow","listProjectFiles","snapshotProject","canUseTool","toolName","input","String","installCommand","isAllowedBash","behavior","rolledBack","currentFiles","Set","restoreProject","rawResult","parsed","every","out","ignored","walk","entry","AIAutoInstallCLI","run","clack","intro","getApiKey","cancel","exit","projectPath","chooseFramework","yes","confirmInstallation","spinner","start","wizard","agent","detected","agentResult","agentApply","outro","writeReport","note","stop","displayResults","apiKeyFile","env","HB_API_KEY","text","placeholder","validate","confirm","select","label","reportJson","report","schemaVersion","showHelp","log","url","argv","args","arg","parseArgs","catch","AutoInstallCLI","CentralizedAIService","cache","openaiModel","maxTokens","temperature","enableCaching","cacheTTL","initializeOpenAI","OpenAI","require","openai","openaiApiKey","request","cacheKey","generateCacheKey","cached","isCacheValid","performAIAnalysis","codeContext","buildConflictResolutionPrompt","chat","completions","create","model","messages","role","max_tokens","choices","parseConflictResolutions","projectContext","buildOptimizationPrompt","parseOptimizations","buildAnalysisPrompt","response_format","parseAnalysisResult","getDefaultAnalysis","Buffer","from","toString","getStats","cacheSize","caching","openaiAvailable","clearCache","clear"],"mappings":"6KAWA,MAAMA,EAA4B,QAC5BC,EAAqB,cA2EdC,EAOX,WAAAC,CAAYC,EAAgBC,EAAsBC,QAAQC,MAAOC,EAAqC,IAJ5FC,KAAAC,UAAkC,KAEpCD,KAAAE,YAAwB,GAG9BF,KAAKL,OAASA,EACdK,KAAKJ,YAAcO,EAAKC,QAAQR,GAChCI,KAAKD,QAAUA,CACjB,CAEO,YAAAM,CAAaC,GAClBN,KAAKD,QAAQO,UAAYA,CAC3B,CAKQ,eAAAC,CAAgBC,EAAkBC,GACxC,MAAMC,EAAUF,EAASG,MAAM,KAAKC,IAAIC,QAClCC,EAAUL,EAASE,MAAM,KAAKC,IAAIC,QAExC,IAAK,IAAIE,EAAI,EAAGA,EAAIC,KAAKC,IAAIP,EAAQQ,OAAQJ,EAAQI,QAASH,IAAK,CACjE,MAAMI,EAAKT,EAAQK,IAAM,EACnBK,EAAKN,EAAQC,IAAM,EACzB,GAAII,EAAKC,EAAI,OAAO,EACpB,GAAID,EAAKC,EAAI,OAAO,CACtB,CACA,OAAO,CACT,CAEQ,YAAAC,CAAaC,EAAiBC,GACpC,OAAOvB,KAAKO,gBAAgBe,EAASC,IAAW,CAClD,CAEQ,eAAAC,CAAgBF,GACtB,OAAOG,SAASH,EAAQX,MAAM,KAAK,KAAO,CAC5C,CAKA,aAAMe,GACJ,IAEE1B,KAAKC,gBAAkBD,KAAK2B,kBAG5B,MAAMC,QAAoB5B,KAAK6B,iBAGzBC,QAAsB9B,KAAK+B,wBAC5B/B,KA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