humanbehavior-js 0.7.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- "use strict";var e=require("fs"),t=require("path"),n=require("child_process"),i=require("@clack/prompts"),r="undefined"!=typeof document?document.currentScript:null;function a(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var o=a(e),s=a(t),c=a(i);class u{constructor(e,t=process.cwd()){this.framework=null,this.manualNotes=[],this.apiKey=e,this.projectRoot=t}compareVersions(e,t){const n=e.split(".").map(Number),i=t.split(".").map(Number);for(let e=0;e<Math.max(n.length,i.length);e++){const t=n[e]||0,r=i[e]||0;if(t>r)return 1;if(t<r)return-1}return 0}isVersionGte(e,t){return this.compareVersions(e,t)>=0}getMajorVersion(e){return parseInt(e.split(".")[0])||0}async install(){try{this.framework=await this.detectFramework(),await this.installPackage();const e=await this.generateModifications();await this.applyModifications(e);const t=this.generateNextSteps();return{success:!0,framework:this.framework,modifications:e,errors:[],nextSteps:t}}catch(e){return{success:!1,framework:this.framework||{name:"unknown",type:"vanilla"},modifications:[],errors:[e instanceof Error?e.message:"Unknown error"],nextSteps:[]}}}async detectFramework(){const e=s.join(this.projectRoot,"package.json");if(!o.existsSync(e))return{name:"vanilla",type:"vanilla",projectRoot:this.projectRoot};const t=JSON.parse(o.readFileSync(e,"utf8")),n={...t.dependencies,...t.devDependencies};let i={name:"vanilla",type:"vanilla",projectRoot:this.projectRoot,features:{}};if(n.nuxt){const e=n.nuxt,t=this.isVersionGte(e,"3.0.0");i={name:"nuxt",type:"nuxt",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!n.typescript,hasRouter:!0,projectRoot:this.projectRoot,features:{hasNuxt3:t}}}else if(n.next){const e=n.next,t=this.isVersionGte(e,"13.0.0");i={name:"nextjs",type:"nextjs",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!n.typescript||!!n["@types/node"],hasRouter:!0,projectRoot:this.projectRoot,features:{hasNextAppRouter:t}}}else if(n["@remix-run/react"]||n["@remix-run/dev"]){const e=n["@remix-run/react"]||n["@remix-run/dev"];i={name:"remix",type:"remix",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!n.typescript||!!n["@types/react"],hasRouter:!0,projectRoot:this.projectRoot,features:{}}}else if(n.react){const e=n.react,t=this.isVersionGte(e,"18.0.0");i={name:"react",type:"react",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!n.typescript||!!n["@types/react"],hasRouter:!!n["react-router-dom"]||!!n["react-router"],projectRoot:this.projectRoot,features:{hasReact18:t}}}else if(n.vue){const e=n.vue,t=this.isVersionGte(e,"3.0.0");i={name:"vue",type:"vue",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!n.typescript||!!n["@vue/cli-service"],hasRouter:!!n["vue-router"],projectRoot:this.projectRoot,features:{hasVue3:t}}}else if(n["@angular/core"]){const e=n["@angular/core"],t=this.isVersionGte(e,"17.0.0");i={name:"angular",type:"angular",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!0,hasRouter:!0,projectRoot:this.projectRoot,features:{hasAngularStandalone:t}}}else if(n.svelte){const e=n.svelte,t=!!n["@sveltejs/kit"];i={name:"svelte",type:"svelte",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!n.typescript||!!n["svelte-check"],hasRouter:!!n["svelte-routing"]||!!n["@sveltejs/kit"],projectRoot:this.projectRoot,features:{hasSvelteKit:t}}}else if(n.astro){const e=n.astro;i={name:"astro",type:"astro",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!n.typescript||!!n["@astrojs/ts-plugin"],hasRouter:!0,projectRoot:this.projectRoot,features:{}}}else if(n.gatsby){const e=n.gatsby;i={name:"gatsby",type:"gatsby",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!n.typescript||!!n["@types/react"],hasRouter:!0,projectRoot:this.projectRoot,features:{}}}return n.vite?i.bundler="vite":n.webpack?i.bundler="webpack":n.esbuild?i.bundler="esbuild":n.rollup&&(i.bundler="rollup"),o.existsSync(s.join(this.projectRoot,"yarn.lock"))?i.packageManager="yarn":o.existsSync(s.join(this.projectRoot,"pnpm-lock.yaml"))?i.packageManager="pnpm":i.packageManager="npm",i}async installPackage(){let e="yarn"===this.framework?.packageManager?"yarn add humanbehavior-js@latest":"pnpm"===this.framework?.packageManager?"pnpm add humanbehavior-js@latest":"npm install humanbehavior-js@latest";"yarn"!==this.framework?.packageManager&&"pnpm"!==this.framework?.packageManager&&(e+=" --legacy-peer-deps");try{n.execSync(e,{cwd:this.projectRoot,stdio:"inherit"})}catch(e){throw new Error(`Failed to install humanbehavior-js: ${e}`)}}async generateModifications(){const e=[];switch(this.framework?.type){case"react":e.push(...await this.generateReactModifications());break;case"nextjs":e.push(...await this.generateNextJSModifications());break;case"nuxt":e.push(...await this.generateNuxtModifications());break;case"astro":e.push(...await this.generateAstroModifications());break;case"gatsby":e.push(...await this.generateGatsbyModifications());break;case"remix":e.push(...await this.generateRemixModifications());break;case"vue":e.push(...await this.generateVueModifications());break;case"angular":e.push(...await this.generateAngularModifications());break;case"svelte":e.push(...await this.generateSvelteModifications());break;default:e.push(...await this.generateVanillaModifications())}return e}async generateReactModifications(){const e=[],t=this.findReactAppFile();if(t){const n=o.readFileSync(t,"utf8"),i=this.injectReactProvider(n,t);e.push({filePath:t,action:"modify",content:i,description:"Added HumanBehaviorProvider to React app"})}return e.push(this.createEnvironmentModification(this.framework)),e}mergeProvidersFile(e){const t="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}";if(!o.existsSync(e))return`'use client';\n\nimport { HumanBehaviorProvider } from 'humanbehavior-js/react';\n\n${t}`;const n=o.readFileSync(e,"utf8");if(n.includes("export function HBProvider")||n.includes("export const HBProvider"))return n;let i=n;n.includes("from 'humanbehavior-js/react'")||(i=n.includes("'use client'")?n.replace(/('use client';?)\s*\n/,"$1\n\nimport { HumanBehaviorProvider } from 'humanbehavior-js/react';\n"):`import { HumanBehaviorProvider } from 'humanbehavior-js/react';\n\n${n}`);const r=i.trimEnd();return i=""===r?t:`${r}\n\n${t}`,i}async generateNextJSModifications(){const e=[],t=s.join(this.projectRoot,"src","app","layout.tsx"),n=s.join(this.projectRoot,"app","layout.tsx"),i=s.join(this.projectRoot,"src","pages","_app.tsx"),r=s.join(this.projectRoot,"pages","_app.tsx");let a=null,c=null,u=null;if(o.existsSync(t)?(a=t,c=s.join(this.projectRoot,"src","app","providers.tsx"),u="@/app/providers"):o.existsSync(n)&&(a=n,c=s.join(this.projectRoot,"app","providers.tsx"),u="@/app/providers"),a){const t=this.mergeProvidersFile(c),n=o.existsSync(c);e.push({filePath:c,action:n?"modify":"create",content:t,description:n?"Merged HBProvider into existing providers.tsx file":"Created providers.tsx file with HBProvider for Next.js App Router"});const i=o.readFileSync(a,"utf8"),r=this.injectNextJSAppRouter(i,u);e.push({filePath:a,action:"modify",content:r,description:"Added HumanBehavior provider wrapper to Next.js App Router layout"})}else if(o.existsSync(i)||o.existsSync(r)){const t=o.existsSync(i)?i:r,n=o.existsSync(i)?s.join(this.projectRoot,"src","components","HumanBehaviorProvider.tsx"):s.join(this.projectRoot,"components","HumanBehaviorProvider.tsx"),a=o.existsSync(i)?"../components/HumanBehaviorProvider":"./components/HumanBehaviorProvider";e.push({filePath:n,action:"create",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}",description:"Created HumanBehavior provider file for Pages Router"});const c=o.readFileSync(t,"utf8"),u=this.injectNextJSPagesRouter(c,a);e.push({filePath:t,action:"modify",content:u,description:"Added HumanBehavior provider wrapper to Next.js Pages Router"})}return e.push(this.createEnvironmentModification(this.framework)),e}async generateAstroModifications(){const e=[],t=s.join(this.projectRoot,"src","components","HumanBehavior.astro");e.push({filePath:t,action:"create",content:"---\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>",description:"Created Astro component for HumanBehavior SDK"});const n=[s.join(this.projectRoot,"src","layouts","Layout.astro"),s.join(this.projectRoot,"src","layouts","layout.astro"),s.join(this.projectRoot,"src","layouts","BaseLayout.astro")];let i=null;for(const e of n)if(o.existsSync(e)){i=e;break}if(i){const t=o.readFileSync(i,"utf8"),n=this.injectAstroLayout(t);e.push({filePath:i,action:"modify",content:n,description:"Added HumanBehavior component to Astro layout"})}return e.push(this.createEnvironmentModification(this.framework)),e}async generateNuxtModifications(){const e=[],t=s.join(this.projectRoot,"app","plugins","humanbehavior.client.ts");e.push({filePath:t,action:"create",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});",description:"Created Nuxt plugin for HumanBehavior SDK in app directory"});const n=s.join(this.projectRoot,"nuxt.config.ts");{const t=this.applyOrNotify(n,e=>this.injectNuxtConfig(e),"Added HumanBehavior runtime config to Nuxt config","Nuxt: Add inside defineNuxtConfig({ … }):\nruntimeConfig: { public: { humanBehaviorApiKey: process.env.NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY } },");t&&e.push(t)}return e.push(this.createEnvironmentModification(this.framework)),e}async generateRemixModifications(){const e=[],t=s.join(this.projectRoot,"app","root.tsx");if(o.existsSync(t)){const n=o.readFileSync(t,"utf8"),i=this.injectRemixProvider(n);e.push({filePath:t,action:"modify",content:i,description:"Added HumanBehaviorProvider to Remix root component"})}return e.push(this.createEnvironmentModification(this.framework)),e}async generateVueModifications(){const e=[],t=this.findVueMainFile(),n=s.join(this.projectRoot,"src","composables"),i=s.join(n,"useHumanBehavior.ts");try{o.existsSync(n)||o.mkdirSync(n,{recursive:!0}),o.existsSync(i)||e.push({filePath:i,action:"create",content:"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",description:"Created Vue composable useHumanBehavior"})}catch{}if(t){const n=o.readFileSync(t,"utf8"),i=this.injectVuePlugin(n);e.push({filePath:t,action:"modify",content:i,description:"Added HumanBehaviorPlugin to Vue app"})}return e.push(this.createEnvironmentModification(this.framework)),e}async generateAngularModifications(){const e=[],t=s.join(this.projectRoot,"src","app","services"),n=s.join(t,"hb.service.ts");o.existsSync(t)||o.mkdirSync(t,{recursive:!0}),o.existsSync(n)||e.push({filePath:n,action:"create",content:"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",description:"Created Angular HumanBehavior service (singleton)"});const i=s.join(this.projectRoot,"src","environments","environment.ts"),r=s.join(this.projectRoot,"src","environments","environment.prod.ts"),a=s.dirname(i);if(o.existsSync(a)||o.mkdirSync(a,{recursive:!0}),o.existsSync(i)){const t=o.readFileSync(i,"utf8");if(!t.includes("humanBehaviorApiKey")){const n=t.replace(/export const environment = {([\s\S]*?)};/,`export const environment = {\n $1,\n humanBehaviorApiKey: '${this.apiKey}'\n};`);e.push({filePath:i,action:"modify",content:n,description:"Added API key to Angular development environment"})}}else e.push({filePath:i,action:"create",content:`export const environment = {\n production: false,\n humanBehaviorApiKey: '${this.apiKey}'\n};`,description:"Created Angular development environment file"});if(o.existsSync(r)){const t=o.readFileSync(r,"utf8");if(!t.includes("humanBehaviorApiKey")){const n=t.replace(/export const environment = {([\s\S]*?)};/,`export const environment = {\n $1,\n humanBehaviorApiKey: '${this.apiKey}'\n};`);e.push({filePath:r,action:"modify",content:n,description:"Added API key to Angular production environment"})}}else e.push({filePath:r,action:"create",content:`export const environment = {\n production: true,\n humanBehaviorApiKey: '${this.apiKey}'\n};`,description:"Created Angular production environment file"});const c=s.join(this.projectRoot,"src","app","app.ts");if(o.existsSync(c)){const t=o.readFileSync(c,"utf8");if(!t.includes("HumanBehavior")){let n=t.replace(/import { Component } from '@angular\/core';/,"import { Component } from '@angular/core';\nimport { HumanBehavior } from './services/hb.service';").replace(/export class App {/,"export class App {\n constructor(private readonly humanBehavior: HumanBehavior) {}");e.push({action:"modify",filePath:c,content:n,description:"Injected HumanBehavior service into Angular app component"})}}return e}async generateSvelteModifications(){const e=[],t=s.join(this.projectRoot,"svelte.config.js");if(o.existsSync(t)){const t=s.join(this.projectRoot,"src","routes","+layout.svelte");if(o.existsSync(t)){const n=o.readFileSync(t,"utf8"),i=this.injectSvelteKitLayout(n);e.push({filePath:t,action:"modify",content:i,description:"Added HumanBehavior tracker init to SvelteKit layout"})}}else{const t=this.findSvelteMainFile();if(t){const n=o.readFileSync(t,"utf8"),i=this.injectSvelteStore(n);e.push({filePath:t,action:"modify",content:i,description:"Added HumanBehavior tracker init to Svelte app"})}}return e.push(this.createEnvironmentModification(this.framework)),e}async generateVanillaModifications(){const e=[],t=this.findHTMLFile();if(t){const n=o.readFileSync(t,"utf8"),i=this.injectVanillaScript(n);e.push({filePath:t,action:"modify",content:i,description:"Added HumanBehavior CDN script to HTML file"})}return e.push(this.createEnvironmentModification(this.framework)),e}async generateGatsbyModifications(){const e=[],t=s.join(this.projectRoot,"gatsby-browser.js");if(o.existsSync(t)){const n=o.readFileSync(t,"utf8"),i=this.injectGatsbyBrowser(n);e.push({filePath:t,action:"modify",content:i,description:"Added HumanBehavior initialization to Gatsby browser"})}else e.push({filePath:t,action:"create",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};",description:"Created gatsby-browser.js with HumanBehavior initialization"});return e.push(this.createEnvironmentModification(this.framework)),e}async applyModifications(e){for(const t of e)try{const e=s.dirname(t.filePath);switch(o.existsSync(e)||o.mkdirSync(e,{recursive:!0}),t.action){case"create":case"modify":o.writeFileSync(t.filePath,t.content);break;case"append":o.appendFileSync(t.filePath,"\n"+t.content)}}catch(e){throw new Error(`Failed to apply modification to ${t.filePath}: ${e}`)}}generateNextSteps(){const e=["✅ SDK installed and configured automatically!","🚀 Your app is now tracking user behavior","📊 View sessions in your HumanBehavior dashboard","🔧 Customize tracking in your code as needed"];return"react"!==this.framework?.type&&"nextjs"!==this.framework?.type||e.push("💡 Use the useHumanBehavior() hook to track custom events"),this.manualNotes.length&&e.push(...this.manualNotes.map(e=>`⚠️ ${e}`)),e}applyOrNotify(e,t,n,i){if(!o.existsSync(e))return this.manualNotes.push(`${i} (file missing: ${s.relative(this.projectRoot,e)})`),null;const r=o.readFileSync(e,"utf8"),a=t(r);return a!==r?{filePath:e,action:"modify",content:a,description:n}:(this.manualNotes.push(i),null)}findReactAppFile(){const e=["src/App.jsx","src/App.js","src/App.tsx","src/App.ts","src/index.js","src/index.tsx","src/main.js","src/main.tsx"];for(const t of e){const e=s.join(this.projectRoot,t);if(o.existsSync(e))return e}return null}findVueMainFile(){const e=["src/main.js","src/main.ts","src/main.jsx","src/main.tsx"];for(const t of e){const e=s.join(this.projectRoot,t);if(o.existsSync(e))return e}return null}findSvelteMainFile(){const e=["src/main.js","src/main.ts","src/main.svelte"];for(const t of e){const e=s.join(this.projectRoot,t);if(o.existsSync(e))return e}return null}findHTMLFile(){const e=["index.html","public/index.html","dist/index.html"];for(const t of e){const e=s.join(this.projectRoot,t);if(o.existsSync(e))return e}return null}injectReactProvider(e,t){if(t.endsWith(".tsx")||t.endsWith(".ts"),e.includes("HumanBehaviorProvider"))return e;const n="vite"===this.framework?.bundler?"import.meta.env.VITE_HUMANBEHAVIOR_API_KEY!":"process.env.REACT_APP_HUMANBEHAVIOR_API_KEY!",i="import { HumanBehaviorProvider } from 'humanbehavior-js/react';",r=this.framework?.features?.hasReact18;if(e.includes("function App()")||e.includes("const App =")){let t=e.replace(/(import.*?from.*?['"]react['"];?)/,`$1\n${i}`);return t.includes(i)||(t=`${i}\n\n${t}`),t=t.replace(/return\s*\(([\s\S]*?)\)\s*;/,`return (\n <HumanBehaviorProvider apiKey={${n}}>\n $1\n </HumanBehaviorProvider>\n );`),t}if(r&&e.includes("createRoot")){let t=e.replace(/(import.*?from.*?['"]react['"];?)/,`$1\n${i}`);return t.includes(i)||(t=`${i}\n\n${t}`),t=t.replace(/(root\.render\s*\([\s\S]*?\)\s*;)/,`root.render(\n <HumanBehaviorProvider apiKey={${n}}>\n $1\n </HumanBehaviorProvider>\n );`),t}return`${i}\n\n${e}`}injectNextJSAppRouter(e,t="@/app/providers"){if(e.includes("HBProvider"))return e;const n=`import { HBProvider } from '${t}';`;let i=e.replace(/export default function RootLayout/,`${n}\n\nexport default function RootLayout`);return i=i.replace(/<body([^>]*)>([\s\S]*?)<\/body>/,(e,t,n)=>`<body${t}>\n <HBProvider>\n ${n.trim()}\n </HBProvider>\n </body>`),i}injectNextJSPagesRouter(e,t="../components/HumanBehaviorProvider"){if(e.includes("HBProvider"))return e;const n=`import { HBProvider } from '${t}';`;return e.replace(/function MyApp/,`${n}\n\nfunction MyApp`).replace(/return \(([\s\S]*?)\);/,"return (\n <HBProvider>\n $1\n </HBProvider>\n );")}injectRemixProvider(e){if(e.includes("HumanBehaviorProvider"))return e;let t=e;return e.includes("useLoaderData")||(t=t.replace(/(} from ['"]@remix-run\/react['"];?\s*)/,"$1import { useLoaderData } from '@remix-run/react';\n")),e.includes("HumanBehaviorProvider")||(t=t.replace(/(} from ['"]@remix-run\/react['"];?\s*)/,"$1import { HumanBehaviorProvider } from 'humanbehavior-js/react';\n")),e.includes("LoaderFunctionArgs")||(t=t.replace(/(} from ['"]@remix-run\/node['"];?\s*)/,"$1import type { LoaderFunctionArgs } from '@remix-run/node';\n")),e.includes("export const loader")||(t=t.replace(/(export function Layout)/,"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")),e.includes("const data = useLoaderData")||(t=t.replace(/(export default function App\(\) \{\s*)(return \(\s*<div[^>]*>[\s\S]*?<\/div>\s*\);\s*\})/,'$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}')),t}injectVuePlugin(e){if(e.includes("useHumanBehavior"))return e;const t=this.framework?.features?.hasVue3,n=e.includes("createApp")||e.includes("import { createApp }");let i=e.replace(/import\s*\{\s*HumanBehaviorPlugin\s*\}\s*from\s*['\"]humanbehavior-js\/vue['\"];?/g,"").replace(/app\.use\(\s*HumanBehaviorPlugin[\s\S]*?\);?/g,"");if(t||n){const e="import { useHumanBehavior } from './composables/useHumanBehavior';";if(!i.includes(e)){const t=i.lastIndexOf("import");if(-1!==t){const n=i.indexOf("\n",t);i=-1!==n?i.slice(0,n+1)+e+"\n"+i.slice(n+1):i+"\n"+e}else i=e+"\n"+i}return i.includes("createApp")&&(i=i.replace(/(const\s+app\s*=\s*createApp\([^)]*\))/,"$1\nconst { tracker } = useHumanBehavior();")),i}{const e="import { HumanBehaviorTracker } from 'humanbehavior-js';";return i.includes(e)||(i=`${e}\n${i}`),i.includes("new Vue")&&(i=i.replace(/(new\s+Vue\s*\()/,"HumanBehaviorTracker.init(process.env.VUE_APP_HUMANBEHAVIOR_API_KEY || import.meta?.env?.VITE_HUMANBEHAVIOR_API_KEY);\n$1")),i}}injectAngularModule(e){if(e.includes("HumanBehaviorModule"))return e;let t=e;return e.includes("environment")||(t=e.replace(/import.*from.*['"]@angular/,"import { environment } from '../environments/environment';\n$&")),t.replace(/imports:\s*\[([\s\S]*?)\]/,"imports: [\n $1,\n HumanBehaviorModule.forRoot({\n apiKey: environment.humanBehaviorApiKey\n })\n ]").replace(/import.*from.*['"]@angular/,"$&\nimport { HumanBehaviorModule } from 'humanbehavior-js/angular';")}injectAngularStandaloneInit(e){if(e.includes("initializeHumanBehavior"))return e;let t=e.replace(/import.*from.*['"]@angular/,"import { initializeHumanBehavior } from 'humanbehavior-js/angular';\nimport { environment } from './environments/environment';\n$&");return t=t.replace(/(bootstrapApplication\([^}]+\}?\)(?:\s*\.catch[^;]+;)?)/,"$1\n\n// Initialize HumanBehavior SDK (client-side only)\nif (typeof window !== 'undefined') {\n const tracker = initializeHumanBehavior(environment.humanBehaviorApiKey);\n}"),t}injectSvelteStore(e){if(e.includes("HumanBehaviorTracker.init"))return e;return`import { HumanBehaviorTracker } from 'humanbehavior-js';\n// Initialize HumanBehavior SDK\nHumanBehaviorTracker.init(import.meta.env?.VITE_HUMANBEHAVIOR_API_KEY || process.env.PUBLIC_HUMANBEHAVIOR_API_KEY || '');\n\n${e}`}injectSvelteKitLayout(e){if(e.includes("HumanBehaviorTracker.init"))return e;const t="import { PUBLIC_HUMANBEHAVIOR_API_KEY } from '$env/static/public';",n="import { HumanBehaviorTracker } from 'humanbehavior-js';",i="import { browser } from '$app/environment';",r="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}";return e.includes('<script lang="ts">')?e.replace(/<script lang="ts">/,`<script lang="ts">\n\t${i}\n\t${t}\n\t${n}\n\t${r}`):e.includes("<script>")?e.replace(/<script>/,`<script>\n\t${i}\n\t${t}\n\t${n}\n\t${r}`):`<script lang="ts">\n${i}\n${t}\n${n}\n${r}\n<\/script>\n\n${e}`}injectVanillaScript(e){if(e.includes("humanbehavior-js"))return e;const t=`<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>`;return e.replace(/<\/head>/,` <script src="https://unpkg.com/humanbehavior-js@latest/dist/index.min.js"><\/script>\n ${t}\n</head>`)}injectAstroLayout(e){if(e.includes("HumanBehavior")||e.includes("humanbehavior-js"))return e;let t=e;if(!e.includes("import HumanBehavior")){const n="import HumanBehavior from '../components/HumanBehavior.astro';",i=e.indexOf("---",3);t=-1!==i?e.slice(0,i)+"\n"+n+"\n"+e.slice(i):"---\n"+n+"\n---\n\n"+e}const n=t.lastIndexOf("</body>");return-1===n?t+"\n\n<HumanBehavior />":t.slice(0,n)+" <HumanBehavior />\n"+t.slice(n)}injectNuxtConfig(e){if(e.includes("humanBehaviorApiKey"))return e;const t=this.framework?.features?.hasNuxt3;if(t){const t=/export\s+default\s+defineNuxtConfig\s*\(\s*\{/;if(t.test(e)){const n=e.replace(t,"export default defineNuxtConfig({\n runtimeConfig: {\n public: {\n humanBehaviorApiKey: process.env.NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY\n }\n },");if(n!==e)return n}const n=e.indexOf("defineNuxtConfig(");if(-1!==n){const t=e.indexOf("{",n);if(-1!==t){const n="\n runtimeConfig: {\n public: {\n humanBehaviorApiKey: process.env.NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY\n }\n },";return`${e.slice(0,t+1)}${n}${e.slice(t+1)}`}}return e}return e.replace(/export default \{/,"export default {\n env: {\n humanBehaviorApiKey: process.env.HUMANBEHAVIOR_API_KEY\n },")}injectGatsbyLayout(e){if(e.includes("HumanBehavior"))return e;let t=e.replace(/import.*from.*['"]\./,"import HumanBehavior from './HumanBehavior';\n$&");return t=t.replace(/(\s*<\/body>)/,"\n <HumanBehavior apiKey={process.env.GATSBY_HUMANBEHAVIOR_API_KEY || ''} />\n$1"),t}injectGatsbyBrowser(e){const t="import { HumanBehaviorTracker } from 'humanbehavior-js';";if(/export\s+const\s+onClientEntry\s*=\s*\(/.test(e)){let n=e;return n.includes("from 'humanbehavior-js'")||(n=`${t}\n${n}`),n.includes("HumanBehaviorTracker.init(")?n:(n=n.replace(/(export\s+const\s+onClientEntry\s*=\s*\([^)]*\)\s*=>\s*\{)/,"$1\n const apiKey = process.env.GATSBY_HUMANBEHAVIOR_API_KEY;\n if (apiKey) {\n HumanBehaviorTracker.init(apiKey);\n }\n"),n)}return`${e.trim(),`${t}\n`}export const onClientEntry = () => {\n const apiKey = process.env.GATSBY_HUMANBEHAVIOR_API_KEY;\n if (apiKey) {\n HumanBehaviorTracker.init(apiKey);\n }\n};${e.trim()?`\n\n${e}`:""}`}findBestEnvFile(e){const t=[".env.local",".env.development.local",".env.development",".env.local.development",".env",".env.production",".env.staging"],n=(e=>{if("react"===e.type&&"vite"===e.bundler)return"VITE_HUMANBEHAVIOR_API_KEY";return{react:"REACT_APP_HUMANBEHAVIOR_API_KEY",nextjs:"NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY",vue:"VITE_HUMANBEHAVIOR_API_KEY",svelte:"PUBLIC_HUMANBEHAVIOR_API_KEY",angular:"HUMANBEHAVIOR_API_KEY",nuxt:"NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY",remix:"HUMANBEHAVIOR_API_KEY",vanilla:"HUMANBEHAVIOR_API_KEY",astro:"PUBLIC_HUMANBEHAVIOR_API_KEY",gatsby:"GATSBY_HUMANBEHAVIOR_API_KEY",node:"HUMANBEHAVIOR_API_KEY",auto:"HUMANBEHAVIOR_API_KEY"}[e.type]||"HUMANBEHAVIOR_API_KEY"})(e);for(const e of t){const t=s.join(this.projectRoot,e);if(o.existsSync(t))return{filePath:t,envVarName:n}}const i={react:".env.local",nextjs:".env.local",vue:".env.local",svelte:".env",angular:".env",nuxt:".env",remix:".env.local",vanilla:".env",astro:".env",gatsby:".env.development",node:".env",auto:".env"}[e.type]||".env";return{filePath:s.join(this.projectRoot,i),envVarName:n}}createEnvironmentModification(e){const{filePath:t,envVarName:n}=this.findBestEnvFile(e),i=this.apiKey.trim();if(o.existsSync(t)){const e=o.readFileSync(t,"utf8");return e.includes(n)?{filePath:t,action:"modify",content:e,description:`API key already exists in ${s.basename(t)}`}:{filePath:t,action:"append",content:`\n${n}=${i}`,description:`Added API key to existing ${s.basename(t)}`}}return{filePath:t,action:"create",content:`${n}=${i}`,description:`Created ${s.basename(t)} with API key`}}}class p{async analyzeCodePatterns(e){return this.analyzeWithHeuristics(e)}async resolveConflicts(e,t){const n=[];for(const t of e)switch(t){case"existing_humanbehavior_code":n.push("update_existing_integration");break;case"existing_provider":n.push("merge_providers");break;case"module_system_conflict":n.push("hybrid_module_support");break;default:n.push("skip_conflict")}return n}async generateOptimizations(e,t){const n=[];switch(e.type){case"react":n.push("Use React.memo for performance optimization"),n.push("Implement error boundaries for better error tracking"),n.push("Consider using React.lazy for code splitting");break;case"vue":n.push("Use Vue 3 Composition API for better performance"),n.push("Implement proper error handling in components"),n.push("Consider using Vue Router for navigation tracking");break;case"angular":n.push("Use Angular standalone components for better tree-shaking"),n.push("Implement proper error handling with ErrorHandler"),n.push("Consider using Angular signals for state management");break;default:n.push("Enable performance tracking"),n.push("Implement error tracking"),n.push("Consider progressive enhancement")}return n}analyzeWithHeuristics(e){const t=e.join(" ").toLowerCase();let n={name:"vanilla",type:"vanilla"},i=.5;t.includes("nuxt")||t.includes("nuxtjs")||t.includes("defineNuxtConfig")||t.includes("nuxt.config")||t.includes("@nuxt/")||t.includes("useNuxtApp")||t.includes("useRuntimeConfig")||t.includes("useSeoMeta")||t.includes("useHead")||t.includes("useLazyFetch")||t.includes("useFetch")||t.includes("useAsyncData")||t.includes("#app")?(n={name:"nuxt",type:"nuxt"},i=.95):t.includes("next")||t.includes("nextjs")||t.includes("next/link")||t.includes("next/image")||t.includes("next/navigation")||t.includes("next/router")||t.includes("getserverSideProps")||t.includes("getstaticProps")||t.includes("getstaticPaths")||t.includes("app/layout")||t.includes("app/page")||t.includes("pages/")?(n={name:"nextjs",type:"nextjs"},i=.95):t.includes("gatsby")||t.includes("gatsby-browser")||t.includes("gatsby-ssr")||t.includes("gatsby-node")||t.includes("gatsby-config")||t.includes("useStaticQuery")||t.includes("graphql")?(n={name:"gatsby",type:"gatsby"},i=.95):t.includes("react")?(n={name:"react",type:"react"},i=.9):t.includes("vue")?(n={name:"vue",type:"vue"},i=.9):t.includes("angular")?(n={name:"angular",type:"angular"},i=.9):t.includes("svelte")&&(n={name:"svelte",type:"svelte"},i=.9);let r="script";"react"===n.type||"nextjs"===n.type||"gatsby"===n.type?r="provider":"vue"===n.type?r="plugin":"angular"===n.type&&(r="module");let a="modern";return(t.includes("require(")||t.includes("var "))&&(a="legacy"),{framework:n,confidence:i,patterns:e,conflicts:[],recommendations:[],integrationStrategy:r,compatibilityMode:a}}}class l{constructor(e){this.config={timeout:1e4,...e}}async analyzeCodePatterns(e){try{const t=await fetch(`${this.config.apiEndpoint}/analyze`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({codeSamples:e}),signal:AbortSignal.timeout(this.config.timeout||1e4)});if(!t.ok)throw new Error(`AI service returned ${t.status}: ${t.statusText}`);return(await t.json()).analysis}catch(t){return console.warn("Remote AI service failed, falling back to heuristic analysis:",t),this.performHeuristicAnalysis(e)}}async resolveConflicts(e,t){try{const n=await fetch(`${this.config.apiEndpoint}/resolve-conflicts`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({conflicts:e,framework:t}),signal:AbortSignal.timeout(this.config.timeout||1e4)});if(!n.ok)throw new Error(`AI service returned ${n.status}: ${n.statusText}`);return(await n.json()).resolutions||[]}catch(n){return console.warn("Remote AI conflict resolution failed, using heuristic approach:",n),this.resolveConflictsHeuristic(e,t)}}async generateOptimizations(e,t){try{const n=await fetch(`${this.config.apiEndpoint}/optimize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({framework:e,patterns:t}),signal:AbortSignal.timeout(this.config.timeout||1e4)});if(!n.ok)throw new Error(`AI service returned ${n.status}: ${n.statusText}`);return(await n.json()).optimizations||[]}catch(n){return console.warn("Remote AI optimization generation failed, using heuristic approach:",n),this.generateOptimizationsHeuristic(e,t)}}performHeuristicAnalysis(e){const t=e.join(" ").toLowerCase();let n={name:"vanilla",type:"vanilla"},i=.5;t.includes("nuxt")||t.includes("nuxtjs")||t.includes("defineNuxtConfig")||t.includes("nuxt.config")||t.includes("@nuxt/")||t.includes("useNuxtApp")||t.includes("useRuntimeConfig")||t.includes("useSeoMeta")||t.includes("useHead")||t.includes("useLazyFetch")||t.includes("useFetch")||t.includes("useAsyncData")||t.includes("#app")?(n={name:"nuxt",type:"nuxt"},i=.95):t.includes("next")||t.includes("nextjs")||t.includes("next/link")||t.includes("next/image")||t.includes("next/navigation")||t.includes("next/router")||t.includes("getserverSideProps")||t.includes("getstaticProps")||t.includes("getstaticPaths")||t.includes("app/layout")||t.includes("app/page")||t.includes("pages/")?(n={name:"nextjs",type:"nextjs"},i=.95):t.includes("gatsby")||t.includes("gatsby-browser")||t.includes("gatsby-ssr")||t.includes("gatsby-node")||t.includes("gatsby-config")||t.includes("useStaticQuery")||t.includes("graphql")?(n={name:"gatsby",type:"gatsby"},i=.95):t.includes("react")?(n={name:"react",type:"react"},i=.9):t.includes("vue")?(n={name:"vue",type:"vue"},i=.9):t.includes("angular")?(n={name:"angular",type:"angular"},i=.9):t.includes("svelte")?(n={name:"svelte",type:"svelte"},i=.9):t.includes("astro")&&(n={name:"astro",type:"astro"},i=.9);let r="script";"react"===n.type||"nextjs"===n.type||"gatsby"===n.type?r="provider":"vue"===n.type?r="plugin":"angular"===n.type&&(r="module");let a="modern";return(t.includes("require(")||t.includes("var "))&&(a="legacy"),{framework:n,confidence:i,patterns:e,conflicts:[],recommendations:[],integrationStrategy:r,compatibilityMode:a}}resolveConflictsHeuristic(e,t){const n=[];for(const t of e)switch(t){case"existing_humanbehavior_code":n.push("update_existing_integration");break;case"existing_provider":n.push("merge_providers");break;case"module_system_conflict":n.push("hybrid_module_support");break;default:n.push("skip_conflict")}return n}generateOptimizationsHeuristic(e,t){const n=[];switch(e.type){case"react":n.push("Use React.memo for performance optimization"),n.push("Implement error boundaries for better error tracking"),n.push("Consider using React.lazy for code splitting");break;case"vue":n.push("Use Vue 3 Composition API for better performance"),n.push("Implement proper error handling in components"),n.push("Consider using Vue Router for navigation tracking");break;case"angular":n.push("Use Angular standalone components for better tree-shaking"),n.push("Implement proper error handling with ErrorHandler"),n.push("Consider using Angular signals for state management");break;default:n.push("Enable performance tracking"),n.push("Implement error tracking"),n.push("Consider progressive enhancement")}return n}}class m extends u{constructor(e,t=process.cwd(),n){super(e,t),this.selectedFramework=n.toLowerCase(),this.framework=this.createFrameworkInfo(this.selectedFramework)}async install(){try{if("auto"===this.selectedFramework)this.framework=await this.runFullDetection();else{this.framework=this.createFrameworkInfo(this.selectedFramework),this.framework||(this.framework={name:"unknown",type:"vanilla"});const e=await this.runFullDetection();this.framework={...e,name:this.framework.name,type:this.framework.type}}await this.installPackage();const e=await this.generateModifications();await this.applyModifications(e);const t=this.generateManualNextSteps();return{success:!0,framework:this.framework,modifications:e,errors:[],nextSteps:t,selectedFramework:this.selectedFramework,manualMode:!0}}catch(e){return{success:!1,framework:this.framework||{name:"unknown",type:"vanilla"},modifications:[],errors:[e instanceof Error?e.message:"Unknown error"],nextSteps:[],selectedFramework:this.selectedFramework,manualMode:!0}}}async runFullDetection(){if("auto"===this.selectedFramework){const e=new l({apiEndpoint:"https://ik3zxh4790.execute-api.us-east-1.amazonaws.com/prod"}),t=await this.scanProjectFiles(),n=await this.extractCodeSamples(t);return(await e.analyzeCodePatterns(n)).framework}{const e=new u(this.apiKey,this.projectRoot);return await e.detectFramework()}}async scanProjectFiles(){const e=[],t=(n,i=0)=>{if(!(i>3))try{const r=o.readdirSync(n);for(const a of r){const r=s.join(n,a),c=o.statSync(r);c.isDirectory()&&!a.startsWith(".")&&"node_modules"!==a?t(r,i+1):c.isFile()&&this.isRelevantFile(a)&&e.push(r)}}catch(e){}};return t(this.projectRoot),e}isRelevantFile(e){return[".js",".jsx",".ts",".tsx",".vue",".svelte",".html",".json",".config.js",".config.ts",".babelrc",".eslintrc"].some(t=>e.endsWith(t))||["package.json","tsconfig.json","vite.config","webpack.config","next.config","nuxt.config","angular.json","svelte.config"].some(t=>e.includes(t))}async extractCodeSamples(e){const t=[];for(const n of e.slice(0,20))try{const e=o.readFileSync(n,"utf8"),i=s.relative(this.projectRoot,n);t.push(`File: ${i}\n${e.substring(0,1e3)}`)}catch(e){}return t}createFrameworkInfo(e){return{react:{name:"react",type:"react"},nextjs:{name:"nextjs",type:"nextjs"},next:{name:"nextjs",type:"nextjs"},vue:{name:"vue",type:"vue"},nuxt:{name:"nuxt",type:"nuxt"},nuxtjs:{name:"nuxt",type:"nuxt"},angular:{name:"angular",type:"angular"},svelte:{name:"svelte",type:"svelte"},sveltekit:{name:"svelte",type:"svelte"},remix:{name:"remix",type:"remix"},astro:{name:"astro",type:"astro"},gatsby:{name:"gatsby",type:"gatsby"},vanilla:{name:"vanilla",type:"vanilla"},node:{name:"node",type:"node"},auto:{name:"auto-detected",type:"auto"}}[e]||{name:e,type:"vanilla"}}async detectFramework(){return this.framework||{name:"unknown",type:"vanilla"}}generateManualNextSteps(){return["✅ Manual framework installation completed!",`🎯 Selected framework: ${this.framework?.name||"unknown"}`,`🔧 Integration strategy: ${this.getIntegrationStrategy()}`,"🚀 Your app is now ready to track user behavior","📊 View sessions in your HumanBehavior dashboard"]}getIntegrationStrategy(){if(!this.framework?.type)return"script";switch(this.framework.type){case"react":case"nextjs":return"provider";case"vue":return"plugin";case"angular":return"module";default:return"script"}}}class h{constructor(e){this.options=e}async run(){c.intro("🤖 AI-Enhanced HumanBehavior SDK Auto-Installation");try{const e=await this.getApiKey();e||(c.cancel("API key is required"),process.exit(1));const t=this.options.projectPath||process.cwd(),n=await this.chooseFramework();if(n||(c.cancel("Installation cancelled."),process.exit(0)),!this.options.yes){await this.confirmInstallation(t,n)||(c.cancel("Installation cancelled."),process.exit(0))}const i=c.spinner();i.start("🔍 Analyzing your project with AI...");const r=new m(e,t,n),a=await r.install();i.stop("Analysis complete!"),this.displayResults(a,n)}catch(e){c.cancel(`Error: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)}}async getApiKey(){if(this.options.apiKey)return this.options.apiKey;return await c.text({message:"Enter your HumanBehavior API key:",placeholder:"hb_...",validate:e=>e?e.startsWith("hb_")?void 0:'API key should start with "hb_"':"API key is required"})}async confirmInstallation(e,t){return await c.confirm({message:`Ready to install HumanBehavior SDK in ${e} for ${t}?`})}async chooseFramework(){return await c.select({message:"Select your framework:",options:[{label:"React",value:"react"},{label:"Next.js",value:"nextjs"},{label:"Vue",value:"vue"},{label:"Angular",value:"angular"},{label:"Svelte",value:"svelte"},{label:"Nuxt.js",value:"nuxt"},{label:"Remix",value:"remix"},{label:"Astro",value:"astro"},{label:"Gatsby",value:"gatsby"},{label:"Vanilla JS/TS",value:"vanilla"}]})}displayResults(e,t){if(e.success){if(c.outro("🎉 Installation completed successfully!"),c.note(`Framework detected: ${e.framework.name} (${e.framework.type})`,"Framework Info"),e.modifications&&e.modifications.length>0){const t=e.modifications.map(e=>`${e.action}: ${e.filePath} - ${e.description}`);c.note(t.join("\n"),"Files Modified")}e.nextSteps&&e.nextSteps.length>0&&c.note(e.nextSteps.join("\n"),"Next Steps"),e.aiAnalysis&&(c.note(`Confidence: ${Math.round(100*e.aiAnalysis.confidence)}%`,"AI Analysis"),e.aiAnalysis.recommendations&&e.aiAnalysis.recommendations.length>0&&c.note(e.aiAnalysis.recommendations.join("\n"),"AI Recommendations"))}else c.cancel("Installation failed"),e.errors&&e.errors.length>0&&c.note(e.errors.join("\n"),"Errors")}}function d(){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")}function f(){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')}new h(function(){const e=process.argv.slice(2),t={};for(let n=0;n<e.length;n++){const i=e[n];switch(i){case"--help":case"-h":d(),process.exit(0);break;case"--yes":case"-y":t.yes=!0;break;case"--dry-run":t.dryRun=!0;break;case"--project":case"-p":t.projectPath=e[++n];break;case"--framework":case"-f":t.framework=e[++n];break;case"init":e[n+1]&&!e[n+1].startsWith("-")||(f(),process.exit(1)),t.apiKey=e[++n];break;default:t.apiKey||i.startsWith("-")||(t.apiKey=i)}}return t}()).run().catch(e=>{c.cancel(`Unexpected error: ${e.message}`),process.exit(1)});class y{constructor(e){this.options=e}async run(){c.intro("🚀 HumanBehavior SDK Auto-Installation");try{const e=await this.getApiKey();e||(c.cancel("API key is required"),process.exit(1));const t=this.options.projectPath||process.cwd();if(!this.options.yes){await this.confirmInstallation(t)||(c.cancel("Installation cancelled."),process.exit(0))}const n=c.spinner();n.start("🔍 Detecting framework and applying integration...");const i=new u(e,t),r=await i.install();n.stop("Installation complete!"),this.displayResults(r)}catch(e){c.cancel(`Error: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)}}async getApiKey(){if(this.options.apiKey)return this.options.apiKey;return await c.text({message:"Enter your HumanBehavior API key:",placeholder:"hb_...",validate:e=>e?e.startsWith("hb_")?void 0:'API key should start with "hb_"':"API key is required"})}async confirmInstallation(e){return await c.confirm({message:`Ready to install HumanBehavior SDK in ${e}?`})}displayResults(e){if(e.success){if(c.outro("🎉 Installation completed successfully!"),c.note(`Framework detected: ${e.framework.name} (${e.framework.type})`,"Framework Info"),e.modifications&&e.modifications.length>0){const t=e.modifications.map(e=>`${e.action}: ${e.filePath} - ${e.description}`);c.note(t.join("\n"),"Files Modified")}e.nextSteps&&e.nextSteps.length>0&&c.note(e.nextSteps.join("\n"),"Next Steps")}else c.cancel("Installation failed"),e.errors&&e.errors.length>0&&c.note(e.errors.join("\n"),"Errors")}}function g(){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")}if(("undefined"==typeof document?require("url").pathToFileURL(__filename).href:r&&"SCRIPT"===r.tagName.toUpperCase()&&r.src||new URL("index.js",document.baseURI).href)===`file://${process.argv[1]}`){new y(function(){const e=process.argv.slice(2),t={};for(let n=0;n<e.length;n++){const i=e[n];switch(i){case"--help":case"-h":g(),process.exit(0);break;case"--yes":case"-y":t.yes=!0;break;case"--dry-run":t.dryRun=!0;break;case"--project":case"-p":t.projectPath=e[++n];break;default:t.apiKey||i.startsWith("-")||(t.apiKey=i)}}return t}()).run().catch(e=>{c.cancel(`Unexpected error: ${e.message}`),process.exit(1)})}exports.AIAutoInstallCLI=h,exports.AIBrowserInstallationWizard=class{constructor(e,t){this.apiKey=e,this.aiService=t||new p}async install(){try{const e=await this.performBrowserAIAnalysis(),t=this.generateAIBrowserModifications(e);return{success:!0,framework:e.framework,modifications:t,errors:[],nextSteps:["✅ AI-optimized browser integration ready!",`🎯 Framework detected: ${e.framework.name}`,`🔧 Integration strategy: ${e.integrationStrategy}`,"📋 Copy the generated code to your project","🚀 Your app will be ready to track user behavior"],aiAnalysis:e,learningData:{patterns:e.patterns,framework:e.framework.name,success:!0}}}catch(e){return{success:!1,framework:{name:"unknown",type:"vanilla"},modifications:[],errors:[e instanceof Error?e.message:"Unknown error"],nextSteps:[],aiAnalysis:{framework:{name:"unknown",type:"vanilla"},confidence:0,patterns:[],conflicts:[],recommendations:[],integrationStrategy:"script",compatibilityMode:"legacy"},learningData:{patterns:[],framework:"unknown",success:!1}}}}async performBrowserAIAnalysis(){this.detectBrowserFramework();const e=[`Browser Environment: ${this.analyzeBrowserPatterns().join(", ")}`];return await this.aiService.analyzeCodePatterns(e)}detectBrowserFramework(){if("undefined"!=typeof window){if(window.React)return{name:"react",type:"react"};if(window.Vue)return{name:"vue",type:"vue"};if(window.angular)return{name:"angular",type:"angular"}}return{name:"vanilla",type:"vanilla"}}analyzeBrowserPatterns(){const e=[];if("undefined"!=typeof window){window.React&&e.push("React global detected"),window.Vue&&e.push("Vue global detected"),window.angular&&e.push("Angular global detected"),document.querySelector("[data-reactroot]")&&e.push("React DOM detected"),document.querySelector("[data-vue]")&&e.push("Vue DOM detected");document.querySelectorAll("script").forEach(t=>{t.src.includes("react")&&e.push("React script detected"),t.src.includes("vue")&&e.push("Vue script detected")})}return e}generateAIBrowserModifications(e){const t=[];if("react"===e.framework.type)t.push({filePath:"App.jsx",action:"create",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: '${e.framework.name}',\n integrationStrategy: '${e.integrationStrategy}'\n }}\n >\n {/* Your app components */}\n </HumanBehaviorProvider>\n );\n}\n\nexport default App;`,description:"AI-optimized React component with HumanBehaviorProvider"});else t.push({filePath:"humanbehavior-init.js",action:"create",content:`// AI-Optimized Vanilla JS Integration\nimport { HumanBehaviorTracker } from 'humanbehavior-js';\n\nconst tracker = HumanBehaviorTracker.init('${this.apiKey}', {\n // AI-generated configuration\n framework: '${e.framework.name}',\n integrationStrategy: '${e.integrationStrategy}',\n compatibilityMode: '${e.compatibilityMode}',\n enablePerformanceTracking: true,\n enableErrorTracking: true\n});`,description:"AI-optimized vanilla JS initialization"});return t}},exports.AIEnhancedInstallationWizard=class extends u{constructor(e,t=process.cwd(),n){super(e,t),this.learningCache=new Map,this.patternDatabase=new Map,this.aiService=n||new p,this.loadLearningData()}async install(){try{const e=await this.performAICodeAnalysis();this.framework=await this.detectFrameworkWithAI(e);const t=await this.generateAIOptimizedModifications(e);await this.applyModificationsWithAI(t,e);const n=this.generateAINextSteps(e);return await this.learnFromInstallation(e,t),{success:!0,framework:this.framework,modifications:t,errors:[],nextSteps:n,aiAnalysis:e,learningData:{patterns:e.patterns,framework:this.framework.name,success:!0}}}catch(e){return{success:!1,framework:this.framework||{name:"unknown",type:"vanilla"},modifications:[],errors:[e instanceof Error?e.message:"Unknown error"],nextSteps:[],aiAnalysis:{framework:{name:"unknown",type:"vanilla"},confidence:0,patterns:[],conflicts:[],recommendations:[],integrationStrategy:"script",compatibilityMode:"legacy"},learningData:{patterns:[],framework:"unknown",success:!1}}}}async performAICodeAnalysis(){const e=await this.scanProjectFiles(),t=await this.extractCodeSamples(e);return await this.aiService.analyzeCodePatterns(t)}async scanProjectFiles(){const e=[],t=(n,i=0)=>{if(!(i>3))try{const r=o.readdirSync(n);for(const a of r){const r=s.join(n,a),c=o.statSync(r);c.isDirectory()&&!a.startsWith(".")&&"node_modules"!==a?t(r,i+1):c.isFile()&&this.isRelevantFile(a)&&e.push(r)}}catch(e){}};return t(this.projectRoot),e}isRelevantFile(e){return[".js",".jsx",".ts",".tsx",".vue",".svelte",".html",".json",".config.js",".config.ts",".babelrc",".eslintrc"].some(t=>e.endsWith(t))||["package.json","tsconfig.json","vite.config","webpack.config","next.config","nuxt.config","angular.json","svelte.config","app/layout","app/page","pages/index","pages/_app","pages/_document"].some(t=>e.includes(t))}async extractCodeSamples(e){const t=[];for(const n of e.slice(0,20))try{const e=o.readFileSync(n,"utf8"),i=s.relative(this.projectRoot,n),r=this.extractCodePatterns(e);r.length>0&&t.push(`File: ${i}\n${r.join("\n")}`)}catch(e){}return t}extractCodePatterns(e){const t=[],n={react:[/import\s+React\s+from\s+['"]react['"]/gi,/from\s+['"]react['"]/gi,/function\s+\w+\s*\(\s*\)\s*{/gi,/const\s+\w+\s*=\s*\(\s*\)\s*=>\s*{/gi],vue:[/import\s+{\s*createApp\s*}\s+from\s+['"]vue['"]/gi,/from\s+['"]vue['"]/gi,/<template>/gi,/<script\s+setup>/gi],angular:[/import\s+{\s*Component\s*}\s+from\s+['"]@angular\/core['"]/gi,/@Component\s*\(\s*{/gi,/from\s+['"]@angular/gi],svelte:[/<script>/gi,/import\s+.*\s+from\s+['"]svelte/gi,/from\s+['"]svelte/gi],nextjs:[/import\s+.*\s+from\s+['"]next/gi,/from\s+['"]next/gi,/export\s+default\s+function\s+Page/gi,/export\s+default\s+function\s+Layout/gi,/export\s+default\s+function\s+Loading/gi,/export\s+default\s+function\s+Error/gi,/export\s+default\s+function\s+Not-found/gi,/useRouter\s+from\s+['"]next\/navigation['"]/gi,/useRouter\s+from\s+['"]next\/router['"]/gi,/Link\s+from\s+['"]next\/link['"]/gi,/Image\s+from\s+['"]next\/image['"]/gi,/getServerSideProps/gi,/getStaticProps/gi,/getStaticPaths/gi,/next\.config/gi,/app\/layout\.tsx/gi,/app\/page\.tsx/gi,/pages\/.*\.tsx/gi,/pages\/.*\.jsx/gi,/pages\/.*\.ts/gi,/pages\/.*\.js/gi],nuxt:[/import\s+.*\s+from\s+['"]nuxt/gi,/from\s+['"]nuxt/gi,/export\s+default\s+defineNuxtConfig/gi,/defineNuxtConfig/gi,/nuxt\.config\.ts/gi,/nuxt\.config\.js/gi,/@nuxt\//gi,/#app/gi,/useNuxtApp/gi,/useRuntimeConfig/gi,/useSeoMeta/gi,/useHead/gi,/useLazyFetch/gi,/useFetch/gi,/useAsyncData/gi,/<NuxtLayout/gi,/<NuxtPage/gi,/NuxtLayout/gi,/NuxtPage/gi,/pages\/.*\.vue/gi,/layouts\/.*\.vue/gi,/components\/.*\.vue/gi,/composables\/.*\.ts/gi,/middleware\/.*\.ts/gi,/server\/.*\.ts/gi,/plugins\/.*\.ts/gi,/public\//gi,/assets\//gi,/content\//gi]};for(const[i,r]of Object.entries(n))for(const n of r){const r=e.match(n);r&&(t.push(...r.slice(0,3)),t.push(`${i.toUpperCase()}: ${r.slice(0,3).join(", ")}`))}const i=e.match(/import\s+.*\s+from\s+['"][^'"]+['"]/gi);i&&t.push(`IMPORTS: ${i.slice(0,5).join(", ")}`);const r=e.match(/export\s+.*/gi);return r&&t.push(`EXPORTS: ${r.slice(0,3).join(", ")}`),t}async detectFrameworkWithAI(e){const t=await super.detectFramework();return e.confidence>.8?{...e.framework,bundler:t.bundler,packageManager:t.packageManager,hasTypeScript:t.hasTypeScript,hasRouter:t.hasRouter,projectRoot:this.projectRoot}:{...t,..."vanilla"!==e.framework.type&&{type:e.framework.type,name:e.framework.name}}}async generateAIOptimizedModifications(e){const t=(await super.generateModifications()).map(t=>this.enhanceModificationWithAI(t,e)),n=this.generateAIOptimizations(e);return t.push(...n),t}enhanceModificationWithAI(e,t){let n=e.content;return"legacy"===t.compatibilityMode&&(n=`// HumanBehavior SDK - Legacy Compatibility Mode\n${n}`),"provider"===t.integrationStrategy&&(n=`// HumanBehavior SDK - Provider Pattern (Future-proof)\n${n}`),t.conflicts.length>0&&(n=`// Conflict Resolution: ${t.conflicts.join(", ")}\n${n}`),{...e,content:n,description:`${e.description} (AI-optimized)`}}generateAIOptimizations(e){return[]}async applyModificationsWithAI(e,t){for(const n of e)try{const e=await this.detectConflicts(n);if(e.length>0){const i=await this.aiService.resolveConflicts(e,t.framework),r=await this.resolveConflicts(n,e,i,t);await this.applyModification(r)}else await this.applyModification(n)}catch(e){throw new Error(`Failed to apply AI-optimized modification to ${n.filePath}: ${e}`)}}async detectConflicts(e){const t=[];if(o.existsSync(e.filePath)){const n=o.readFileSync(e.filePath,"utf8");(n.includes("HumanBehavior")||n.includes("humanbehavior"))&&t.push("existing_humanbehavior_code"),e.content.includes("Provider")&&n.includes("Provider")&&t.push("existing_provider"),e.content.includes("import")&&n.includes("require(")&&t.push("module_system_conflict")}return t}async resolveConflicts(e,t,n,i){let r=e.content;for(let i=0;i<t.length;i++){const a=t[i];switch(n[i]){case"update_existing_integration":r=`// Updated HumanBehavior Integration\n${r}`;break;case"merge_providers":r=r.replace(/<HumanBehaviorProvider/g,'<HumanBehaviorProvider key="updated"');break;case"hybrid_module_support":r=`// Hybrid module system support\n${r}`;break;case"skip_conflict":return{...e,content:"",description:`${e.description} (skipped due to conflict)`};default:r=`// Conflict resolved: ${a}\n${r}`}}return{...e,content:r,description:`${e.description} (conflict-resolved)`}}async applyModification(e){if(!e.content)return;const t=s.dirname(e.filePath);switch(o.existsSync(t)||o.mkdirSync(t,{recursive:!0}),e.action){case"create":case"modify":o.writeFileSync(e.filePath,e.content);break;case"append":o.appendFileSync(e.filePath,"\n"+e.content)}}generateAINextSteps(e){const t=["✅ AI-optimized SDK installation completed!",`🎯 Framework detected: ${e.framework.name} (confidence: ${Math.round(100*e.confidence)}%)`,`🔧 Integration strategy: ${e.integrationStrategy}`,`🔄 Compatibility mode: ${e.compatibilityMode}`,"🚀 Your app is now tracking user behavior with AI-optimized configuration"];return e.recommendations.length>0&&(t.push("💡 AI Recommendations:"),e.recommendations.forEach(e=>t.push(` • ${e}`))),t}async learnFromInstallation(e,t){const n={timestamp:(new Date).toISOString(),framework:e.framework.name,patterns:e.patterns,integrationStrategy:e.integrationStrategy,compatibilityMode:e.compatibilityMode,modifications:t.length,success:!0};this.learningCache.set(`${e.framework.name}_${Date.now()}`,n),this.patternDatabase.has(e.framework.name)||this.patternDatabase.set(e.framework.name,[]),this.patternDatabase.get(e.framework.name).push(n),await this.saveLearningData()}loadLearningData(){}async saveLearningData(){}getAIInsights(e){return this.patternDatabase.get(e)||[]}getLearningStats(){const e={totalInstallations:this.learningCache.size,frameworks:{},patterns:{}};for(const[t,n]of this.patternDatabase.entries())e.frameworks[t]=n.length;return e}},exports.AutoInstallCLI=y,exports.AutoInstallationWizard=u,exports.CentralizedAIService=class{constructor(e){this.cache=new Map,this.config={openaiModel:"gpt-4",maxTokens:2e3,temperature:.3,enableCaching:!0,cacheTTL:3600,...e},this.initializeOpenAI()}initializeOpenAI(){try{const{OpenAI:e}=require("openai");this.openai=new e({apiKey:this.config.openaiApiKey})}catch(e){console.warn("OpenAI not available, falling back to heuristic analysis"),this.openai=null}}async analyzeCodePatterns(e){const t={codeSamples:e,timestamp:(new Date).toISOString()},n=this.generateCacheKey(t);if(this.config.enableCaching){const e=this.cache.get(n);if(e&&this.isCacheValid(e.timestamp))return e.analysis}const i=await this.performAIAnalysis(t);return this.config.enableCaching&&this.cache.set(n,{analysis:i,timestamp:Date.now()}),i}async resolveConflicts(e,t){const n={conflicts:e,framework:t,codeContext:"HumanBehavior SDK integration"};if(!this.openai)return this.resolveConflictsHeuristic(e,t);try{const e=this.buildConflictResolutionPrompt(n),t=await this.openai.chat.completions.create({model:this.config.openaiModel,messages:[{role:"system",content:"You are an expert at resolving code integration conflicts. Provide specific resolution strategies."},{role:"user",content:e}],max_tokens:this.config.maxTokens,temperature:this.config.temperature}),i=t.choices[0]?.message?.content;return i&&"string"==typeof i?this.parseConflictResolutions(i):[]}catch(e){console.warn("AI conflict resolution failed, using heuristic approach:",e instanceof Error?e.message:"Unknown error")}return this.resolveConflictsHeuristic(e,t)}async generateOptimizations(e,t){const n={framework:e,patterns:t,projectContext:"HumanBehavior SDK integration"};if(!this.openai)return this.generateOptimizationsHeuristic(e,t);try{const e=this.buildOptimizationPrompt(n),t=await this.openai.chat.completions.create({model:this.config.openaiModel,messages:[{role:"system",content:"You are an expert at optimizing code integration. Provide specific, actionable recommendations."},{role:"user",content:e}],max_tokens:this.config.maxTokens,temperature:this.config.temperature}),i=t.choices[0]?.message?.content;if(i)return this.parseOptimizations(i)}catch(e){console.warn("AI optimization generation failed, using heuristic approach:",e instanceof Error?e.message:"Unknown error")}return this.generateOptimizationsHeuristic(e,t)}async performAIAnalysis(e){if(!this.openai)return this.performHeuristicAnalysis(e);try{const t=this.buildAnalysisPrompt(e),n=await this.openai.chat.completions.create({model:this.config.openaiModel,messages:[{role:"system",content:"You are an expert at analyzing code patterns and determining optimal integration strategies. Provide detailed analysis in JSON format."},{role:"user",content:t}],max_tokens:this.config.maxTokens,temperature:this.config.temperature,response_format:{type:"json_object"}}),i=n.choices[0]?.message?.content;if(i)return this.parseAnalysisResult(i)}catch(e){console.warn("AI analysis failed, using heuristic approach:",e instanceof Error?e.message:"Unknown error")}return this.performHeuristicAnalysis(e)}buildAnalysisPrompt(e){return`Analyze these code samples to determine the framework and integration strategy:\n\n${e.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.`}buildConflictResolutionPrompt(e){return`Resolve these integration conflicts for ${e.framework.name}:\n\nConflicts: ${e.conflicts.join(", ")}\n\nFramework: ${e.framework.name} (${e.framework.type})\nContext: ${e.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.`}buildOptimizationPrompt(e){return`Generate optimizations for ${e.framework.name} integration:\n\nFramework: ${e.framework.name} (${e.framework.type})\nPatterns: ${e.patterns.join(", ")}\nContext: ${e.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.`}parseAnalysisResult(e){try{const t=JSON.parse(e);return{framework:t.framework||{name:"vanilla",type:"vanilla"},confidence:t.confidence||.5,patterns:t.patterns||[],conflicts:t.conflicts||[],recommendations:t.recommendations||[],integrationStrategy:t.integrationStrategy||"script",compatibilityMode:t.compatibilityMode||"modern"}}catch(e){return console.warn("Failed to parse AI analysis result:",e),this.getDefaultAnalysis()}}parseConflictResolutions(e){try{const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch(e){return console.warn("Failed to parse conflict resolutions:",e),[]}}parseOptimizations(e){try{const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch(e){return console.warn("Failed to parse optimizations:",e),[]}}performHeuristicAnalysis(e){const t=e.codeSamples.join(" ").toLowerCase();let n={name:"vanilla",type:"vanilla"},i=.5;t.includes("react")?(n={name:"react",type:"react"},i=.9):t.includes("vue")?(n={name:"vue",type:"vue"},i=.9):t.includes("angular")?(n={name:"angular",type:"angular"},i=.9):t.includes("svelte")?(n={name:"svelte",type:"svelte"},i=.9):t.includes("next")?(n={name:"nextjs",type:"nextjs"},i=.9):t.includes("nuxt")&&(n={name:"nuxt",type:"nuxt"},i=.9);let r="script";"react"===n.type||"nextjs"===n.type?r="provider":"vue"===n.type?r="plugin":"angular"===n.type&&(r="module");let a="modern";return(t.includes("require(")||t.includes("var "))&&(a="legacy"),{framework:n,confidence:i,patterns:e.codeSamples,conflicts:[],recommendations:[],integrationStrategy:r,compatibilityMode:a}}resolveConflictsHeuristic(e,t){const n=[];for(const t of e)switch(t){case"existing_humanbehavior_code":n.push("update_existing_integration");break;case"existing_provider":n.push("merge_providers");break;case"module_system_conflict":n.push("hybrid_module_support");break;default:n.push("skip_conflict")}return n}generateOptimizationsHeuristic(e,t){const n=[];switch(e.type){case"react":n.push("Use React.memo for performance optimization"),n.push("Implement error boundaries for better error tracking"),n.push("Consider using React.lazy for code splitting");break;case"vue":n.push("Use Vue 3 Composition API for better performance"),n.push("Implement proper error handling in components"),n.push("Consider using Vue Router for navigation tracking");break;case"angular":n.push("Use Angular standalone components for better tree-shaking"),n.push("Implement proper error handling with ErrorHandler"),n.push("Consider using Angular signals for state management");break;default:n.push("Enable performance tracking"),n.push("Implement error tracking"),n.push("Consider progressive enhancement")}return n}generateCacheKey(e){const t=JSON.stringify(e);return Buffer.from(t).toString("base64").substring(0,32)}isCacheValid(e){return Date.now()-e<1e3*(this.config.cacheTTL||3600)}getDefaultAnalysis(){return{framework:{name:"vanilla",type:"vanilla"},confidence:.5,patterns:[],conflicts:[],recommendations:[],integrationStrategy:"script",compatibilityMode:"modern"}}getStats(){return{cacheSize:this.cache.size,config:{model:this.config.openaiModel,maxTokens:this.config.maxTokens,temperature:this.config.temperature,caching:this.config.enableCaching},openaiAvailable:!!this.openai}}clearCache(){this.cache.clear()}},exports.InstallWizard=u,exports.RemoteAIService=l;
1
+ "use strict";var e=require("fs"),t=require("path"),n=require("child_process"),i=require("util"),r=require("@clack/prompts"),a="undefined"!=typeof document?document.currentScript:null;function o(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var s=o(e),c=o(t),u=o(r);class p{constructor(e,t=process.cwd()){this.framework=null,this.manualNotes=[],this.apiKey=e,this.projectRoot=t}compareVersions(e,t){const n=e.split(".").map(Number),i=t.split(".").map(Number);for(let e=0;e<Math.max(n.length,i.length);e++){const t=n[e]||0,r=i[e]||0;if(t>r)return 1;if(t<r)return-1}return 0}isVersionGte(e,t){return this.compareVersions(e,t)>=0}getMajorVersion(e){return parseInt(e.split(".")[0])||0}async install(){try{this.framework=await this.detectFramework(),await this.installPackage();const e=await this.generateModifications();await this.applyModifications(e);const t=this.generateNextSteps();return{success:!0,framework:this.framework,modifications:e,errors:[],nextSteps:t}}catch(e){return{success:!1,framework:this.framework||{name:"unknown",type:"vanilla"},modifications:[],errors:[e instanceof Error?e.message:"Unknown error"],nextSteps:[]}}}async detectFramework(){const e=c.join(this.projectRoot,"package.json");if(!s.existsSync(e))return{name:"vanilla",type:"vanilla",projectRoot:this.projectRoot};const t=JSON.parse(s.readFileSync(e,"utf8")),n={...t.dependencies,...t.devDependencies};let i={name:"vanilla",type:"vanilla",projectRoot:this.projectRoot,features:{}};if(n.nuxt){const e=n.nuxt,t=this.isVersionGte(e,"3.0.0");i={name:"nuxt",type:"nuxt",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!n.typescript,hasRouter:!0,projectRoot:this.projectRoot,features:{hasNuxt3:t}}}else if(n.next){const e=n.next,t=this.isVersionGte(e,"13.0.0");i={name:"nextjs",type:"nextjs",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!n.typescript||!!n["@types/node"],hasRouter:!0,projectRoot:this.projectRoot,features:{hasNextAppRouter:t}}}else if(n["@remix-run/react"]||n["@remix-run/dev"]){const e=n["@remix-run/react"]||n["@remix-run/dev"];i={name:"remix",type:"remix",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!n.typescript||!!n["@types/react"],hasRouter:!0,projectRoot:this.projectRoot,features:{}}}else if(n.react){const e=n.react,t=this.isVersionGte(e,"18.0.0");i={name:"react",type:"react",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!n.typescript||!!n["@types/react"],hasRouter:!!n["react-router-dom"]||!!n["react-router"],projectRoot:this.projectRoot,features:{hasReact18:t}}}else if(n.vue){const e=n.vue,t=this.isVersionGte(e,"3.0.0");i={name:"vue",type:"vue",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!n.typescript||!!n["@vue/cli-service"],hasRouter:!!n["vue-router"],projectRoot:this.projectRoot,features:{hasVue3:t}}}else if(n["@angular/core"]){const e=n["@angular/core"],t=this.isVersionGte(e,"17.0.0");i={name:"angular",type:"angular",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!0,hasRouter:!0,projectRoot:this.projectRoot,features:{hasAngularStandalone:t}}}else if(n.svelte){const e=n.svelte,t=!!n["@sveltejs/kit"];i={name:"svelte",type:"svelte",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!n.typescript||!!n["svelte-check"],hasRouter:!!n["svelte-routing"]||!!n["@sveltejs/kit"],projectRoot:this.projectRoot,features:{hasSvelteKit:t}}}else if(n.astro){const e=n.astro;i={name:"astro",type:"astro",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!n.typescript||!!n["@astrojs/ts-plugin"],hasRouter:!0,projectRoot:this.projectRoot,features:{}}}else if(n.gatsby){const e=n.gatsby;i={name:"gatsby",type:"gatsby",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!n.typescript||!!n["@types/react"],hasRouter:!0,projectRoot:this.projectRoot,features:{}}}return n.vite?i.bundler="vite":n.webpack?i.bundler="webpack":n.esbuild?i.bundler="esbuild":n.rollup&&(i.bundler="rollup"),s.existsSync(c.join(this.projectRoot,"yarn.lock"))?i.packageManager="yarn":s.existsSync(c.join(this.projectRoot,"pnpm-lock.yaml"))?i.packageManager="pnpm":i.packageManager="npm",i}async installPackage(){let e="yarn"===this.framework?.packageManager?"yarn add humanbehavior-js@latest":"pnpm"===this.framework?.packageManager?"pnpm add humanbehavior-js@latest":"npm install humanbehavior-js@latest";"yarn"!==this.framework?.packageManager&&"pnpm"!==this.framework?.packageManager&&(e+=" --legacy-peer-deps");try{n.execSync(e,{cwd:this.projectRoot,stdio:"inherit"})}catch(e){throw new Error(`Failed to install humanbehavior-js: ${e}`)}}async generateModifications(){const e=[];switch(this.framework?.type){case"react":e.push(...await this.generateReactModifications());break;case"nextjs":e.push(...await this.generateNextJSModifications());break;case"nuxt":e.push(...await this.generateNuxtModifications());break;case"astro":e.push(...await this.generateAstroModifications());break;case"gatsby":e.push(...await this.generateGatsbyModifications());break;case"remix":e.push(...await this.generateRemixModifications());break;case"vue":e.push(...await this.generateVueModifications());break;case"angular":e.push(...await this.generateAngularModifications());break;case"svelte":e.push(...await this.generateSvelteModifications());break;default:e.push(...await this.generateVanillaModifications())}return e}async generateReactModifications(){const e=[],t=this.findReactAppFile();if(t){const n=s.readFileSync(t,"utf8"),i=this.injectReactProvider(n,t);e.push({filePath:t,action:"modify",content:i,description:"Added HumanBehaviorProvider to React app"})}return e.push(this.createEnvironmentModification(this.framework)),e}mergeProvidersFile(e){const t="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}";if(!s.existsSync(e))return`'use client';\n\nimport { HumanBehaviorProvider } from 'humanbehavior-js/react';\n\n${t}`;const n=s.readFileSync(e,"utf8");if(n.includes("export function HBProvider")||n.includes("export const HBProvider"))return n;let i=n;n.includes("from 'humanbehavior-js/react'")||(i=n.includes("'use client'")?n.replace(/('use client';?)\s*\n/,"$1\n\nimport { HumanBehaviorProvider } from 'humanbehavior-js/react';\n"):`import { HumanBehaviorProvider } from 'humanbehavior-js/react';\n\n${n}`);const r=i.trimEnd();return i=""===r?t:`${r}\n\n${t}`,i}async generateNextJSModifications(){const e=[],t=c.join(this.projectRoot,"src","app","layout.tsx"),n=c.join(this.projectRoot,"app","layout.tsx"),i=c.join(this.projectRoot,"src","pages","_app.tsx"),r=c.join(this.projectRoot,"pages","_app.tsx");let a=null,o=null,u=null;if(s.existsSync(t)?(a=t,o=c.join(this.projectRoot,"src","app","providers.tsx"),u="@/app/providers"):s.existsSync(n)&&(a=n,o=c.join(this.projectRoot,"app","providers.tsx"),u="@/app/providers"),a){const t=this.mergeProvidersFile(o),n=s.existsSync(o);e.push({filePath:o,action:n?"modify":"create",content:t,description:n?"Merged HBProvider into existing providers.tsx file":"Created providers.tsx file with HBProvider for Next.js App Router"});const i=s.readFileSync(a,"utf8"),r=this.injectNextJSAppRouter(i,u);e.push({filePath:a,action:"modify",content:r,description:"Added HumanBehavior provider wrapper to Next.js App Router layout"})}else if(s.existsSync(i)||s.existsSync(r)){const t=s.existsSync(i)?i:r,n=s.existsSync(i)?c.join(this.projectRoot,"src","components","HumanBehaviorProvider.tsx"):c.join(this.projectRoot,"components","HumanBehaviorProvider.tsx"),a=s.existsSync(i)?"../components/HumanBehaviorProvider":"./components/HumanBehaviorProvider";e.push({filePath:n,action:"create",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}",description:"Created HumanBehavior provider file for Pages Router"});const o=s.readFileSync(t,"utf8"),u=this.injectNextJSPagesRouter(o,a);e.push({filePath:t,action:"modify",content:u,description:"Added HumanBehavior provider wrapper to Next.js Pages Router"})}return e.push(this.createEnvironmentModification(this.framework)),e}async generateAstroModifications(){const e=[],t=c.join(this.projectRoot,"src","components","HumanBehavior.astro");e.push({filePath:t,action:"create",content:"---\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>",description:"Created Astro component for HumanBehavior SDK"});const n=[c.join(this.projectRoot,"src","layouts","Layout.astro"),c.join(this.projectRoot,"src","layouts","layout.astro"),c.join(this.projectRoot,"src","layouts","BaseLayout.astro")];let i=null;for(const e of n)if(s.existsSync(e)){i=e;break}if(i){const t=s.readFileSync(i,"utf8"),n=this.injectAstroLayout(t);e.push({filePath:i,action:"modify",content:n,description:"Added HumanBehavior component to Astro layout"})}return e.push(this.createEnvironmentModification(this.framework)),e}async generateNuxtModifications(){const e=[],t=c.join(this.projectRoot,"app","plugins","humanbehavior.client.ts");e.push({filePath:t,action:"create",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});",description:"Created Nuxt plugin for HumanBehavior SDK in app directory"});const n=c.join(this.projectRoot,"nuxt.config.ts");{const t=this.applyOrNotify(n,e=>this.injectNuxtConfig(e),"Added HumanBehavior runtime config to Nuxt config","Nuxt: Add inside defineNuxtConfig({ … }):\nruntimeConfig: { public: { humanBehaviorApiKey: process.env.NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY } },");t&&e.push(t)}return e.push(this.createEnvironmentModification(this.framework)),e}async generateRemixModifications(){const e=[],t=c.join(this.projectRoot,"app","root.tsx");if(s.existsSync(t)){const n=s.readFileSync(t,"utf8"),i=this.injectRemixProvider(n);e.push({filePath:t,action:"modify",content:i,description:"Added HumanBehaviorProvider to Remix root component"})}return e.push(this.createEnvironmentModification(this.framework)),e}async generateVueModifications(){const e=[],t=this.findVueMainFile(),n=c.join(this.projectRoot,"src","composables"),i=c.join(n,"useHumanBehavior.ts");try{s.existsSync(n)||s.mkdirSync(n,{recursive:!0}),s.existsSync(i)||e.push({filePath:i,action:"create",content:"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",description:"Created Vue composable useHumanBehavior"})}catch{}if(t){const n=s.readFileSync(t,"utf8"),i=this.injectVuePlugin(n);e.push({filePath:t,action:"modify",content:i,description:"Added HumanBehaviorPlugin to Vue app"})}return e.push(this.createEnvironmentModification(this.framework)),e}async generateAngularModifications(){const e=[],t=c.join(this.projectRoot,"src","app","services"),n=c.join(t,"hb.service.ts");s.existsSync(t)||s.mkdirSync(t,{recursive:!0}),s.existsSync(n)||e.push({filePath:n,action:"create",content:"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",description:"Created Angular HumanBehavior service (singleton)"});const i=c.join(this.projectRoot,"src","environments","environment.ts"),r=c.join(this.projectRoot,"src","environments","environment.prod.ts"),a=c.dirname(i);if(s.existsSync(a)||s.mkdirSync(a,{recursive:!0}),s.existsSync(i)){const t=s.readFileSync(i,"utf8");if(!t.includes("humanBehaviorApiKey")){const n=t.replace(/export const environment = {([\s\S]*?)};/,`export const environment = {\n $1,\n humanBehaviorApiKey: '${this.apiKey}'\n};`);e.push({filePath:i,action:"modify",content:n,description:"Added API key to Angular development environment"})}}else e.push({filePath:i,action:"create",content:`export const environment = {\n production: false,\n humanBehaviorApiKey: '${this.apiKey}'\n};`,description:"Created Angular development environment file"});if(s.existsSync(r)){const t=s.readFileSync(r,"utf8");if(!t.includes("humanBehaviorApiKey")){const n=t.replace(/export const environment = {([\s\S]*?)};/,`export const environment = {\n $1,\n humanBehaviorApiKey: '${this.apiKey}'\n};`);e.push({filePath:r,action:"modify",content:n,description:"Added API key to Angular production environment"})}}else e.push({filePath:r,action:"create",content:`export const environment = {\n production: true,\n humanBehaviorApiKey: '${this.apiKey}'\n};`,description:"Created Angular production environment file"});const o=c.join(this.projectRoot,"src","app","app.ts");if(s.existsSync(o)){const t=s.readFileSync(o,"utf8");if(!t.includes("HumanBehavior")){let n=t.replace(/import { Component } from '@angular\/core';/,"import { Component } from '@angular/core';\nimport { HumanBehavior } from './services/hb.service';").replace(/export class App {/,"export class App {\n constructor(private readonly humanBehavior: HumanBehavior) {}");e.push({action:"modify",filePath:o,content:n,description:"Injected HumanBehavior service into Angular app component"})}}return e}async generateSvelteModifications(){const e=[],t=c.join(this.projectRoot,"svelte.config.js");if(s.existsSync(t)){const t=c.join(this.projectRoot,"src","routes","+layout.svelte");if(s.existsSync(t)){const n=s.readFileSync(t,"utf8"),i=this.injectSvelteKitLayout(n);e.push({filePath:t,action:"modify",content:i,description:"Added HumanBehavior tracker init to SvelteKit layout"})}}else{const t=this.findSvelteMainFile();if(t){const n=s.readFileSync(t,"utf8"),i=this.injectSvelteStore(n);e.push({filePath:t,action:"modify",content:i,description:"Added HumanBehavior tracker init to Svelte app"})}}return e.push(this.createEnvironmentModification(this.framework)),e}async generateVanillaModifications(){const e=[],t=this.findHTMLFile();if(t){const n=s.readFileSync(t,"utf8"),i=this.injectVanillaScript(n);e.push({filePath:t,action:"modify",content:i,description:"Added HumanBehavior CDN script to HTML file"})}return e.push(this.createEnvironmentModification(this.framework)),e}async generateGatsbyModifications(){const e=[],t=c.join(this.projectRoot,"gatsby-browser.js");if(s.existsSync(t)){const n=s.readFileSync(t,"utf8"),i=this.injectGatsbyBrowser(n);e.push({filePath:t,action:"modify",content:i,description:"Added HumanBehavior initialization to Gatsby browser"})}else e.push({filePath:t,action:"create",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};",description:"Created gatsby-browser.js with HumanBehavior initialization"});return e.push(this.createEnvironmentModification(this.framework)),e}async applyModifications(e){for(const t of e)try{const e=c.dirname(t.filePath);switch(s.existsSync(e)||s.mkdirSync(e,{recursive:!0}),t.action){case"create":case"modify":s.writeFileSync(t.filePath,t.content);break;case"append":s.appendFileSync(t.filePath,"\n"+t.content)}}catch(e){throw new Error(`Failed to apply modification to ${t.filePath}: ${e}`)}}generateNextSteps(){const e=["✅ SDK installed and configured automatically!","🚀 Your app is now tracking user behavior","📊 View sessions in your HumanBehavior dashboard","🔧 Customize tracking in your code as needed"];return"react"!==this.framework?.type&&"nextjs"!==this.framework?.type||e.push("💡 Use the useHumanBehavior() hook to track custom events"),this.manualNotes.length&&e.push(...this.manualNotes.map(e=>`⚠️ ${e}`)),e}applyOrNotify(e,t,n,i){if(!s.existsSync(e))return this.manualNotes.push(`${i} (file missing: ${c.relative(this.projectRoot,e)})`),null;const r=s.readFileSync(e,"utf8"),a=t(r);return a!==r?{filePath:e,action:"modify",content:a,description:n}:(this.manualNotes.push(i),null)}findReactAppFile(){const e=["src/App.jsx","src/App.js","src/App.tsx","src/App.ts","src/index.js","src/index.tsx","src/main.js","src/main.tsx"];for(const t of e){const e=c.join(this.projectRoot,t);if(s.existsSync(e))return e}return null}findVueMainFile(){const e=["src/main.js","src/main.ts","src/main.jsx","src/main.tsx"];for(const t of e){const e=c.join(this.projectRoot,t);if(s.existsSync(e))return e}return null}findSvelteMainFile(){const e=["src/main.js","src/main.ts","src/main.svelte"];for(const t of e){const e=c.join(this.projectRoot,t);if(s.existsSync(e))return e}return null}findHTMLFile(){const e=["index.html","public/index.html","dist/index.html"];for(const t of e){const e=c.join(this.projectRoot,t);if(s.existsSync(e))return e}return null}injectReactProvider(e,t){if(t.endsWith(".tsx")||t.endsWith(".ts"),e.includes("HumanBehaviorProvider"))return e;const n="vite"===this.framework?.bundler?"import.meta.env.VITE_HUMANBEHAVIOR_API_KEY!":"process.env.REACT_APP_HUMANBEHAVIOR_API_KEY!",i="import { HumanBehaviorProvider } from 'humanbehavior-js/react';",r=this.framework?.features?.hasReact18;if(e.includes("function App()")||e.includes("const App =")){let t=e.replace(/(import.*?from.*?['"]react['"];?)/,`$1\n${i}`);return t.includes(i)||(t=`${i}\n\n${t}`),t=t.replace(/return\s*\(([\s\S]*?)\)\s*;/,`return (\n <HumanBehaviorProvider apiKey={${n}}>\n $1\n </HumanBehaviorProvider>\n );`),t}if(r&&e.includes("createRoot")){let t=e.replace(/(import.*?from.*?['"]react['"];?)/,`$1\n${i}`);return t.includes(i)||(t=`${i}\n\n${t}`),t=t.replace(/(root\.render\s*\([\s\S]*?\)\s*;)/,`root.render(\n <HumanBehaviorProvider apiKey={${n}}>\n $1\n </HumanBehaviorProvider>\n );`),t}return`${i}\n\n${e}`}injectNextJSAppRouter(e,t="@/app/providers"){if(e.includes("HBProvider"))return e;const n=`import { HBProvider } from '${t}';`;let i=e.replace(/export default function RootLayout/,`${n}\n\nexport default function RootLayout`);return i=i.replace(/<body([^>]*)>([\s\S]*?)<\/body>/,(e,t,n)=>`<body${t}>\n <HBProvider>\n ${n.trim()}\n </HBProvider>\n </body>`),i}injectNextJSPagesRouter(e,t="../components/HumanBehaviorProvider"){if(e.includes("HBProvider"))return e;const n=`import { HBProvider } from '${t}';`;return e.replace(/function MyApp/,`${n}\n\nfunction MyApp`).replace(/return \(([\s\S]*?)\);/,"return (\n <HBProvider>\n $1\n </HBProvider>\n );")}injectRemixProvider(e){if(e.includes("HumanBehaviorProvider"))return e;let t=e;return e.includes("useLoaderData")||(t=t.replace(/(} from ['"]@remix-run\/react['"];?\s*)/,"$1import { useLoaderData } from '@remix-run/react';\n")),e.includes("HumanBehaviorProvider")||(t=t.replace(/(} from ['"]@remix-run\/react['"];?\s*)/,"$1import { HumanBehaviorProvider } from 'humanbehavior-js/react';\n")),e.includes("LoaderFunctionArgs")||(t=t.replace(/(} from ['"]@remix-run\/node['"];?\s*)/,"$1import type { LoaderFunctionArgs } from '@remix-run/node';\n")),e.includes("export const loader")||(t=t.replace(/(export function Layout)/,"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")),e.includes("const data = useLoaderData")||(t=t.replace(/(export default function App\(\) \{\s*)(return \(\s*<div[^>]*>[\s\S]*?<\/div>\s*\);\s*\})/,'$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}')),t}injectVuePlugin(e){if(e.includes("useHumanBehavior"))return e;const t=this.framework?.features?.hasVue3,n=e.includes("createApp")||e.includes("import { createApp }");let i=e.replace(/import\s*\{\s*HumanBehaviorPlugin\s*\}\s*from\s*['\"]humanbehavior-js\/vue['\"];?/g,"").replace(/app\.use\(\s*HumanBehaviorPlugin[\s\S]*?\);?/g,"");if(t||n){const e="import { useHumanBehavior } from './composables/useHumanBehavior';";if(!i.includes(e)){const t=i.lastIndexOf("import");if(-1!==t){const n=i.indexOf("\n",t);i=-1!==n?i.slice(0,n+1)+e+"\n"+i.slice(n+1):i+"\n"+e}else i=e+"\n"+i}return i.includes("createApp")&&(i=i.replace(/(const\s+app\s*=\s*createApp\([^)]*\))/,"$1\nconst { tracker } = useHumanBehavior();")),i}{const e="import { HumanBehaviorTracker } from 'humanbehavior-js';";return i.includes(e)||(i=`${e}\n${i}`),i.includes("new Vue")&&(i=i.replace(/(new\s+Vue\s*\()/,"HumanBehaviorTracker.init(process.env.VUE_APP_HUMANBEHAVIOR_API_KEY || import.meta?.env?.VITE_HUMANBEHAVIOR_API_KEY);\n$1")),i}}injectAngularModule(e){if(e.includes("HumanBehaviorModule"))return e;let t=e;return e.includes("environment")||(t=e.replace(/import.*from.*['"]@angular/,"import { environment } from '../environments/environment';\n$&")),t.replace(/imports:\s*\[([\s\S]*?)\]/,"imports: [\n $1,\n HumanBehaviorModule.forRoot({\n apiKey: environment.humanBehaviorApiKey\n })\n ]").replace(/import.*from.*['"]@angular/,"$&\nimport { HumanBehaviorModule } from 'humanbehavior-js/angular';")}injectAngularStandaloneInit(e){if(e.includes("initializeHumanBehavior"))return e;let t=e.replace(/import.*from.*['"]@angular/,"import { initializeHumanBehavior } from 'humanbehavior-js/angular';\nimport { environment } from './environments/environment';\n$&");return t=t.replace(/(bootstrapApplication\([^}]+\}?\)(?:\s*\.catch[^;]+;)?)/,"$1\n\n// Initialize HumanBehavior SDK (client-side only)\nif (typeof window !== 'undefined') {\n const tracker = initializeHumanBehavior(environment.humanBehaviorApiKey);\n}"),t}injectSvelteStore(e){if(e.includes("HumanBehaviorTracker.init"))return e;return`import { HumanBehaviorTracker } from 'humanbehavior-js';\n// Initialize HumanBehavior SDK\nHumanBehaviorTracker.init(import.meta.env?.VITE_HUMANBEHAVIOR_API_KEY || process.env.PUBLIC_HUMANBEHAVIOR_API_KEY || '');\n\n${e}`}injectSvelteKitLayout(e){if(e.includes("HumanBehaviorTracker.init"))return e;const t="import { PUBLIC_HUMANBEHAVIOR_API_KEY } from '$env/static/public';",n="import { HumanBehaviorTracker } from 'humanbehavior-js';",i="import { browser } from '$app/environment';",r="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}";return e.includes('<script lang="ts">')?e.replace(/<script lang="ts">/,`<script lang="ts">\n\t${i}\n\t${t}\n\t${n}\n\t${r}`):e.includes("<script>")?e.replace(/<script>/,`<script>\n\t${i}\n\t${t}\n\t${n}\n\t${r}`):`<script lang="ts">\n${i}\n${t}\n${n}\n${r}\n<\/script>\n\n${e}`}injectVanillaScript(e){if(e.includes("humanbehavior-js"))return e;const t=`<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>`;return e.replace(/<\/head>/,` <script src="https://unpkg.com/humanbehavior-js@latest/dist/index.min.js"><\/script>\n ${t}\n</head>`)}injectAstroLayout(e){if(e.includes("HumanBehavior")||e.includes("humanbehavior-js"))return e;let t=e;if(!e.includes("import HumanBehavior")){const n="import HumanBehavior from '../components/HumanBehavior.astro';",i=e.indexOf("---",3);t=-1!==i?e.slice(0,i)+"\n"+n+"\n"+e.slice(i):"---\n"+n+"\n---\n\n"+e}const n=t.lastIndexOf("</body>");return-1===n?t+"\n\n<HumanBehavior />":t.slice(0,n)+" <HumanBehavior />\n"+t.slice(n)}injectNuxtConfig(e){if(e.includes("humanBehaviorApiKey"))return e;const t=this.framework?.features?.hasNuxt3;if(t){const t=/export\s+default\s+defineNuxtConfig\s*\(\s*\{/;if(t.test(e)){const n=e.replace(t,"export default defineNuxtConfig({\n runtimeConfig: {\n public: {\n humanBehaviorApiKey: process.env.NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY\n }\n },");if(n!==e)return n}const n=e.indexOf("defineNuxtConfig(");if(-1!==n){const t=e.indexOf("{",n);if(-1!==t){const n="\n runtimeConfig: {\n public: {\n humanBehaviorApiKey: process.env.NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY\n }\n },";return`${e.slice(0,t+1)}${n}${e.slice(t+1)}`}}return e}return e.replace(/export default \{/,"export default {\n env: {\n humanBehaviorApiKey: process.env.HUMANBEHAVIOR_API_KEY\n },")}injectGatsbyLayout(e){if(e.includes("HumanBehavior"))return e;let t=e.replace(/import.*from.*['"]\./,"import HumanBehavior from './HumanBehavior';\n$&");return t=t.replace(/(\s*<\/body>)/,"\n <HumanBehavior apiKey={process.env.GATSBY_HUMANBEHAVIOR_API_KEY || ''} />\n$1"),t}injectGatsbyBrowser(e){const t="import { HumanBehaviorTracker } from 'humanbehavior-js';";if(/export\s+const\s+onClientEntry\s*=\s*\(/.test(e)){let n=e;return n.includes("from 'humanbehavior-js'")||(n=`${t}\n${n}`),n.includes("HumanBehaviorTracker.init(")?n:(n=n.replace(/(export\s+const\s+onClientEntry\s*=\s*\([^)]*\)\s*=>\s*\{)/,"$1\n const apiKey = process.env.GATSBY_HUMANBEHAVIOR_API_KEY;\n if (apiKey) {\n HumanBehaviorTracker.init(apiKey);\n }\n"),n)}return`${e.trim(),`${t}\n`}export const onClientEntry = () => {\n const apiKey = process.env.GATSBY_HUMANBEHAVIOR_API_KEY;\n if (apiKey) {\n HumanBehaviorTracker.init(apiKey);\n }\n};${e.trim()?`\n\n${e}`:""}`}findBestEnvFile(e){const t=[".env.local",".env.development.local",".env.development",".env.local.development",".env",".env.production",".env.staging"],n=(e=>{if("react"===e.type&&"vite"===e.bundler)return"VITE_HUMANBEHAVIOR_API_KEY";return{react:"REACT_APP_HUMANBEHAVIOR_API_KEY",nextjs:"NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY",vue:"VITE_HUMANBEHAVIOR_API_KEY",svelte:"PUBLIC_HUMANBEHAVIOR_API_KEY",angular:"HUMANBEHAVIOR_API_KEY",nuxt:"NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY",remix:"HUMANBEHAVIOR_API_KEY",vanilla:"HUMANBEHAVIOR_API_KEY",astro:"PUBLIC_HUMANBEHAVIOR_API_KEY",gatsby:"GATSBY_HUMANBEHAVIOR_API_KEY",node:"HUMANBEHAVIOR_API_KEY",auto:"HUMANBEHAVIOR_API_KEY"}[e.type]||"HUMANBEHAVIOR_API_KEY"})(e);for(const e of t){const t=c.join(this.projectRoot,e);if(s.existsSync(t))return{filePath:t,envVarName:n}}const i={react:".env.local",nextjs:".env.local",vue:".env.local",svelte:".env",angular:".env",nuxt:".env",remix:".env.local",vanilla:".env",astro:".env",gatsby:".env.development",node:".env",auto:".env"}[e.type]||".env";return{filePath:c.join(this.projectRoot,i),envVarName:n}}createEnvironmentModification(e){const{filePath:t,envVarName:n}=this.findBestEnvFile(e),i=this.apiKey.trim();if(s.existsSync(t)){const e=s.readFileSync(t,"utf8");return e.includes(n)?{filePath:t,action:"modify",content:e,description:`API key already exists in ${c.basename(t)}`}:{filePath:t,action:"append",content:`\n${n}=${i}`,description:`Added API key to existing ${c.basename(t)}`}}return{filePath:t,action:"create",content:`${n}=${i}`,description:`Created ${c.basename(t)} with API key`}}}class l{async analyzeCodePatterns(e){return this.analyzeWithHeuristics(e)}async resolveConflicts(e,t){const n=[];for(const t of e)switch(t){case"existing_humanbehavior_code":n.push("update_existing_integration");break;case"existing_provider":n.push("merge_providers");break;case"module_system_conflict":n.push("hybrid_module_support");break;default:n.push("skip_conflict")}return n}async generateOptimizations(e,t){const n=[];switch(e.type){case"react":n.push("Use React.memo for performance optimization"),n.push("Implement error boundaries for better error tracking"),n.push("Consider using React.lazy for code splitting");break;case"vue":n.push("Use Vue 3 Composition API for better performance"),n.push("Implement proper error handling in components"),n.push("Consider using Vue Router for navigation tracking");break;case"angular":n.push("Use Angular standalone components for better tree-shaking"),n.push("Implement proper error handling with ErrorHandler"),n.push("Consider using Angular signals for state management");break;default:n.push("Enable performance tracking"),n.push("Implement error tracking"),n.push("Consider progressive enhancement")}return n}analyzeWithHeuristics(e){const t=e.join(" ").toLowerCase();let n={name:"vanilla",type:"vanilla"},i=.5;t.includes("nuxt")||t.includes("nuxtjs")||t.includes("defineNuxtConfig")||t.includes("nuxt.config")||t.includes("@nuxt/")||t.includes("useNuxtApp")||t.includes("useRuntimeConfig")||t.includes("useSeoMeta")||t.includes("useHead")||t.includes("useLazyFetch")||t.includes("useFetch")||t.includes("useAsyncData")||t.includes("#app")?(n={name:"nuxt",type:"nuxt"},i=.95):t.includes("next")||t.includes("nextjs")||t.includes("next/link")||t.includes("next/image")||t.includes("next/navigation")||t.includes("next/router")||t.includes("getserverSideProps")||t.includes("getstaticProps")||t.includes("getstaticPaths")||t.includes("app/layout")||t.includes("app/page")||t.includes("pages/")?(n={name:"nextjs",type:"nextjs"},i=.95):t.includes("gatsby")||t.includes("gatsby-browser")||t.includes("gatsby-ssr")||t.includes("gatsby-node")||t.includes("gatsby-config")||t.includes("useStaticQuery")||t.includes("graphql")?(n={name:"gatsby",type:"gatsby"},i=.95):t.includes("react")?(n={name:"react",type:"react"},i=.9):t.includes("vue")?(n={name:"vue",type:"vue"},i=.9):t.includes("angular")?(n={name:"angular",type:"angular"},i=.9):t.includes("svelte")&&(n={name:"svelte",type:"svelte"},i=.9);let r="script";"react"===n.type||"nextjs"===n.type||"gatsby"===n.type?r="provider":"vue"===n.type?r="plugin":"angular"===n.type&&(r="module");let a="modern";return(t.includes("require(")||t.includes("var "))&&(a="legacy"),{framework:n,confidence:i,patterns:e,conflicts:[],recommendations:[],integrationStrategy:r,compatibilityMode:a}}}const h=i.promisify(n.exec),d=24e3,m="$humanbehavior_wizard_verified";class f{constructor(e,t){this.projectRoot=c.resolve(e),this.verification=t}async execute(e){try{let t;switch(e.name){case"hb_list_files":t=this.listFiles(e.input);break;case"hb_read_file":t=this.readFile(e.input);break;case"hb_write_file":t=this.writeFile(e.input);break;case"hb_grep":t=this.grep(e.input);break;case"hb_bash":t=await this.bash(e.input);break;case"hb_verify_installation":t=await this.verifyInstallation();break;default:throw new Error(`Unknown tool: ${e.name}`)}return{type:"tool_result",tool_use_id:e.id,content:t}}catch(t){return{type:"tool_result",tool_use_id:e.id,content:t instanceof Error?t.message:"Unknown tool error",is_error:!0}}}resolveProjectPath(e){const t="string"==typeof e&&e.trim()?e:".",n=c.resolve(this.projectRoot,t);if(n!==this.projectRoot&&!n.startsWith(`${this.projectRoot}${c.sep}`))throw new Error(`Path escapes project root: ${t}`);return n}listFiles(e){const t=this.resolveProjectPath(e.path),n="number"==typeof e.maxDepth?Math.max(0,Math.min(e.maxDepth,6)):3,i=new Set([".git",".next","dist","build","coverage","node_modules"]),r=[],a=(e,t)=>{if(t>n||r.length>=300)return;const o=s.readdirSync(e,{withFileTypes:!0});for(const n of o){if(i.has(n.name)||n.name.endsWith("-lock.json")||"pnpm-lock.yaml"===n.name||"yarn.lock"===n.name)continue;const o=c.join(e,n.name),s=c.relative(this.projectRoot,o)||".";if(r.push(n.isDirectory()?`${s}/`:s),n.isDirectory()&&a(o,t+1),r.length>=120)break}};return a(t,0),r.slice(0,120).join("\n")||"(no files)"}readFile(e){const t=this.resolveProjectPath(e.path),n="number"==typeof e.maxBytes?Math.max(1,Math.min(e.maxBytes,24e3)):24e3,i=s.readFileSync(t),r=i.length>n,a=i.subarray(0,n).toString("utf8");return r?`${a}\n\n[truncated at ${n} bytes]`:a}writeFile(e){if("string"!=typeof e.content)throw new Error("content must be a string");const t=this.resolveProjectPath(e.path);return s.mkdirSync(c.dirname(t),{recursive:!0}),s.writeFileSync(t,e.content,"utf8"),`Wrote ${Buffer.byteLength(e.content,"utf8")} bytes to ${c.relative(this.projectRoot,t)}`}grep(e){if("string"!=typeof e.pattern||!e.pattern)throw new Error("pattern is required");const t=this.resolveProjectPath(e.path),n=new RegExp(e.pattern,"i"),i=new Set([".git",".next","dist","build","coverage","node_modules"]),r=[],a=e=>{if(r.length>=40)return;const t=s.statSync(e);if(t.isDirectory()){for(const t of s.readdirSync(e,{withFileTypes:!0}))if(!i.has(t.name)&&!t.name.endsWith("-lock.json")&&"pnpm-lock.yaml"!==t.name&&"yarn.lock"!==t.name&&(a(c.join(e,t.name)),r.length>=40))break;return}if(!t.isFile()||t.size>512e3)return;const o=s.readFileSync(e,"utf8").split(/\r?\n/);for(let t=0;t<o.length;t++)if(n.test(o[t])){const n=o[t].length>240?`${o[t].slice(0,240)}...`:o[t];if(r.push(`${c.relative(this.projectRoot,e)}:${t+1}: ${n}`),r.length>=40)break}};return a(t),r.join("\n")||"(no matches)"}async bash(e){if("string"!=typeof e.command||!e.command.trim())throw new Error("command is required");this.assertSafeCommand(e.command);const{stdout:t,stderr:n}=await h(e.command,{cwd:this.projectRoot,timeout:6e4,maxBuffer:d,env:process.env}),i=[t,n].filter(Boolean).join("\n");return i?i.length>d?`${i.slice(0,d)}\n\n[truncated at 24000 bytes]`:i:"(command completed with no output)"}async verifyInstallation(){if(!this.verification)throw new Error("Verification is not configured for this run.");const e=`hb-wizard-${this.verification.runId}`,t=`hb-wizard-${this.verification.runId}`,n=(this.verification.ingestionUrl||process.env.HUMANBEHAVIOR_INGESTION_URL||"https://ingest.humanbehavior.co").replace(/\/$/,""),i=await fetch(`${n}/api/ingestion/customEvent`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${this.verification.apiKey}`},body:JSON.stringify({sessionId:e,endUserId:t,eventName:m,eventProperties:{wizardRunId:this.verification.runId,source:"humanbehavior-wizard",projectRoot:this.projectRoot},automaticProperties:{url:"humanbehavior://wizard",pathname:"/wizard"}})});if(!i.ok){const e=await i.text().catch(()=>i.statusText);throw new Error(`Verification event failed (${i.status}): ${e||i.statusText}`)}for(let e=1;e<=12;e++){const t=await this.verification.verifyRun();if(t.verified)return JSON.stringify({verified:!0,event:m,attempt:e,verification:t.verification??{}});await new Promise(e=>setTimeout(e,2500))}return JSON.stringify({verified:!1,event:m,message:"Verification event was sent but has not appeared in ClickHouse yet."})}assertSafeCommand(e){const t=[/\brm\s+-rf\b/,/\bgit\s+reset\b/,/\bgit\s+clean\b/,/\bsudo\b/,/\bchmod\s+-R\b/,/>\s*\/dev\/(?:disk|rdisk)/];for(const n of t)if(n.test(e))throw new Error(`Refusing unsafe command: ${e}`)}}class g{constructor(e){this.apiKey=e.apiKey,this.baseUrl=(e.baseUrl||process.env.HUMANBEHAVIOR_APP_URL||"https://www.humanbehavior.co").replace(/\/$/,"")}getRunConsoleUrl(e,t){return`${this.baseUrl}/projects/${e}/get-started/sdk?wizardRun=${t}`}async createRun(e){return(await this.request("/api/wizard/runs",{method:"POST",body:JSON.stringify(e)})).json()}async updateRun(e,t){await this.request(`/api/wizard/runs/${e}`,{method:"PATCH",body:JSON.stringify(t)})}async createAgentSession(e){return(await this.request("/api/wizard/agent-sessions",{method:"POST",body:JSON.stringify(e)})).json()}async runAgentTurn(e,t,n){return(await this.request(`/api/wizard/agent-sessions/${e}/turn`,{method:"POST",body:JSON.stringify({messages:n})},t)).json()}async verifyRun(e){return(await this.request(`/api/wizard/runs/${e}/verify`,{method:"POST",body:JSON.stringify({})})).json()}async request(e,t,n=this.apiKey){const i=await fetch(`${this.baseUrl}${e}`,{...t,headers:{"content-type":"application/json",authorization:`Bearer ${n}`,...t.headers}});if(!i.ok){const e=await i.text().catch(()=>i.statusText);throw new Error(`Wizard API request failed (${i.status}): ${e||i.statusText}`)}return i}}const y="https://documentation.humanbehavior.co";class v extends Error{constructor(e="The managed Human Behavior agent installer is not available yet."){super(e),this.name="ManagedAgentUnavailableError"}}class w{constructor(e){this.apiKey=e.apiKey,this.projectPath=c.resolve(e.projectPath||process.cwd()),this.executionMode=e.executionMode||"interactive",this.ingestionUrl=e.ingestionUrl,this.apiClient=new g({apiKey:e.apiKey,baseUrl:e.appUrl})}async run(){const e=this.scanRepo();let t,n=null,i=null,r=null;if(!this.apiKey.startsWith("hb_"))return this.failure(e,'HumanBehavior API key should start with "hb_".');try{const i=await this.apiClient.createRun({executionMode:this.executionMode,repo:e});n=i.run.id,t=this.apiClient.getRunConsoleUrl(i.projectSlug,i.run.id)}catch(t){if("dry-run"!==this.executionMode)return this.failure(e,`Could not start a managed wizard run: ${t instanceof Error?t.message:"Unknown error"}`);i=`Dashboard sync unavailable: ${t instanceof Error?t.message:"Unknown error"}`}if("dry-run"===this.executionMode){const r={success:!0,phase:"analyze",repo:e,errors:[],nextSteps:["Dry run complete. No files were changed.","The managed agent session is required before edit planning can run.",...t?[`Dashboard run: ${t}`]:[],...i?[i]:[],`Manual setup docs: ${y}`],dashboardUrl:t};return await this.updateRunSafely(n,{status:"completed",phase:"finish",result:r}),r}try{if(!n)throw new Error("Wizard run was not created.");const e=await this.apiClient.createAgentSession({runId:n,permissionMode:"yes"===this.executionMode?"acceptEdits":"default"});r={id:e.session.id,token:e.sessionToken}}catch(i){const r=this.failure(e,`Could not start managed Claude agent session: ${i instanceof Error?i.message:"Unknown error"}`,t);return await this.updateRunSafely(n,{status:"failed",phase:"analyze",result:r}),r}return this.runRemoteToolLoop(n,r,e,t)}async runRemoteToolLoop(e,t,n,i){let r=!1;const a=new f(this.projectPath,{apiKey:this.apiKey,runId:e,ingestionUrl:this.ingestionUrl,verifyRun:async()=>{const t=await this.apiClient.verifyRun(e);return t.verified&&(r=!0),t}}),o=[{role:"user",content:this.createInitialPrompt(n)}];for(let s=0;s<18;s++){const s=await this.apiClient.runAgentTurn(t.id,t.token,o);if(o.push({role:"assistant",content:s.message.content}),0===s.toolRequests.length){if(!r){const t=this.failure(n,"Managed agent stopped before verification completed.",i);return await this.updateRunSafely(e,{status:"failed",phase:"check-errors",result:t}),t}const t={success:!0,phase:"finish",repo:n,errors:[],nextSteps:["Managed agent loop completed.","Review the local git diff before committing.",...i?[`Dashboard run: ${i}`]:[]],dashboardUrl:i};return await this.updateRunSafely(e,{status:"completed",phase:"finish",result:t}),t}await this.updateRunSafely(e,{status:"running",phase:this.phaseForTools(s.toolRequests),result:{success:!1,nextSteps:[`Executing ${s.toolRequests.length} agent tool request(s).`]}});const c=[];for(const e of s.toolRequests)c.push(await a.execute(e));o.push({role:"user",content:c})}const s=this.failure(n,"Managed agent exceeded 18 turns before finishing.",i);return await this.updateRunSafely(e,{status:"failed",phase:"check-errors",result:s}),s}createInitialPrompt(e){return["Run the Human Behavior SDK installation now.","",`Project root: ${this.projectPath}`,`Execution mode: ${this.executionMode}`,`Human Behavior API key: ${this.apiKey}`,`Package manager: ${e.packageManager}`,`Workspace shape: ${e.workspaceShape}`,`package.json files: ${e.packageJsonPaths.join(", ")||"none"}`,"","Use the available tools to inspect and edit the project.","Do not inspect node_modules, package-lock.json, pnpm-lock.yaml, yarn.lock, build output, or dist output unless absolutely necessary.",'For browser SDK imports, humanbehavior-js has no default export. Use named exports, for example: import { init } from "humanbehavior-js"; then call init(apiKey).',"When using hb_write_file, write exactly one complete file body. Do not duplicate previous file contents.","When finished, stop requesting tools and summarize what changed."].join("\n")}phaseForTools(e){return e.some(e=>"hb_verify_installation"===e.name)?"check-errors":e.some(e=>"hb_write_file"===e.name)?"edit":e.some(e=>"hb_bash"===e.name)?"check-errors":"analyze"}async updateRunSafely(e,t){if(e)try{await this.apiClient.updateRun(e,t)}catch{}}failure(e,t,n){return{success:!1,phase:"analyze",repo:e,errors:[t],nextSteps:["No files were changed.","Please follow the manual installation docs while the agent installer is unavailable.",...n?[`Dashboard run: ${n}`]:[],`Manual setup docs: ${y}`],dashboardUrl:n}}scanRepo(){const e=this.findPackageJsonPaths(this.projectPath);return{projectPath:this.projectPath,packageManager:this.detectPackageManager(this.projectPath),workspaceShape:this.detectWorkspaceShape(e),packageJsonPaths:e}}findPackageJsonPaths(e){const t=[],n=new Set([".git",".next","dist","build","coverage","node_modules"]),i=(r,a)=>{if(a>4)return;let o;try{o=s.readdirSync(r,{withFileTypes:!0})}catch{return}for(const s of o){const o=c.join(r,s.name);s.isFile()&&"package.json"===s.name?t.push(c.relative(e,o)||"package.json"):!s.isDirectory()||n.has(s.name)||s.name.startsWith(".")||i(o,a+1)}};return i(e,0),t.sort()}detectPackageManager(e){return s.existsSync(c.join(e,"bun.lockb"))||s.existsSync(c.join(e,"bun.lock"))?"bun":s.existsSync(c.join(e,"pnpm-lock.yaml"))?"pnpm":s.existsSync(c.join(e,"yarn.lock"))?s.existsSync(c.join(e,".yarnrc.yml"))||s.existsSync(c.join(e,".pnp.cjs"))?"yarn-berry":"yarn-classic":s.existsSync(c.join(e,"package-lock.json"))?"npm":"unknown"}detectWorkspaceShape(e){return 0===e.length?"unknown":1===e.length?"single-app":e.length<=4?"simple-monorepo":"complex-monorepo"}}class x{constructor(e){this.options=e}async run(){u.intro("HumanBehavior Agent Installer");try{const e=await this.getApiKey();e||(u.cancel("API key is required"),process.exit(1));const t=this.options.projectPath||process.cwd();if(!this.options.yes){await this.confirmInstallation(t)||(u.cancel("Installation cancelled."),process.exit(0))}const n=u.spinner();n.start(this.options.dryRun?"Scanning project...":"Starting managed agent installer...");const i=new w({apiKey:e,projectPath:t,executionMode:this.getExecutionMode(),appUrl:this.options.appUrl,ingestionUrl:this.options.ingestionUrl}),r=await i.run();n.stop(this.options.dryRun?"Scan complete.":"Agent installer finished."),this.displayResults(r)}catch(e){u.cancel(`Error: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)}}async getApiKey(){if(this.options.apiKey)return this.options.apiKey;return await u.text({message:"Enter your HumanBehavior API key:",placeholder:"hb_...",validate:e=>e?e.startsWith("hb_")?void 0:'API key should start with "hb_"':"API key is required"})}getExecutionMode(){return this.options.dryRun?"dry-run":this.options.yes?"yes":"interactive"}async confirmInstallation(e){return await u.confirm({message:`Ready to run the HumanBehavior agent installer in ${e}?`})}displayResults(e){if(u.note([`Project path: ${e.repo.projectPath}`,`Package manager: ${e.repo.packageManager}`,`Workspace shape: ${e.repo.workspaceShape}`,`package.json files: ${e.repo.packageJsonPaths.length||"none"}`].join("\n"),"Project Scan"),e.success)return e.nextSteps.length>0&&u.note(e.nextSteps.join("\n"),"Next Steps"),void u.outro(this.options.dryRun?"Dry run complete.":"Installation completed successfully.");e.errors.length>0&&u.note(e.errors.join("\n"),"Errors"),e.nextSteps.length>0&&u.note(e.nextSteps.join("\n"),"Next Steps"),u.cancel("Agent installer unavailable."),process.exit(1)}}function k(){console.log("\nHumanBehavior Agent Installer\n\nUsage: npx humanbehavior-js init [api-key] [options]\n\nOptions:\n -h, --help Show this help message\n -y, --yes Skip confirmation prompts\n --dry-run Scan and report without changing files\n -p, --project <path> Specify project directory\n --app-url <url> HumanBehavior app URL for local/dev testing\n --ingestion-url <url> HumanBehavior ingestion URL for local/dev testing\n\nExamples:\n npx humanbehavior-js init\n npx humanbehavior-js init hb_your_api_key_here\n npx humanbehavior-js init --project ./my-app --yes\n")}if(("undefined"==typeof document?require("url").pathToFileURL(__filename).href:a&&"SCRIPT"===a.tagName.toUpperCase()&&a.src||new URL("index.js",document.baseURI).href)===`file://${process.argv[1]}`){new x(function(){const e=process.argv.slice(2),t={};for(let n=0;n<e.length;n++){const i=e[n];switch(i){case"--help":case"-h":k(),process.exit(0);break;case"--yes":case"-y":t.yes=!0;break;case"--dry-run":t.dryRun=!0;break;case"--project":case"-p":t.projectPath=e[++n];break;case"--app-url":t.appUrl=e[++n];break;case"--ingestion-url":t.ingestionUrl=e[++n];break;case"--framework":case"-f":throw new Error("--framework is no longer supported. The agent installer scans the project automatically.");case"init":e[n+1]&&!e[n+1].startsWith("-")&&(t.apiKey=e[++n]);break;default:t.apiKey||i.startsWith("-")||(t.apiKey=i)}}return t}()).run().catch(e=>{u.cancel(`Unexpected error: ${e.message}`),process.exit(1)})}class b{constructor(e){this.options=e}async run(){u.intro("🚀 HumanBehavior SDK Auto-Installation");try{const e=await this.getApiKey();e||(u.cancel("API key is required"),process.exit(1));const t=this.options.projectPath||process.cwd();if(!this.options.yes){await this.confirmInstallation(t)||(u.cancel("Installation cancelled."),process.exit(0))}const n=u.spinner();n.start("🔍 Detecting framework and applying integration...");const i=new p(e,t),r=await i.install();n.stop("Installation complete!"),this.displayResults(r)}catch(e){u.cancel(`Error: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)}}async getApiKey(){if(this.options.apiKey)return this.options.apiKey;return await u.text({message:"Enter your HumanBehavior API key:",placeholder:"hb_...",validate:e=>e?e.startsWith("hb_")?void 0:'API key should start with "hb_"':"API key is required"})}async confirmInstallation(e){return await u.confirm({message:`Ready to install HumanBehavior SDK in ${e}?`})}displayResults(e){if(e.success){if(u.outro("🎉 Installation completed successfully!"),u.note(`Framework detected: ${e.framework.name} (${e.framework.type})`,"Framework Info"),e.modifications&&e.modifications.length>0){const t=e.modifications.map(e=>`${e.action}: ${e.filePath} - ${e.description}`);u.note(t.join("\n"),"Files Modified")}e.nextSteps&&e.nextSteps.length>0&&u.note(e.nextSteps.join("\n"),"Next Steps")}else u.cancel("Installation failed"),e.errors&&e.errors.length>0&&u.note(e.errors.join("\n"),"Errors")}}function j(){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")}if(("undefined"==typeof document?require("url").pathToFileURL(__filename).href:a&&"SCRIPT"===a.tagName.toUpperCase()&&a.src||new URL("index.js",document.baseURI).href)===`file://${process.argv[1]}`){new b(function(){const e=process.argv.slice(2),t={};for(let n=0;n<e.length;n++){const i=e[n];switch(i){case"--help":case"-h":j(),process.exit(0);break;case"--yes":case"-y":t.yes=!0;break;case"--dry-run":t.dryRun=!0;break;case"--project":case"-p":t.projectPath=e[++n];break;default:t.apiKey||i.startsWith("-")||(t.apiKey=i)}}return t}()).run().catch(e=>{u.cancel(`Unexpected error: ${e.message}`),process.exit(1)})}exports.AIAutoInstallCLI=x,exports.AIBrowserInstallationWizard=class{constructor(e,t){this.apiKey=e,this.aiService=t||new l}async install(){try{const e=await this.performBrowserAIAnalysis(),t=this.generateAIBrowserModifications(e);return{success:!0,framework:e.framework,modifications:t,errors:[],nextSteps:["✅ AI-optimized browser integration ready!",`🎯 Framework detected: ${e.framework.name}`,`🔧 Integration strategy: ${e.integrationStrategy}`,"📋 Copy the generated code to your project","🚀 Your app will be ready to track user behavior"],aiAnalysis:e,learningData:{patterns:e.patterns,framework:e.framework.name,success:!0}}}catch(e){return{success:!1,framework:{name:"unknown",type:"vanilla"},modifications:[],errors:[e instanceof Error?e.message:"Unknown error"],nextSteps:[],aiAnalysis:{framework:{name:"unknown",type:"vanilla"},confidence:0,patterns:[],conflicts:[],recommendations:[],integrationStrategy:"script",compatibilityMode:"legacy"},learningData:{patterns:[],framework:"unknown",success:!1}}}}async performBrowserAIAnalysis(){this.detectBrowserFramework();const e=[`Browser Environment: ${this.analyzeBrowserPatterns().join(", ")}`];return await this.aiService.analyzeCodePatterns(e)}detectBrowserFramework(){if("undefined"!=typeof window){if(window.React)return{name:"react",type:"react"};if(window.Vue)return{name:"vue",type:"vue"};if(window.angular)return{name:"angular",type:"angular"}}return{name:"vanilla",type:"vanilla"}}analyzeBrowserPatterns(){const e=[];if("undefined"!=typeof window){window.React&&e.push("React global detected"),window.Vue&&e.push("Vue global detected"),window.angular&&e.push("Angular global detected"),document.querySelector("[data-reactroot]")&&e.push("React DOM detected"),document.querySelector("[data-vue]")&&e.push("Vue DOM detected");document.querySelectorAll("script").forEach(t=>{t.src.includes("react")&&e.push("React script detected"),t.src.includes("vue")&&e.push("Vue script detected")})}return e}generateAIBrowserModifications(e){const t=[];if("react"===e.framework.type)t.push({filePath:"App.jsx",action:"create",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: '${e.framework.name}',\n integrationStrategy: '${e.integrationStrategy}'\n }}\n >\n {/* Your app components */}\n </HumanBehaviorProvider>\n );\n}\n\nexport default App;`,description:"AI-optimized React component with HumanBehaviorProvider"});else t.push({filePath:"humanbehavior-init.js",action:"create",content:`// AI-Optimized Vanilla JS Integration\nimport { HumanBehaviorTracker } from 'humanbehavior-js';\n\nconst tracker = HumanBehaviorTracker.init('${this.apiKey}', {\n // AI-generated configuration\n framework: '${e.framework.name}',\n integrationStrategy: '${e.integrationStrategy}',\n compatibilityMode: '${e.compatibilityMode}',\n enablePerformanceTracking: true,\n enableErrorTracking: true\n});`,description:"AI-optimized vanilla JS initialization"});return t}},exports.AIEnhancedInstallationWizard=class extends p{constructor(e,t=process.cwd(),n){super(e,t),this.learningCache=new Map,this.patternDatabase=new Map,this.aiService=n||new l,this.loadLearningData()}async install(){try{const e=await this.performAICodeAnalysis();this.framework=await this.detectFrameworkWithAI(e);const t=await this.generateAIOptimizedModifications(e);await this.applyModificationsWithAI(t,e);const n=this.generateAINextSteps(e);return await this.learnFromInstallation(e,t),{success:!0,framework:this.framework,modifications:t,errors:[],nextSteps:n,aiAnalysis:e,learningData:{patterns:e.patterns,framework:this.framework.name,success:!0}}}catch(e){return{success:!1,framework:this.framework||{name:"unknown",type:"vanilla"},modifications:[],errors:[e instanceof Error?e.message:"Unknown error"],nextSteps:[],aiAnalysis:{framework:{name:"unknown",type:"vanilla"},confidence:0,patterns:[],conflicts:[],recommendations:[],integrationStrategy:"script",compatibilityMode:"legacy"},learningData:{patterns:[],framework:"unknown",success:!1}}}}async performAICodeAnalysis(){const e=await this.scanProjectFiles(),t=await this.extractCodeSamples(e);return await this.aiService.analyzeCodePatterns(t)}async scanProjectFiles(){const e=[],t=(n,i=0)=>{if(!(i>3))try{const r=s.readdirSync(n);for(const a of r){const r=c.join(n,a),o=s.statSync(r);o.isDirectory()&&!a.startsWith(".")&&"node_modules"!==a?t(r,i+1):o.isFile()&&this.isRelevantFile(a)&&e.push(r)}}catch(e){}};return t(this.projectRoot),e}isRelevantFile(e){return[".js",".jsx",".ts",".tsx",".vue",".svelte",".html",".json",".config.js",".config.ts",".babelrc",".eslintrc"].some(t=>e.endsWith(t))||["package.json","tsconfig.json","vite.config","webpack.config","next.config","nuxt.config","angular.json","svelte.config","app/layout","app/page","pages/index","pages/_app","pages/_document"].some(t=>e.includes(t))}async extractCodeSamples(e){const t=[];for(const n of e.slice(0,20))try{const e=s.readFileSync(n,"utf8"),i=c.relative(this.projectRoot,n),r=this.extractCodePatterns(e);r.length>0&&t.push(`File: ${i}\n${r.join("\n")}`)}catch(e){}return t}extractCodePatterns(e){const t=[],n={react:[/import\s+React\s+from\s+['"]react['"]/gi,/from\s+['"]react['"]/gi,/function\s+\w+\s*\(\s*\)\s*{/gi,/const\s+\w+\s*=\s*\(\s*\)\s*=>\s*{/gi],vue:[/import\s+{\s*createApp\s*}\s+from\s+['"]vue['"]/gi,/from\s+['"]vue['"]/gi,/<template>/gi,/<script\s+setup>/gi],angular:[/import\s+{\s*Component\s*}\s+from\s+['"]@angular\/core['"]/gi,/@Component\s*\(\s*{/gi,/from\s+['"]@angular/gi],svelte:[/<script>/gi,/import\s+.*\s+from\s+['"]svelte/gi,/from\s+['"]svelte/gi],nextjs:[/import\s+.*\s+from\s+['"]next/gi,/from\s+['"]next/gi,/export\s+default\s+function\s+Page/gi,/export\s+default\s+function\s+Layout/gi,/export\s+default\s+function\s+Loading/gi,/export\s+default\s+function\s+Error/gi,/export\s+default\s+function\s+Not-found/gi,/useRouter\s+from\s+['"]next\/navigation['"]/gi,/useRouter\s+from\s+['"]next\/router['"]/gi,/Link\s+from\s+['"]next\/link['"]/gi,/Image\s+from\s+['"]next\/image['"]/gi,/getServerSideProps/gi,/getStaticProps/gi,/getStaticPaths/gi,/next\.config/gi,/app\/layout\.tsx/gi,/app\/page\.tsx/gi,/pages\/.*\.tsx/gi,/pages\/.*\.jsx/gi,/pages\/.*\.ts/gi,/pages\/.*\.js/gi],nuxt:[/import\s+.*\s+from\s+['"]nuxt/gi,/from\s+['"]nuxt/gi,/export\s+default\s+defineNuxtConfig/gi,/defineNuxtConfig/gi,/nuxt\.config\.ts/gi,/nuxt\.config\.js/gi,/@nuxt\//gi,/#app/gi,/useNuxtApp/gi,/useRuntimeConfig/gi,/useSeoMeta/gi,/useHead/gi,/useLazyFetch/gi,/useFetch/gi,/useAsyncData/gi,/<NuxtLayout/gi,/<NuxtPage/gi,/NuxtLayout/gi,/NuxtPage/gi,/pages\/.*\.vue/gi,/layouts\/.*\.vue/gi,/components\/.*\.vue/gi,/composables\/.*\.ts/gi,/middleware\/.*\.ts/gi,/server\/.*\.ts/gi,/plugins\/.*\.ts/gi,/public\//gi,/assets\//gi,/content\//gi]};for(const[i,r]of Object.entries(n))for(const n of r){const r=e.match(n);r&&(t.push(...r.slice(0,3)),t.push(`${i.toUpperCase()}: ${r.slice(0,3).join(", ")}`))}const i=e.match(/import\s+.*\s+from\s+['"][^'"]+['"]/gi);i&&t.push(`IMPORTS: ${i.slice(0,5).join(", ")}`);const r=e.match(/export\s+.*/gi);return r&&t.push(`EXPORTS: ${r.slice(0,3).join(", ")}`),t}async detectFrameworkWithAI(e){const t=await super.detectFramework();return e.confidence>.8?{...e.framework,bundler:t.bundler,packageManager:t.packageManager,hasTypeScript:t.hasTypeScript,hasRouter:t.hasRouter,projectRoot:this.projectRoot}:{...t,..."vanilla"!==e.framework.type&&{type:e.framework.type,name:e.framework.name}}}async generateAIOptimizedModifications(e){const t=(await super.generateModifications()).map(t=>this.enhanceModificationWithAI(t,e)),n=this.generateAIOptimizations(e);return t.push(...n),t}enhanceModificationWithAI(e,t){let n=e.content;return"legacy"===t.compatibilityMode&&(n=`// HumanBehavior SDK - Legacy Compatibility Mode\n${n}`),"provider"===t.integrationStrategy&&(n=`// HumanBehavior SDK - Provider Pattern (Future-proof)\n${n}`),t.conflicts.length>0&&(n=`// Conflict Resolution: ${t.conflicts.join(", ")}\n${n}`),{...e,content:n,description:`${e.description} (AI-optimized)`}}generateAIOptimizations(e){return[]}async applyModificationsWithAI(e,t){for(const n of e)try{const e=await this.detectConflicts(n);if(e.length>0){const i=await this.aiService.resolveConflicts(e,t.framework),r=await this.resolveConflicts(n,e,i,t);await this.applyModification(r)}else await this.applyModification(n)}catch(e){throw new Error(`Failed to apply AI-optimized modification to ${n.filePath}: ${e}`)}}async detectConflicts(e){const t=[];if(s.existsSync(e.filePath)){const n=s.readFileSync(e.filePath,"utf8");(n.includes("HumanBehavior")||n.includes("humanbehavior"))&&t.push("existing_humanbehavior_code"),e.content.includes("Provider")&&n.includes("Provider")&&t.push("existing_provider"),e.content.includes("import")&&n.includes("require(")&&t.push("module_system_conflict")}return t}async resolveConflicts(e,t,n,i){let r=e.content;for(let i=0;i<t.length;i++){const a=t[i];switch(n[i]){case"update_existing_integration":r=`// Updated HumanBehavior Integration\n${r}`;break;case"merge_providers":r=r.replace(/<HumanBehaviorProvider/g,'<HumanBehaviorProvider key="updated"');break;case"hybrid_module_support":r=`// Hybrid module system support\n${r}`;break;case"skip_conflict":return{...e,content:"",description:`${e.description} (skipped due to conflict)`};default:r=`// Conflict resolved: ${a}\n${r}`}}return{...e,content:r,description:`${e.description} (conflict-resolved)`}}async applyModification(e){if(!e.content)return;const t=c.dirname(e.filePath);switch(s.existsSync(t)||s.mkdirSync(t,{recursive:!0}),e.action){case"create":case"modify":s.writeFileSync(e.filePath,e.content);break;case"append":s.appendFileSync(e.filePath,"\n"+e.content)}}generateAINextSteps(e){const t=["✅ AI-optimized SDK installation completed!",`🎯 Framework detected: ${e.framework.name} (confidence: ${Math.round(100*e.confidence)}%)`,`🔧 Integration strategy: ${e.integrationStrategy}`,`🔄 Compatibility mode: ${e.compatibilityMode}`,"🚀 Your app is now tracking user behavior with AI-optimized configuration"];return e.recommendations.length>0&&(t.push("💡 AI Recommendations:"),e.recommendations.forEach(e=>t.push(` • ${e}`))),t}async learnFromInstallation(e,t){const n={timestamp:(new Date).toISOString(),framework:e.framework.name,patterns:e.patterns,integrationStrategy:e.integrationStrategy,compatibilityMode:e.compatibilityMode,modifications:t.length,success:!0};this.learningCache.set(`${e.framework.name}_${Date.now()}`,n),this.patternDatabase.has(e.framework.name)||this.patternDatabase.set(e.framework.name,[]),this.patternDatabase.get(e.framework.name).push(n),await this.saveLearningData()}loadLearningData(){}async saveLearningData(){}getAIInsights(e){return this.patternDatabase.get(e)||[]}getLearningStats(){const e={totalInstallations:this.learningCache.size,frameworks:{},patterns:{}};for(const[t,n]of this.patternDatabase.entries())e.frameworks[t]=n.length;return e}},exports.AgentInstallationRunner=w,exports.AutoInstallCLI=b,exports.AutoInstallationWizard=p,exports.CentralizedAIService=class{constructor(e){this.cache=new Map,this.config={openaiModel:"gpt-4",maxTokens:2e3,temperature:.3,enableCaching:!0,cacheTTL:3600,...e},this.initializeOpenAI()}initializeOpenAI(){try{const{OpenAI:e}=require("openai");this.openai=new e({apiKey:this.config.openaiApiKey})}catch(e){console.warn("OpenAI not available, falling back to heuristic analysis"),this.openai=null}}async analyzeCodePatterns(e){const t={codeSamples:e,timestamp:(new Date).toISOString()},n=this.generateCacheKey(t);if(this.config.enableCaching){const e=this.cache.get(n);if(e&&this.isCacheValid(e.timestamp))return e.analysis}const i=await this.performAIAnalysis(t);return this.config.enableCaching&&this.cache.set(n,{analysis:i,timestamp:Date.now()}),i}async resolveConflicts(e,t){const n={conflicts:e,framework:t,codeContext:"HumanBehavior SDK integration"};if(!this.openai)return this.resolveConflictsHeuristic(e,t);try{const e=this.buildConflictResolutionPrompt(n),t=await this.openai.chat.completions.create({model:this.config.openaiModel,messages:[{role:"system",content:"You are an expert at resolving code integration conflicts. Provide specific resolution strategies."},{role:"user",content:e}],max_tokens:this.config.maxTokens,temperature:this.config.temperature}),i=t.choices[0]?.message?.content;return i&&"string"==typeof i?this.parseConflictResolutions(i):[]}catch(e){console.warn("AI conflict resolution failed, using heuristic approach:",e instanceof Error?e.message:"Unknown error")}return this.resolveConflictsHeuristic(e,t)}async generateOptimizations(e,t){const n={framework:e,patterns:t,projectContext:"HumanBehavior SDK integration"};if(!this.openai)return this.generateOptimizationsHeuristic(e,t);try{const e=this.buildOptimizationPrompt(n),t=await this.openai.chat.completions.create({model:this.config.openaiModel,messages:[{role:"system",content:"You are an expert at optimizing code integration. Provide specific, actionable recommendations."},{role:"user",content:e}],max_tokens:this.config.maxTokens,temperature:this.config.temperature}),i=t.choices[0]?.message?.content;if(i)return this.parseOptimizations(i)}catch(e){console.warn("AI optimization generation failed, using heuristic approach:",e instanceof Error?e.message:"Unknown error")}return this.generateOptimizationsHeuristic(e,t)}async performAIAnalysis(e){if(!this.openai)return this.performHeuristicAnalysis(e);try{const t=this.buildAnalysisPrompt(e),n=await this.openai.chat.completions.create({model:this.config.openaiModel,messages:[{role:"system",content:"You are an expert at analyzing code patterns and determining optimal integration strategies. Provide detailed analysis in JSON format."},{role:"user",content:t}],max_tokens:this.config.maxTokens,temperature:this.config.temperature,response_format:{type:"json_object"}}),i=n.choices[0]?.message?.content;if(i)return this.parseAnalysisResult(i)}catch(e){console.warn("AI analysis failed, using heuristic approach:",e instanceof Error?e.message:"Unknown error")}return this.performHeuristicAnalysis(e)}buildAnalysisPrompt(e){return`Analyze these code samples to determine the framework and integration strategy:\n\n${e.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.`}buildConflictResolutionPrompt(e){return`Resolve these integration conflicts for ${e.framework.name}:\n\nConflicts: ${e.conflicts.join(", ")}\n\nFramework: ${e.framework.name} (${e.framework.type})\nContext: ${e.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.`}buildOptimizationPrompt(e){return`Generate optimizations for ${e.framework.name} integration:\n\nFramework: ${e.framework.name} (${e.framework.type})\nPatterns: ${e.patterns.join(", ")}\nContext: ${e.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.`}parseAnalysisResult(e){try{const t=JSON.parse(e);return{framework:t.framework||{name:"vanilla",type:"vanilla"},confidence:t.confidence||.5,patterns:t.patterns||[],conflicts:t.conflicts||[],recommendations:t.recommendations||[],integrationStrategy:t.integrationStrategy||"script",compatibilityMode:t.compatibilityMode||"modern"}}catch(e){return console.warn("Failed to parse AI analysis result:",e),this.getDefaultAnalysis()}}parseConflictResolutions(e){try{const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch(e){return console.warn("Failed to parse conflict resolutions:",e),[]}}parseOptimizations(e){try{const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch(e){return console.warn("Failed to parse optimizations:",e),[]}}performHeuristicAnalysis(e){const t=e.codeSamples.join(" ").toLowerCase();let n={name:"vanilla",type:"vanilla"},i=.5;t.includes("react")?(n={name:"react",type:"react"},i=.9):t.includes("vue")?(n={name:"vue",type:"vue"},i=.9):t.includes("angular")?(n={name:"angular",type:"angular"},i=.9):t.includes("svelte")?(n={name:"svelte",type:"svelte"},i=.9):t.includes("next")?(n={name:"nextjs",type:"nextjs"},i=.9):t.includes("nuxt")&&(n={name:"nuxt",type:"nuxt"},i=.9);let r="script";"react"===n.type||"nextjs"===n.type?r="provider":"vue"===n.type?r="plugin":"angular"===n.type&&(r="module");let a="modern";return(t.includes("require(")||t.includes("var "))&&(a="legacy"),{framework:n,confidence:i,patterns:e.codeSamples,conflicts:[],recommendations:[],integrationStrategy:r,compatibilityMode:a}}resolveConflictsHeuristic(e,t){const n=[];for(const t of e)switch(t){case"existing_humanbehavior_code":n.push("update_existing_integration");break;case"existing_provider":n.push("merge_providers");break;case"module_system_conflict":n.push("hybrid_module_support");break;default:n.push("skip_conflict")}return n}generateOptimizationsHeuristic(e,t){const n=[];switch(e.type){case"react":n.push("Use React.memo for performance optimization"),n.push("Implement error boundaries for better error tracking"),n.push("Consider using React.lazy for code splitting");break;case"vue":n.push("Use Vue 3 Composition API for better performance"),n.push("Implement proper error handling in components"),n.push("Consider using Vue Router for navigation tracking");break;case"angular":n.push("Use Angular standalone components for better tree-shaking"),n.push("Implement proper error handling with ErrorHandler"),n.push("Consider using Angular signals for state management");break;default:n.push("Enable performance tracking"),n.push("Implement error tracking"),n.push("Consider progressive enhancement")}return n}generateCacheKey(e){const t=JSON.stringify(e);return Buffer.from(t).toString("base64").substring(0,32)}isCacheValid(e){return Date.now()-e<1e3*(this.config.cacheTTL||3600)}getDefaultAnalysis(){return{framework:{name:"vanilla",type:"vanilla"},confidence:.5,patterns:[],conflicts:[],recommendations:[],integrationStrategy:"script",compatibilityMode:"modern"}}getStats(){return{cacheSize:this.cache.size,config:{model:this.config.openaiModel,maxTokens:this.config.maxTokens,temperature:this.config.temperature,caching:this.config.enableCaching},openaiAvailable:!!this.openai}}clearCache(){this.cache.clear()}},exports.InstallWizard=p,exports.LocalToolExecutor=f,exports.ManagedAgentUnavailableError=v,exports.ManagedWizardApiClient=g,exports.RemoteAIService=class{constructor(e){this.config={timeout:1e4,...e}}async analyzeCodePatterns(e){try{const t=await fetch(`${this.config.apiEndpoint}/analyze`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({codeSamples:e}),signal:AbortSignal.timeout(this.config.timeout||1e4)});if(!t.ok)throw new Error(`AI service returned ${t.status}: ${t.statusText}`);return(await t.json()).analysis}catch(t){return console.warn("Remote AI service failed, falling back to heuristic analysis:",t),this.performHeuristicAnalysis(e)}}async resolveConflicts(e,t){try{const n=await fetch(`${this.config.apiEndpoint}/resolve-conflicts`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({conflicts:e,framework:t}),signal:AbortSignal.timeout(this.config.timeout||1e4)});if(!n.ok)throw new Error(`AI service returned ${n.status}: ${n.statusText}`);return(await n.json()).resolutions||[]}catch(n){return console.warn("Remote AI conflict resolution failed, using heuristic approach:",n),this.resolveConflictsHeuristic(e,t)}}async generateOptimizations(e,t){try{const n=await fetch(`${this.config.apiEndpoint}/optimize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({framework:e,patterns:t}),signal:AbortSignal.timeout(this.config.timeout||1e4)});if(!n.ok)throw new Error(`AI service returned ${n.status}: ${n.statusText}`);return(await n.json()).optimizations||[]}catch(n){return console.warn("Remote AI optimization generation failed, using heuristic approach:",n),this.generateOptimizationsHeuristic(e,t)}}performHeuristicAnalysis(e){const t=e.join(" ").toLowerCase();let n={name:"vanilla",type:"vanilla"},i=.5;t.includes("nuxt")||t.includes("nuxtjs")||t.includes("defineNuxtConfig")||t.includes("nuxt.config")||t.includes("@nuxt/")||t.includes("useNuxtApp")||t.includes("useRuntimeConfig")||t.includes("useSeoMeta")||t.includes("useHead")||t.includes("useLazyFetch")||t.includes("useFetch")||t.includes("useAsyncData")||t.includes("#app")?(n={name:"nuxt",type:"nuxt"},i=.95):t.includes("next")||t.includes("nextjs")||t.includes("next/link")||t.includes("next/image")||t.includes("next/navigation")||t.includes("next/router")||t.includes("getserverSideProps")||t.includes("getstaticProps")||t.includes("getstaticPaths")||t.includes("app/layout")||t.includes("app/page")||t.includes("pages/")?(n={name:"nextjs",type:"nextjs"},i=.95):t.includes("gatsby")||t.includes("gatsby-browser")||t.includes("gatsby-ssr")||t.includes("gatsby-node")||t.includes("gatsby-config")||t.includes("useStaticQuery")||t.includes("graphql")?(n={name:"gatsby",type:"gatsby"},i=.95):t.includes("react")?(n={name:"react",type:"react"},i=.9):t.includes("vue")?(n={name:"vue",type:"vue"},i=.9):t.includes("angular")?(n={name:"angular",type:"angular"},i=.9):t.includes("svelte")?(n={name:"svelte",type:"svelte"},i=.9):t.includes("astro")&&(n={name:"astro",type:"astro"},i=.9);let r="script";"react"===n.type||"nextjs"===n.type||"gatsby"===n.type?r="provider":"vue"===n.type?r="plugin":"angular"===n.type&&(r="module");let a="modern";return(t.includes("require(")||t.includes("var "))&&(a="legacy"),{framework:n,confidence:i,patterns:e,conflicts:[],recommendations:[],integrationStrategy:r,compatibilityMode:a}}resolveConflictsHeuristic(e,t){const n=[];for(const t of e)switch(t){case"existing_humanbehavior_code":n.push("update_existing_integration");break;case"existing_provider":n.push("merge_providers");break;case"module_system_conflict":n.push("hybrid_module_support");break;default:n.push("skip_conflict")}return n}generateOptimizationsHeuristic(e,t){const n=[];switch(e.type){case"react":n.push("Use React.memo for performance optimization"),n.push("Implement error boundaries for better error tracking"),n.push("Consider using React.lazy for code splitting");break;case"vue":n.push("Use Vue 3 Composition API for better performance"),n.push("Implement proper error handling in components"),n.push("Consider using Vue Router for navigation tracking");break;case"angular":n.push("Use Angular standalone components for better tree-shaking"),n.push("Implement proper error handling with ErrorHandler"),n.push("Consider using Angular signals for state management");break;default:n.push("Enable performance tracking"),n.push("Implement error tracking"),n.push("Consider progressive enhancement")}return n}};
2
2
  //# sourceMappingURL=index.js.map