humanbehavior-js 0.4.15 → 0.4.17

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.
Files changed (89) hide show
  1. package/dist/cjs/wizard/index.cjs +6 -8
  2. package/dist/cjs/wizard/index.cjs.map +1 -1
  3. package/dist/cli/ai-auto-install.js +6 -8
  4. package/dist/cli/ai-auto-install.js.map +1 -1
  5. package/dist/esm/wizard/index.js +6 -8
  6. package/dist/esm/wizard/index.js.map +1 -1
  7. package/package/WIZARD_USAGE_GUIDE.md +381 -0
  8. package/package/canvas-recording-demo.html +143 -0
  9. package/package/clean-console-demo.html +39 -0
  10. package/package/dist/cjs/angular/index.cjs +14354 -0
  11. package/package/dist/cjs/angular/index.cjs.map +1 -0
  12. package/package/dist/cjs/index.cjs +14323 -0
  13. package/package/dist/cjs/index.cjs.map +1 -0
  14. package/package/dist/cjs/install-wizard.cjs +1530 -0
  15. package/package/dist/cjs/install-wizard.cjs.map +1 -0
  16. package/package/dist/cjs/react/index.cjs +14478 -0
  17. package/package/dist/cjs/react/index.cjs.map +1 -0
  18. package/package/dist/cjs/remix/index.cjs +14452 -0
  19. package/package/dist/cjs/remix/index.cjs.map +1 -0
  20. package/package/dist/cjs/svelte/index.cjs +14308 -0
  21. package/package/dist/cjs/svelte/index.cjs.map +1 -0
  22. package/package/dist/cjs/vue/index.cjs +14317 -0
  23. package/package/dist/cjs/vue/index.cjs.map +1 -0
  24. package/package/dist/cjs/wizard/index.cjs +3446 -0
  25. package/package/dist/cjs/wizard/index.cjs.map +1 -0
  26. package/package/dist/cli/ai-auto-install.cjs +57161 -0
  27. package/package/dist/cli/ai-auto-install.cjs.map +1 -0
  28. package/package/dist/cli/ai-auto-install.js +1969 -0
  29. package/package/dist/cli/ai-auto-install.js.map +1 -0
  30. package/package/dist/cli/auto-install.cjs +56352 -0
  31. package/package/dist/cli/auto-install.cjs.map +1 -0
  32. package/package/dist/cli/auto-install.js +1957 -0
  33. package/package/dist/cli/auto-install.js.map +1 -0
  34. package/package/dist/esm/angular/index.js +14350 -0
  35. package/package/dist/esm/angular/index.js.map +1 -0
  36. package/package/dist/esm/index.js +14309 -0
  37. package/package/dist/esm/index.js.map +1 -0
  38. package/package/dist/esm/install-wizard.js +1507 -0
  39. package/package/dist/esm/install-wizard.js.map +1 -0
  40. package/package/dist/esm/react/index.js +14472 -0
  41. package/package/dist/esm/react/index.js.map +1 -0
  42. package/package/dist/esm/remix/index.js +14448 -0
  43. package/package/dist/esm/remix/index.js.map +1 -0
  44. package/package/dist/esm/svelte/index.js +14306 -0
  45. package/package/dist/esm/svelte/index.js.map +1 -0
  46. package/package/dist/esm/vue/index.js +14315 -0
  47. package/package/dist/esm/vue/index.js.map +1 -0
  48. package/package/dist/esm/wizard/index.js +3415 -0
  49. package/package/dist/esm/wizard/index.js.map +1 -0
  50. package/package/dist/index.min.js +2 -0
  51. package/package/dist/index.min.js.map +1 -0
  52. package/package/dist/types/angular/index.d.ts +267 -0
  53. package/package/dist/types/index.d.ts +373 -0
  54. package/package/dist/types/install-wizard.d.ts +156 -0
  55. package/package/dist/types/react/index.d.ts +255 -0
  56. package/package/dist/types/remix/index.d.ts +246 -0
  57. package/package/dist/types/svelte/index.d.ts +232 -0
  58. package/package/dist/types/vue/index.d.ts +15 -0
  59. package/package/dist/types/wizard/index.d.ts +523 -0
  60. package/package/package.json +105 -0
  61. package/package/readme.md +281 -0
  62. package/package/rollup.config.js +422 -0
  63. package/package/simple-demo.html +26 -0
  64. package/package/simple-spa.html +838 -0
  65. package/package/src/angular/index.ts +79 -0
  66. package/package/src/api.ts +376 -0
  67. package/package/src/index.ts +28 -0
  68. package/package/src/react/AutoInstallWizard.tsx +557 -0
  69. package/package/src/react/browser.ts +8 -0
  70. package/package/src/react/index.tsx +308 -0
  71. package/package/src/redact.ts +521 -0
  72. package/package/src/remix/index.ts +16 -0
  73. package/package/src/svelte/index.ts +14 -0
  74. package/package/src/tracker.ts +1319 -0
  75. package/package/src/types/clack.d.ts +31 -0
  76. package/package/src/utils/logger.ts +144 -0
  77. package/package/src/vue/index.ts +29 -0
  78. package/package/src/wizard/README.md +114 -0
  79. package/package/src/wizard/ai/ai-install-wizard.ts +897 -0
  80. package/package/src/wizard/ai/manual-framework-wizard.ts +238 -0
  81. package/package/src/wizard/cli/ai-auto-install.ts +243 -0
  82. package/package/src/wizard/cli/auto-install.ts +224 -0
  83. package/package/src/wizard/core/install-wizard.ts +1744 -0
  84. package/package/src/wizard/index.ts +23 -0
  85. package/package/src/wizard/services/centralized-ai-service.ts +668 -0
  86. package/package/src/wizard/services/remote-ai-service.ts +240 -0
  87. package/package/tsconfig.json +24 -0
  88. package/package.json +1 -1
  89. package/src/wizard/cli/ai-auto-install.ts +4 -6
@@ -0,0 +1,3415 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import * as clack from '@clack/prompts';
4
+
5
+ /******************************************************************************
6
+ Copyright (c) Microsoft Corporation.
7
+
8
+ Permission to use, copy, modify, and/or distribute this software for any
9
+ purpose with or without fee is hereby granted.
10
+
11
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
12
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
14
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
15
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
16
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
17
+ PERFORMANCE OF THIS SOFTWARE.
18
+ ***************************************************************************** */
19
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
20
+
21
+
22
+ function __awaiter(thisArg, _arguments, P, generator) {
23
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
24
+ return new (P || (P = Promise))(function (resolve, reject) {
25
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
26
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
27
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
28
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
29
+ });
30
+ }
31
+
32
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
33
+ var e = new Error(message);
34
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
35
+ };
36
+
37
+ /**
38
+ * HumanBehavior SDK Auto-Installation Wizard
39
+ *
40
+ * This wizard automatically detects the user's framework and modifies their codebase
41
+ * to integrate the SDK with minimal user intervention.
42
+ */
43
+ class AutoInstallationWizard {
44
+ constructor(apiKey, projectRoot = process.cwd()) {
45
+ this.framework = null;
46
+ this.apiKey = apiKey;
47
+ this.projectRoot = projectRoot;
48
+ }
49
+ /**
50
+ * Simple version comparison utility
51
+ */
52
+ compareVersions(version1, version2) {
53
+ const v1Parts = version1.split('.').map(Number);
54
+ const v2Parts = version2.split('.').map(Number);
55
+ for (let i = 0; i < Math.max(v1Parts.length, v2Parts.length); i++) {
56
+ const v1 = v1Parts[i] || 0;
57
+ const v2 = v2Parts[i] || 0;
58
+ if (v1 > v2)
59
+ return 1;
60
+ if (v1 < v2)
61
+ return -1;
62
+ }
63
+ return 0;
64
+ }
65
+ isVersionGte(version, target) {
66
+ return this.compareVersions(version, target) >= 0;
67
+ }
68
+ getMajorVersion(version) {
69
+ return parseInt(version.split('.')[0]) || 0;
70
+ }
71
+ /**
72
+ * Main installation method - detects framework and auto-installs
73
+ */
74
+ install() {
75
+ return __awaiter(this, void 0, void 0, function* () {
76
+ try {
77
+ // Step 1: Detect framework
78
+ this.framework = yield this.detectFramework();
79
+ // Step 2: Install package
80
+ yield this.installPackage();
81
+ // Step 3: Generate and apply code modifications
82
+ const modifications = yield this.generateModifications();
83
+ yield this.applyModifications(modifications);
84
+ // Step 4: Generate next steps
85
+ const nextSteps = this.generateNextSteps();
86
+ return {
87
+ success: true,
88
+ framework: this.framework,
89
+ modifications,
90
+ errors: [],
91
+ nextSteps
92
+ };
93
+ }
94
+ catch (error) {
95
+ return {
96
+ success: false,
97
+ framework: this.framework || { name: 'unknown', type: 'vanilla' },
98
+ modifications: [],
99
+ errors: [error instanceof Error ? error.message : 'Unknown error'],
100
+ nextSteps: []
101
+ };
102
+ }
103
+ });
104
+ }
105
+ /**
106
+ * Detect the current framework and project setup
107
+ */
108
+ detectFramework() {
109
+ return __awaiter(this, void 0, void 0, function* () {
110
+ const packageJsonPath = path.join(this.projectRoot, 'package.json');
111
+ if (!fs.existsSync(packageJsonPath)) {
112
+ return {
113
+ name: 'vanilla',
114
+ type: 'vanilla',
115
+ projectRoot: this.projectRoot
116
+ };
117
+ }
118
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
119
+ const dependencies = Object.assign(Object.assign({}, packageJson.dependencies), packageJson.devDependencies);
120
+ // Detect framework with version information
121
+ let framework = {
122
+ name: 'vanilla',
123
+ type: 'vanilla',
124
+ projectRoot: this.projectRoot,
125
+ features: {}
126
+ };
127
+ if (dependencies.nuxt) {
128
+ const nuxtVersion = dependencies.nuxt;
129
+ const isNuxt3 = this.isVersionGte(nuxtVersion, '3.0.0');
130
+ framework = {
131
+ name: 'nuxt',
132
+ type: 'nuxt',
133
+ version: nuxtVersion,
134
+ majorVersion: this.getMajorVersion(nuxtVersion),
135
+ hasTypeScript: !!dependencies.typescript,
136
+ hasRouter: true,
137
+ projectRoot: this.projectRoot,
138
+ features: {
139
+ hasNuxt3: isNuxt3
140
+ }
141
+ };
142
+ }
143
+ else if (dependencies.next) {
144
+ const nextVersion = dependencies.next;
145
+ const isNext13 = this.isVersionGte(nextVersion, '13.0.0');
146
+ framework = {
147
+ name: 'nextjs',
148
+ type: 'nextjs',
149
+ version: nextVersion,
150
+ majorVersion: this.getMajorVersion(nextVersion),
151
+ hasTypeScript: !!dependencies.typescript || !!dependencies['@types/node'],
152
+ hasRouter: true,
153
+ projectRoot: this.projectRoot,
154
+ features: {
155
+ hasNextAppRouter: isNext13
156
+ }
157
+ };
158
+ }
159
+ else if (dependencies['@remix-run/react'] || dependencies['@remix-run/dev']) {
160
+ const remixVersion = dependencies['@remix-run/react'] || dependencies['@remix-run/dev'];
161
+ framework = {
162
+ name: 'remix',
163
+ type: 'remix',
164
+ version: remixVersion,
165
+ majorVersion: this.getMajorVersion(remixVersion),
166
+ hasTypeScript: !!dependencies.typescript || !!dependencies['@types/react'],
167
+ hasRouter: true,
168
+ projectRoot: this.projectRoot,
169
+ features: {}
170
+ };
171
+ }
172
+ else if (dependencies.react) {
173
+ const reactVersion = dependencies.react;
174
+ const isReact18 = this.isVersionGte(reactVersion, '18.0.0');
175
+ framework = {
176
+ name: 'react',
177
+ type: 'react',
178
+ version: reactVersion,
179
+ majorVersion: this.getMajorVersion(reactVersion),
180
+ hasTypeScript: !!dependencies.typescript || !!dependencies['@types/react'],
181
+ hasRouter: !!dependencies['react-router-dom'] || !!dependencies['react-router'],
182
+ projectRoot: this.projectRoot,
183
+ features: {
184
+ hasReact18: isReact18
185
+ }
186
+ };
187
+ }
188
+ else if (dependencies.vue) {
189
+ const vueVersion = dependencies.vue;
190
+ const isVue3 = this.isVersionGte(vueVersion, '3.0.0');
191
+ framework = {
192
+ name: 'vue',
193
+ type: 'vue',
194
+ version: vueVersion,
195
+ majorVersion: this.getMajorVersion(vueVersion),
196
+ hasTypeScript: !!dependencies.typescript || !!dependencies['@vue/cli-service'],
197
+ hasRouter: !!dependencies['vue-router'],
198
+ projectRoot: this.projectRoot,
199
+ features: {
200
+ hasVue3: isVue3
201
+ }
202
+ };
203
+ }
204
+ else if (dependencies['@angular/core']) {
205
+ const angularVersion = dependencies['@angular/core'];
206
+ const isAngular17 = this.isVersionGte(angularVersion, '17.0.0');
207
+ framework = {
208
+ name: 'angular',
209
+ type: 'angular',
210
+ version: angularVersion,
211
+ majorVersion: this.getMajorVersion(angularVersion),
212
+ hasTypeScript: true,
213
+ hasRouter: true,
214
+ projectRoot: this.projectRoot,
215
+ features: {
216
+ hasAngularStandalone: isAngular17
217
+ }
218
+ };
219
+ }
220
+ else if (dependencies.svelte) {
221
+ const svelteVersion = dependencies.svelte;
222
+ const isSvelteKit = !!dependencies['@sveltejs/kit'];
223
+ framework = {
224
+ name: 'svelte',
225
+ type: 'svelte',
226
+ version: svelteVersion,
227
+ majorVersion: this.getMajorVersion(svelteVersion),
228
+ hasTypeScript: !!dependencies.typescript || !!dependencies['svelte-check'],
229
+ hasRouter: !!dependencies['svelte-routing'] || !!dependencies['@sveltejs/kit'],
230
+ projectRoot: this.projectRoot,
231
+ features: {
232
+ hasSvelteKit: isSvelteKit
233
+ }
234
+ };
235
+ }
236
+ else if (dependencies.astro) {
237
+ const astroVersion = dependencies.astro;
238
+ framework = {
239
+ name: 'astro',
240
+ type: 'astro',
241
+ version: astroVersion,
242
+ majorVersion: this.getMajorVersion(astroVersion),
243
+ hasTypeScript: !!dependencies.typescript || !!dependencies['@astrojs/ts-plugin'],
244
+ hasRouter: true,
245
+ projectRoot: this.projectRoot,
246
+ features: {}
247
+ };
248
+ }
249
+ else if (dependencies.gatsby) {
250
+ const gatsbyVersion = dependencies.gatsby;
251
+ framework = {
252
+ name: 'gatsby',
253
+ type: 'gatsby',
254
+ version: gatsbyVersion,
255
+ majorVersion: this.getMajorVersion(gatsbyVersion),
256
+ hasTypeScript: !!dependencies.typescript || !!dependencies['@types/react'],
257
+ hasRouter: true,
258
+ projectRoot: this.projectRoot,
259
+ features: {}
260
+ };
261
+ }
262
+ // Detect bundler
263
+ if (dependencies.vite) {
264
+ framework.bundler = 'vite';
265
+ }
266
+ else if (dependencies.webpack) {
267
+ framework.bundler = 'webpack';
268
+ }
269
+ else if (dependencies.esbuild) {
270
+ framework.bundler = 'esbuild';
271
+ }
272
+ else if (dependencies.rollup) {
273
+ framework.bundler = 'rollup';
274
+ }
275
+ // Detect package manager
276
+ if (fs.existsSync(path.join(this.projectRoot, 'yarn.lock'))) {
277
+ framework.packageManager = 'yarn';
278
+ }
279
+ else if (fs.existsSync(path.join(this.projectRoot, 'pnpm-lock.yaml'))) {
280
+ framework.packageManager = 'pnpm';
281
+ }
282
+ else {
283
+ framework.packageManager = 'npm';
284
+ }
285
+ return framework;
286
+ });
287
+ }
288
+ /**
289
+ * Install the SDK package
290
+ */
291
+ installPackage() {
292
+ return __awaiter(this, void 0, void 0, function* () {
293
+ var _a, _b, _c, _d;
294
+ const { execSync } = yield import('child_process');
295
+ // Build base command
296
+ let command = ((_a = this.framework) === null || _a === void 0 ? void 0 : _a.packageManager) === 'yarn'
297
+ ? 'yarn add humanbehavior-js'
298
+ : ((_b = this.framework) === null || _b === void 0 ? void 0 : _b.packageManager) === 'pnpm'
299
+ ? 'pnpm add humanbehavior-js'
300
+ : 'npm install humanbehavior-js';
301
+ // Add legacy peer deps flag for npm to handle dependency conflicts
302
+ if (((_c = this.framework) === null || _c === void 0 ? void 0 : _c.packageManager) !== 'yarn' && ((_d = this.framework) === null || _d === void 0 ? void 0 : _d.packageManager) !== 'pnpm') {
303
+ command += ' --legacy-peer-deps';
304
+ }
305
+ try {
306
+ execSync(command, { cwd: this.projectRoot, stdio: 'inherit' });
307
+ }
308
+ catch (error) {
309
+ throw new Error(`Failed to install humanbehavior-js: ${error}`);
310
+ }
311
+ });
312
+ }
313
+ /**
314
+ * Generate code modifications based on framework
315
+ */
316
+ generateModifications() {
317
+ return __awaiter(this, void 0, void 0, function* () {
318
+ var _a;
319
+ const modifications = [];
320
+ switch ((_a = this.framework) === null || _a === void 0 ? void 0 : _a.type) {
321
+ case 'react':
322
+ modifications.push(...yield this.generateReactModifications());
323
+ break;
324
+ case 'nextjs':
325
+ modifications.push(...yield this.generateNextJSModifications());
326
+ break;
327
+ case 'nuxt':
328
+ modifications.push(...yield this.generateNuxtModifications());
329
+ break;
330
+ case 'astro':
331
+ modifications.push(...yield this.generateAstroModifications());
332
+ break;
333
+ case 'gatsby':
334
+ modifications.push(...yield this.generateGatsbyModifications());
335
+ break;
336
+ case 'remix':
337
+ modifications.push(...yield this.generateRemixModifications());
338
+ break;
339
+ case 'vue':
340
+ modifications.push(...yield this.generateVueModifications());
341
+ break;
342
+ case 'angular':
343
+ modifications.push(...yield this.generateAngularModifications());
344
+ break;
345
+ case 'svelte':
346
+ modifications.push(...yield this.generateSvelteModifications());
347
+ break;
348
+ default:
349
+ modifications.push(...yield this.generateVanillaModifications());
350
+ }
351
+ return modifications;
352
+ });
353
+ }
354
+ /**
355
+ * Generate React-specific modifications
356
+ */
357
+ generateReactModifications() {
358
+ return __awaiter(this, void 0, void 0, function* () {
359
+ const modifications = [];
360
+ // Find main App component or index file
361
+ const appFile = this.findReactAppFile();
362
+ if (appFile) {
363
+ const content = fs.readFileSync(appFile, 'utf8');
364
+ const modifiedContent = this.injectReactProvider(content, appFile);
365
+ modifications.push({
366
+ filePath: appFile,
367
+ action: 'modify',
368
+ content: modifiedContent,
369
+ description: 'Added HumanBehaviorProvider to React app'
370
+ });
371
+ }
372
+ // Create or append to environment file
373
+ modifications.push(this.createEnvironmentModification(this.framework));
374
+ return modifications;
375
+ });
376
+ }
377
+ /**
378
+ * Generate Next.js-specific modifications
379
+ */
380
+ generateNextJSModifications() {
381
+ return __awaiter(this, void 0, void 0, function* () {
382
+ const modifications = [];
383
+ // Check for App Router
384
+ const appLayoutFile = path.join(this.projectRoot, 'src', 'app', 'layout.tsx');
385
+ const pagesLayoutFile = path.join(this.projectRoot, 'src', 'pages', '_app.tsx');
386
+ if (fs.existsSync(appLayoutFile)) {
387
+ // Create providers.tsx file for App Router
388
+ modifications.push({
389
+ filePath: path.join(this.projectRoot, 'src', 'app', 'providers.tsx'),
390
+ action: 'create',
391
+ content: `'use client';
392
+
393
+ import { HumanBehaviorProvider } from 'humanbehavior-js/react';
394
+
395
+ export function Providers({ children }: { children: React.ReactNode }) {
396
+ return (
397
+ <HumanBehaviorProvider apiKey={process.env.NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY}>
398
+ {children}
399
+ </HumanBehaviorProvider>
400
+ );
401
+ }`,
402
+ description: 'Created providers.tsx file for Next.js App Router'
403
+ });
404
+ // Modify layout.tsx to use the provider
405
+ const content = fs.readFileSync(appLayoutFile, 'utf8');
406
+ const modifiedContent = this.injectNextJSAppRouter(content);
407
+ modifications.push({
408
+ filePath: appLayoutFile,
409
+ action: 'modify',
410
+ content: modifiedContent,
411
+ description: 'Added Providers wrapper to Next.js App Router layout'
412
+ });
413
+ }
414
+ else if (fs.existsSync(pagesLayoutFile)) {
415
+ // Create providers.tsx file for Pages Router
416
+ modifications.push({
417
+ filePath: path.join(this.projectRoot, 'src', 'components', 'providers.tsx'),
418
+ action: 'create',
419
+ content: `'use client';
420
+
421
+ import { HumanBehaviorProvider } from 'humanbehavior-js/react';
422
+
423
+ export function Providers({ children }: { children: React.ReactNode }) {
424
+ return (
425
+ <HumanBehaviorProvider apiKey={process.env.NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY}>
426
+ {children}
427
+ </HumanBehaviorProvider>
428
+ );
429
+ }`,
430
+ description: 'Created providers.tsx file for Pages Router'
431
+ });
432
+ // Modify _app.tsx to use the provider
433
+ const content = fs.readFileSync(pagesLayoutFile, 'utf8');
434
+ const modifiedContent = this.injectNextJSPagesRouter(content);
435
+ modifications.push({
436
+ filePath: pagesLayoutFile,
437
+ action: 'modify',
438
+ content: modifiedContent,
439
+ description: 'Added Providers wrapper to Next.js Pages Router'
440
+ });
441
+ }
442
+ // Create or append to environment file
443
+ modifications.push(this.createEnvironmentModification(this.framework));
444
+ return modifications;
445
+ });
446
+ }
447
+ /**
448
+ * Generate Astro-specific modifications
449
+ */
450
+ generateAstroModifications() {
451
+ return __awaiter(this, void 0, void 0, function* () {
452
+ const modifications = [];
453
+ // Create Astro component for HumanBehavior
454
+ const astroComponentPath = path.join(this.projectRoot, 'src', 'components', 'HumanBehavior.astro');
455
+ const astroComponentContent = `---
456
+ // This component will only run on the client side
457
+ ---
458
+
459
+ <script>
460
+ import { HumanBehaviorTracker } from 'humanbehavior-js';
461
+
462
+ // Get API key from environment variable
463
+ const apiKey = import.meta.env.PUBLIC_HUMANBEHAVIOR_API_KEY;
464
+
465
+ console.log('HumanBehavior: API key found:', apiKey ? 'Yes' : 'No');
466
+
467
+ if (apiKey) {
468
+ try {
469
+ const tracker = HumanBehaviorTracker.init(apiKey);
470
+ console.log('HumanBehavior: Tracker initialized successfully');
471
+
472
+ // Test event to verify tracking is working
473
+ setTimeout(() => {
474
+ tracker.customEvent('astro_page_view', {
475
+ page: window.location.pathname,
476
+ framework: 'astro'
477
+ }).then(() => {
478
+ console.log('HumanBehavior: Test event sent successfully');
479
+ }).catch((error) => {
480
+ console.error('HumanBehavior: Failed to send test event:', error);
481
+ });
482
+ }, 1000);
483
+
484
+ } catch (error) {
485
+ console.error('HumanBehavior: Failed to initialize tracker:', error);
486
+ }
487
+ } else {
488
+ console.error('HumanBehavior: No API key found');
489
+ }
490
+ </script>`;
491
+ modifications.push({
492
+ filePath: astroComponentPath,
493
+ action: 'create',
494
+ content: astroComponentContent,
495
+ description: 'Created Astro component for HumanBehavior SDK'
496
+ });
497
+ // Find and update layout file
498
+ const layoutFiles = [
499
+ path.join(this.projectRoot, 'src', 'layouts', 'Layout.astro'),
500
+ path.join(this.projectRoot, 'src', 'layouts', 'layout.astro'),
501
+ path.join(this.projectRoot, 'src', 'layouts', 'BaseLayout.astro')
502
+ ];
503
+ let layoutFile = null;
504
+ for (const file of layoutFiles) {
505
+ if (fs.existsSync(file)) {
506
+ layoutFile = file;
507
+ break;
508
+ }
509
+ }
510
+ if (layoutFile) {
511
+ const content = fs.readFileSync(layoutFile, 'utf8');
512
+ const modifiedContent = this.injectAstroLayout(content);
513
+ modifications.push({
514
+ filePath: layoutFile,
515
+ action: 'modify',
516
+ content: modifiedContent,
517
+ description: 'Added HumanBehavior component to Astro layout'
518
+ });
519
+ }
520
+ // Add environment variable
521
+ modifications.push(this.createEnvironmentModification(this.framework));
522
+ return modifications;
523
+ });
524
+ }
525
+ /**
526
+ * Generate Nuxt-specific modifications
527
+ */
528
+ generateNuxtModifications() {
529
+ return __awaiter(this, void 0, void 0, function* () {
530
+ const modifications = [];
531
+ // Create plugin file for Nuxt (in app directory)
532
+ const pluginFile = path.join(this.projectRoot, 'app', 'plugins', 'humanbehavior.client.ts');
533
+ modifications.push({
534
+ filePath: pluginFile,
535
+ action: 'create',
536
+ content: `import { HumanBehaviorTracker } from 'humanbehavior-js';
537
+
538
+ export default defineNuxtPlugin(() => {
539
+ const config = useRuntimeConfig();
540
+
541
+ // Initialize HumanBehavior SDK (client-side only)
542
+ if (typeof window !== 'undefined') {
543
+ const apiKey = config.public.humanBehaviorApiKey;
544
+ console.log('HumanBehavior: API key:', apiKey ? 'present' : 'missing');
545
+
546
+ if (apiKey) {
547
+ try {
548
+ const tracker = HumanBehaviorTracker.init(apiKey);
549
+ console.log('HumanBehavior: Tracker initialized successfully');
550
+ } catch (error) {
551
+ console.error('HumanBehavior: Failed to initialize tracker:', error);
552
+ }
553
+ } else {
554
+ console.error('HumanBehavior: No API key found in runtime config');
555
+ }
556
+ }
557
+ });`,
558
+ description: 'Created Nuxt plugin for HumanBehavior SDK in app directory'
559
+ });
560
+ // Create environment configuration
561
+ const nuxtConfigFile = path.join(this.projectRoot, 'nuxt.config.ts');
562
+ if (fs.existsSync(nuxtConfigFile)) {
563
+ const content = fs.readFileSync(nuxtConfigFile, 'utf8');
564
+ const modifiedContent = this.injectNuxtConfig(content);
565
+ modifications.push({
566
+ filePath: nuxtConfigFile,
567
+ action: 'modify',
568
+ content: modifiedContent,
569
+ description: 'Added HumanBehavior runtime config to Nuxt config'
570
+ });
571
+ }
572
+ // Create or append to environment file
573
+ modifications.push(this.createEnvironmentModification(this.framework));
574
+ return modifications;
575
+ });
576
+ }
577
+ /**
578
+ * Generate Remix-specific modifications
579
+ */
580
+ generateRemixModifications() {
581
+ return __awaiter(this, void 0, void 0, function* () {
582
+ const modifications = [];
583
+ // Find root.tsx file
584
+ const rootFile = path.join(this.projectRoot, 'app', 'root.tsx');
585
+ if (fs.existsSync(rootFile)) {
586
+ const content = fs.readFileSync(rootFile, 'utf8');
587
+ const modifiedContent = this.injectRemixProvider(content);
588
+ modifications.push({
589
+ filePath: rootFile,
590
+ action: 'modify',
591
+ content: modifiedContent,
592
+ description: 'Added HumanBehaviorProvider to Remix root component'
593
+ });
594
+ }
595
+ // Create or append to environment file
596
+ modifications.push(this.createEnvironmentModification(this.framework));
597
+ return modifications;
598
+ });
599
+ }
600
+ /**
601
+ * Generate Vue-specific modifications
602
+ */
603
+ generateVueModifications() {
604
+ return __awaiter(this, void 0, void 0, function* () {
605
+ const modifications = [];
606
+ // Find main.js or main.ts
607
+ const mainFile = this.findVueMainFile();
608
+ if (mainFile) {
609
+ const content = fs.readFileSync(mainFile, 'utf8');
610
+ const modifiedContent = this.injectVuePlugin(content);
611
+ modifications.push({
612
+ filePath: mainFile,
613
+ action: 'modify',
614
+ content: modifiedContent,
615
+ description: 'Added HumanBehaviorPlugin to Vue app'
616
+ });
617
+ }
618
+ // Create or append to environment file
619
+ modifications.push(this.createEnvironmentModification(this.framework));
620
+ return modifications;
621
+ });
622
+ }
623
+ /**
624
+ * Generate Angular-specific modifications
625
+ */
626
+ generateAngularModifications() {
627
+ return __awaiter(this, void 0, void 0, function* () {
628
+ const modifications = [];
629
+ // Check for modern Angular (standalone components) vs legacy (NgModule)
630
+ const appModuleFile = path.join(this.projectRoot, 'src', 'app', 'app.module.ts');
631
+ const appComponentFile = path.join(this.projectRoot, 'src', 'app', 'app.ts');
632
+ const mainFile = path.join(this.projectRoot, 'src', 'main.ts');
633
+ const isModernAngular = fs.existsSync(appComponentFile) && !fs.existsSync(appModuleFile);
634
+ if (isModernAngular) {
635
+ // Modern Angular 17+ with standalone components
636
+ if (fs.existsSync(mainFile)) {
637
+ const content = fs.readFileSync(mainFile, 'utf8');
638
+ const modifiedContent = this.injectAngularStandaloneInit(content);
639
+ modifications.push({
640
+ filePath: mainFile,
641
+ action: 'modify',
642
+ content: modifiedContent,
643
+ description: 'Added HumanBehavior initialization to Angular main.ts'
644
+ });
645
+ }
646
+ }
647
+ else if (fs.existsSync(appModuleFile)) {
648
+ // Legacy Angular with NgModule
649
+ const content = fs.readFileSync(appModuleFile, 'utf8');
650
+ const modifiedContent = this.injectAngularModule(content);
651
+ modifications.push({
652
+ filePath: appModuleFile,
653
+ action: 'modify',
654
+ content: modifiedContent,
655
+ description: 'Added HumanBehaviorModule to Angular app'
656
+ });
657
+ }
658
+ // Handle Angular environment file (legacy structure)
659
+ const envFile = path.join(this.projectRoot, 'src', 'environments', 'environment.ts');
660
+ if (fs.existsSync(envFile)) {
661
+ const content = fs.readFileSync(envFile, 'utf8');
662
+ if (!content.includes('humanBehaviorApiKey')) {
663
+ const modifiedContent = content.replace(/export const environment = {([\s\S]*?)};/, `export const environment = {
664
+ $1,
665
+ humanBehaviorApiKey: process.env['HUMANBEHAVIOR_API_KEY'] || ''
666
+ };`);
667
+ modifications.push({
668
+ filePath: envFile,
669
+ action: 'modify',
670
+ content: modifiedContent,
671
+ description: 'Added API key to Angular environment'
672
+ });
673
+ }
674
+ }
675
+ // Create or append to environment file
676
+ modifications.push(this.createEnvironmentModification(this.framework));
677
+ return modifications;
678
+ });
679
+ }
680
+ /**
681
+ * Generate Svelte-specific modifications
682
+ */
683
+ generateSvelteModifications() {
684
+ return __awaiter(this, void 0, void 0, function* () {
685
+ const modifications = [];
686
+ // Check for SvelteKit
687
+ const svelteConfigFile = path.join(this.projectRoot, 'svelte.config.js');
688
+ const isSvelteKit = fs.existsSync(svelteConfigFile);
689
+ if (isSvelteKit) {
690
+ // SvelteKit - create layout file
691
+ const layoutFile = path.join(this.projectRoot, 'src', 'routes', '+layout.svelte');
692
+ if (fs.existsSync(layoutFile)) {
693
+ const content = fs.readFileSync(layoutFile, 'utf8');
694
+ const modifiedContent = this.injectSvelteKitLayout(content);
695
+ modifications.push({
696
+ filePath: layoutFile,
697
+ action: 'modify',
698
+ content: modifiedContent,
699
+ description: 'Added HumanBehavior store to SvelteKit layout'
700
+ });
701
+ }
702
+ }
703
+ else {
704
+ // Regular Svelte - modify main file
705
+ const mainFile = this.findSvelteMainFile();
706
+ if (mainFile) {
707
+ const content = fs.readFileSync(mainFile, 'utf8');
708
+ const modifiedContent = this.injectSvelteStore(content);
709
+ modifications.push({
710
+ filePath: mainFile,
711
+ action: 'modify',
712
+ content: modifiedContent,
713
+ description: 'Added HumanBehavior store to Svelte app'
714
+ });
715
+ }
716
+ }
717
+ // Create or append to environment file
718
+ modifications.push(this.createEnvironmentModification(this.framework));
719
+ return modifications;
720
+ });
721
+ }
722
+ /**
723
+ * Generate vanilla JS/TS modifications
724
+ */
725
+ generateVanillaModifications() {
726
+ return __awaiter(this, void 0, void 0, function* () {
727
+ const modifications = [];
728
+ // Find HTML file to inject script
729
+ const htmlFile = this.findHTMLFile();
730
+ if (htmlFile) {
731
+ const content = fs.readFileSync(htmlFile, 'utf8');
732
+ const modifiedContent = this.injectVanillaScript(content);
733
+ modifications.push({
734
+ filePath: htmlFile,
735
+ action: 'modify',
736
+ content: modifiedContent,
737
+ description: 'Added HumanBehavior CDN script to HTML file'
738
+ });
739
+ }
740
+ // Create or append to environment file
741
+ modifications.push(this.createEnvironmentModification(this.framework));
742
+ return modifications;
743
+ });
744
+ }
745
+ /**
746
+ * Generate Gatsby-specific modifications
747
+ */
748
+ generateGatsbyModifications() {
749
+ return __awaiter(this, void 0, void 0, function* () {
750
+ const modifications = [];
751
+ // Modify or create gatsby-browser.js for Gatsby
752
+ const gatsbyBrowserFile = path.join(this.projectRoot, 'gatsby-browser.js');
753
+ if (fs.existsSync(gatsbyBrowserFile)) {
754
+ const content = fs.readFileSync(gatsbyBrowserFile, 'utf8');
755
+ const modifiedContent = this.injectGatsbyBrowser(content);
756
+ modifications.push({
757
+ filePath: gatsbyBrowserFile,
758
+ action: 'modify',
759
+ content: modifiedContent,
760
+ description: 'Added HumanBehavior initialization to Gatsby browser'
761
+ });
762
+ }
763
+ else {
764
+ // Create gatsby-browser.js if it doesn't exist
765
+ modifications.push({
766
+ filePath: gatsbyBrowserFile,
767
+ action: 'create',
768
+ content: `import { HumanBehaviorTracker } from 'humanbehavior-js';
769
+
770
+ export const onClientEntry = () => {
771
+ console.log('Gatsby browser entry point loaded');
772
+ const apiKey = process.env.GATSBY_HUMANBEHAVIOR_API_KEY;
773
+ console.log('API Key found:', apiKey ? 'Yes' : 'No');
774
+ if (apiKey) {
775
+ const tracker = HumanBehaviorTracker.init(apiKey);
776
+ console.log('HumanBehavior SDK initialized for Gatsby');
777
+ } else {
778
+ console.log('No API key found in environment variables');
779
+ }
780
+ };`,
781
+ description: 'Created gatsby-browser.js with HumanBehavior initialization'
782
+ });
783
+ }
784
+ // Create or append to environment file
785
+ modifications.push(this.createEnvironmentModification(this.framework));
786
+ return modifications;
787
+ });
788
+ }
789
+ /**
790
+ * Apply modifications to the codebase
791
+ */
792
+ applyModifications(modifications) {
793
+ return __awaiter(this, void 0, void 0, function* () {
794
+ for (const modification of modifications) {
795
+ try {
796
+ const dir = path.dirname(modification.filePath);
797
+ if (!fs.existsSync(dir)) {
798
+ fs.mkdirSync(dir, { recursive: true });
799
+ }
800
+ switch (modification.action) {
801
+ case 'create':
802
+ fs.writeFileSync(modification.filePath, modification.content);
803
+ break;
804
+ case 'modify':
805
+ fs.writeFileSync(modification.filePath, modification.content);
806
+ break;
807
+ case 'append':
808
+ fs.appendFileSync(modification.filePath, '\n' + modification.content);
809
+ break;
810
+ }
811
+ }
812
+ catch (error) {
813
+ throw new Error(`Failed to apply modification to ${modification.filePath}: ${error}`);
814
+ }
815
+ }
816
+ });
817
+ }
818
+ /**
819
+ * Generate next steps for the user
820
+ */
821
+ generateNextSteps() {
822
+ var _a, _b;
823
+ const steps = [
824
+ '✅ SDK installed and configured automatically!',
825
+ '🚀 Your app is now tracking user behavior',
826
+ '📊 View sessions in your HumanBehavior dashboard',
827
+ '🔧 Customize tracking in your code as needed'
828
+ ];
829
+ if (((_a = this.framework) === null || _a === void 0 ? void 0 : _a.type) === 'react' || ((_b = this.framework) === null || _b === void 0 ? void 0 : _b.type) === 'nextjs') {
830
+ steps.push('💡 Use the useHumanBehavior() hook to track custom events');
831
+ }
832
+ return steps;
833
+ }
834
+ // Helper methods for file detection and content injection
835
+ findReactAppFile() {
836
+ const possibleFiles = [
837
+ 'src/App.jsx', 'src/App.js', 'src/App.tsx', 'src/App.ts',
838
+ 'src/index.js', 'src/index.tsx', 'src/main.js', 'src/main.tsx'
839
+ ];
840
+ for (const file of possibleFiles) {
841
+ const fullPath = path.join(this.projectRoot, file);
842
+ if (fs.existsSync(fullPath)) {
843
+ return fullPath;
844
+ }
845
+ }
846
+ return null;
847
+ }
848
+ findVueMainFile() {
849
+ const possibleFiles = [
850
+ 'src/main.js', 'src/main.ts', 'src/main.jsx', 'src/main.tsx'
851
+ ];
852
+ for (const file of possibleFiles) {
853
+ const fullPath = path.join(this.projectRoot, file);
854
+ if (fs.existsSync(fullPath)) {
855
+ return fullPath;
856
+ }
857
+ }
858
+ return null;
859
+ }
860
+ findSvelteMainFile() {
861
+ const possibleFiles = [
862
+ 'src/main.js', 'src/main.ts', 'src/main.svelte'
863
+ ];
864
+ for (const file of possibleFiles) {
865
+ const fullPath = path.join(this.projectRoot, file);
866
+ if (fs.existsSync(fullPath)) {
867
+ return fullPath;
868
+ }
869
+ }
870
+ return null;
871
+ }
872
+ findHTMLFile() {
873
+ const possibleFiles = ['index.html', 'public/index.html', 'dist/index.html'];
874
+ for (const file of possibleFiles) {
875
+ const fullPath = path.join(this.projectRoot, file);
876
+ if (fs.existsSync(fullPath)) {
877
+ return fullPath;
878
+ }
879
+ }
880
+ return null;
881
+ }
882
+ injectReactProvider(content, filePath) {
883
+ var _a, _b, _c;
884
+ filePath.endsWith('.tsx') || filePath.endsWith('.ts');
885
+ // Check if already has HumanBehaviorProvider
886
+ if (content.includes('HumanBehaviorProvider')) {
887
+ return content;
888
+ }
889
+ // Determine the correct environment variable syntax based on bundler
890
+ const isVite = ((_a = this.framework) === null || _a === void 0 ? void 0 : _a.bundler) === 'vite';
891
+ const envVar = isVite
892
+ ? 'import.meta.env.VITE_HUMANBEHAVIOR_API_KEY!'
893
+ : 'process.env.HUMANBEHAVIOR_API_KEY!';
894
+ const importStatement = `import { HumanBehaviorProvider } from 'humanbehavior-js/react';`;
895
+ // Enhanced parsing for React 18+ features
896
+ const hasReact18 = (_c = (_b = this.framework) === null || _b === void 0 ? void 0 : _b.features) === null || _c === void 0 ? void 0 : _c.hasReact18;
897
+ // Handle different React patterns
898
+ if (content.includes('function App()') || content.includes('const App =')) {
899
+ // Add import statement
900
+ let modifiedContent = content.replace(/(import.*?from.*?['"]react['"];?)/, `$1\n${importStatement}`);
901
+ // If no React import found, add it at the top
902
+ if (!modifiedContent.includes(importStatement)) {
903
+ modifiedContent = `${importStatement}\n\n${modifiedContent}`;
904
+ }
905
+ // Wrap the App component return with HumanBehaviorProvider
906
+ modifiedContent = modifiedContent.replace(/(return\s*\([\s\S]*?\)\s*;)/, `return (
907
+ <HumanBehaviorProvider apiKey={${envVar}}>
908
+ $1
909
+ </HumanBehaviorProvider>
910
+ );`);
911
+ return modifiedContent;
912
+ }
913
+ // Handle React 18+ createRoot pattern
914
+ if (hasReact18 && content.includes('createRoot')) {
915
+ let modifiedContent = content.replace(/(import.*?from.*?['"]react['"];?)/, `$1\n${importStatement}`);
916
+ if (!modifiedContent.includes(importStatement)) {
917
+ modifiedContent = `${importStatement}\n\n${modifiedContent}`;
918
+ }
919
+ // Wrap the root render with HumanBehaviorProvider
920
+ modifiedContent = modifiedContent.replace(/(root\.render\s*\([\s\S]*?\)\s*;)/, `root.render(
921
+ <HumanBehaviorProvider apiKey={${envVar}}>
922
+ $1
923
+ </HumanBehaviorProvider>
924
+ );`);
925
+ return modifiedContent;
926
+ }
927
+ // Fallback: simple injection
928
+ return `${importStatement}\n\n${content}`;
929
+ }
930
+ injectNextJSAppRouter(content) {
931
+ if (content.includes('Providers')) {
932
+ return content;
933
+ }
934
+ const importStatement = `import { Providers } from './providers';`;
935
+ // First, add the import statement
936
+ let modifiedContent = content.replace(/export default function RootLayout/, `${importStatement}\n\nexport default function RootLayout`);
937
+ // Then wrap the body content with Providers
938
+ // Use a more specific approach to handle the body content
939
+ modifiedContent = modifiedContent.replace(/<body([^>]*)>([\s\S]*?)<\/body>/, (match, bodyAttrs, bodyContent) => {
940
+ // Trim whitespace and newlines from bodyContent
941
+ const trimmedContent = bodyContent.trim();
942
+ return `<body${bodyAttrs}>
943
+ <Providers>
944
+ ${trimmedContent}
945
+ </Providers>
946
+ </body>`;
947
+ });
948
+ return modifiedContent;
949
+ }
950
+ injectNextJSPagesRouter(content) {
951
+ if (content.includes('Providers')) {
952
+ return content;
953
+ }
954
+ const importStatement = `import { Providers } from '../components/providers';`;
955
+ return content.replace(/function MyApp/, `${importStatement}\n\nfunction MyApp`).replace(/return \(([\s\S]*?)\);/, `return (
956
+ <Providers>
957
+ $1
958
+ </Providers>
959
+ );`);
960
+ }
961
+ injectRemixProvider(content) {
962
+ if (content.includes('HumanBehaviorProvider')) {
963
+ return content;
964
+ }
965
+ const importStatement = `import { HumanBehaviorProvider, createHumanBehaviorLoader } from 'humanbehavior-js/remix';`;
966
+ const useLoaderDataImport = `import { useLoaderData } from "@remix-run/react";`;
967
+ // Add imports more robustly
968
+ let modifiedContent = content;
969
+ // Add HumanBehaviorProvider import - find the last import and add after it
970
+ if (!content.includes('HumanBehaviorProvider')) {
971
+ const lastImportIndex = modifiedContent.lastIndexOf('import');
972
+ if (lastImportIndex !== -1) {
973
+ const nextLineIndex = modifiedContent.indexOf('\n', lastImportIndex);
974
+ if (nextLineIndex !== -1) {
975
+ modifiedContent = modifiedContent.slice(0, nextLineIndex + 1) +
976
+ importStatement + '\n' +
977
+ modifiedContent.slice(nextLineIndex + 1);
978
+ }
979
+ else {
980
+ modifiedContent = modifiedContent + '\n' + importStatement;
981
+ }
982
+ }
983
+ else {
984
+ modifiedContent = importStatement + '\n' + modifiedContent;
985
+ }
986
+ }
987
+ // Add useLoaderData import - find the last import and add after it
988
+ if (!content.includes('useLoaderData')) {
989
+ const lastImportIndex = modifiedContent.lastIndexOf('import');
990
+ if (lastImportIndex !== -1) {
991
+ const nextLineIndex = modifiedContent.indexOf('\n', lastImportIndex);
992
+ if (nextLineIndex !== -1) {
993
+ modifiedContent = modifiedContent.slice(0, nextLineIndex + 1) +
994
+ useLoaderDataImport + '\n' +
995
+ modifiedContent.slice(nextLineIndex + 1);
996
+ }
997
+ else {
998
+ modifiedContent = modifiedContent + '\n' + useLoaderDataImport;
999
+ }
1000
+ }
1001
+ else {
1002
+ modifiedContent = useLoaderDataImport + '\n' + modifiedContent;
1003
+ }
1004
+ }
1005
+ // Add loader function before the App component
1006
+ if (!content.includes('export const loader')) {
1007
+ modifiedContent = modifiedContent.replace(/export default function App\(\)/, `export const loader = createHumanBehaviorLoader();
1008
+
1009
+ export default function App()`);
1010
+ }
1011
+ // Wrap the App component content with HumanBehaviorProvider
1012
+ modifiedContent = modifiedContent.replace(/export default function App\(\) \{[\s\S]*?return \(([\s\S]*?)\);[\s\S]*?\}/, `export default function App() {
1013
+ const data = useLoaderData<typeof loader>();
1014
+
1015
+ return (
1016
+ <HumanBehaviorProvider apiKey={data.ENV.HUMANBEHAVIOR_API_KEY}>
1017
+ $1
1018
+ </HumanBehaviorProvider>
1019
+ );
1020
+ }`);
1021
+ return modifiedContent;
1022
+ }
1023
+ injectVuePlugin(content) {
1024
+ var _a, _b;
1025
+ if (content.includes('HumanBehaviorPlugin')) {
1026
+ return content;
1027
+ }
1028
+ const importStatement = `import { HumanBehaviorPlugin } from 'humanbehavior-js/vue';`;
1029
+ // Enhanced Vue 3 support with version detection
1030
+ const hasVue3 = (_b = (_a = this.framework) === null || _a === void 0 ? void 0 : _a.features) === null || _b === void 0 ? void 0 : _b.hasVue3;
1031
+ if (hasVue3) {
1032
+ // Vue 3 with Composition API
1033
+ const pluginUsage = `app.use(HumanBehaviorPlugin, {
1034
+ apiKey: import.meta.env.VITE_HUMANBEHAVIOR_API_KEY
1035
+ });`;
1036
+ let modifiedContent = content;
1037
+ // Add import statement
1038
+ if (!content.includes(importStatement)) {
1039
+ modifiedContent = content.replace(/(import.*?from.*?['"]vue['"];?)/, `$1\n${importStatement}`);
1040
+ // If no Vue import found, add it at the top
1041
+ if (!modifiedContent.includes(importStatement)) {
1042
+ modifiedContent = `${importStatement}\n\n${modifiedContent}`;
1043
+ }
1044
+ }
1045
+ // Handle createApp pattern
1046
+ if (content.includes('createApp')) {
1047
+ modifiedContent = modifiedContent.replace(/(app\.mount\(.*?\))/, `${pluginUsage}\n\n$1`);
1048
+ }
1049
+ return modifiedContent;
1050
+ }
1051
+ else {
1052
+ // Vue 2 with Options API
1053
+ const pluginUsage = `Vue.use(HumanBehaviorPlugin, {
1054
+ apiKey: process.env.VUE_APP_HUMANBEHAVIOR_API_KEY
1055
+ });`;
1056
+ let modifiedContent = content;
1057
+ // Add import statement
1058
+ if (!content.includes(importStatement)) {
1059
+ modifiedContent = content.replace(/(import.*?from.*?['"]vue['"];?)/, `$1\n${importStatement}`);
1060
+ if (!modifiedContent.includes(importStatement)) {
1061
+ modifiedContent = `${importStatement}\n\n${modifiedContent}`;
1062
+ }
1063
+ }
1064
+ // Handle new Vue pattern
1065
+ if (content.includes('new Vue')) {
1066
+ modifiedContent = modifiedContent.replace(/(new Vue\(.*?\))/, `${pluginUsage}\n\n$1`);
1067
+ }
1068
+ return modifiedContent;
1069
+ }
1070
+ }
1071
+ injectAngularModule(content) {
1072
+ if (content.includes('HumanBehaviorModule')) {
1073
+ return content;
1074
+ }
1075
+ const importStatement = `import { HumanBehaviorModule } from 'humanbehavior-js/angular';`;
1076
+ const environmentImport = `import { environment } from '../environments/environment';`;
1077
+ // Add environment import if not present
1078
+ let modifiedContent = content;
1079
+ if (!content.includes('environment')) {
1080
+ modifiedContent = content.replace(/import.*from.*['"]@angular/, `${environmentImport}\n$&`);
1081
+ }
1082
+ return modifiedContent.replace(/imports:\s*\[([\s\S]*?)\]/, `imports: [
1083
+ $1,
1084
+ HumanBehaviorModule.forRoot({
1085
+ apiKey: environment.humanBehaviorApiKey
1086
+ })
1087
+ ]`).replace(/import.*from.*['"]@angular/, `$&\n${importStatement}`);
1088
+ }
1089
+ injectAngularStandaloneInit(content) {
1090
+ if (content.includes('initializeHumanBehavior')) {
1091
+ return content;
1092
+ }
1093
+ const importStatement = `import { initializeHumanBehavior } from 'humanbehavior-js/angular';`;
1094
+ // Add import at the top
1095
+ let modifiedContent = content.replace(/import.*from.*['"]@angular/, `${importStatement}\n$&`);
1096
+ // Add initialization after bootstrapApplication
1097
+ modifiedContent = modifiedContent.replace(/(bootstrapApplication\([^}]+\}?\)(?:\s*\.catch[^;]+;)?)/, `$1
1098
+
1099
+ // Initialize HumanBehavior SDK (client-side only)
1100
+ if (typeof window !== 'undefined') {
1101
+ const tracker = initializeHumanBehavior(
1102
+ '${this.apiKey}'
1103
+ );
1104
+ }`);
1105
+ return modifiedContent;
1106
+ }
1107
+ injectSvelteStore(content) {
1108
+ if (content.includes('humanBehaviorStore')) {
1109
+ return content;
1110
+ }
1111
+ const importStatement = `import { humanBehaviorStore } from 'humanbehavior-js/svelte';`;
1112
+ const initCode = `humanBehaviorStore.init(process.env.PUBLIC_HUMANBEHAVIOR_API_KEY || '');`;
1113
+ return `${importStatement}\n${initCode}\n\n${content}`;
1114
+ }
1115
+ injectSvelteKitLayout(content) {
1116
+ if (content.includes('humanBehaviorStore')) {
1117
+ return content;
1118
+ }
1119
+ const importStatement = `import { humanBehaviorStore } from 'humanbehavior-js/svelte';`;
1120
+ const envImport = `import { PUBLIC_HUMANBEHAVIOR_API_KEY } from '$env/static/public';`;
1121
+ const initCode = `humanBehaviorStore.init(PUBLIC_HUMANBEHAVIOR_API_KEY || '');`;
1122
+ // Add to script section - handle different script tag patterns
1123
+ if (content.includes('<script lang="ts">')) {
1124
+ return content.replace(/<script lang="ts">/, `<script lang="ts">\n\t${envImport}\n\t${importStatement}\n\t${initCode}`);
1125
+ }
1126
+ else if (content.includes('<script>')) {
1127
+ return content.replace(/<script>/, `<script>\n\t${envImport}\n\t${importStatement}\n\t${initCode}`);
1128
+ }
1129
+ else if (content.includes('<script context="module">')) {
1130
+ return content.replace(/<script\s+context="module">/, `<script context="module">\n\t${envImport}\n\t${importStatement}\n\t${initCode}`);
1131
+ }
1132
+ else {
1133
+ // If no script tag found, add one at the beginning
1134
+ return content.replace(/<svelte:head>/, `<script lang="ts">\n\t${envImport}\n\t${importStatement}\n\t${initCode}\n</script>\n\n<svelte:head>`);
1135
+ }
1136
+ }
1137
+ injectVanillaScript(content) {
1138
+ if (content.includes('humanbehavior-js')) {
1139
+ return content;
1140
+ }
1141
+ const cdnScript = `<script src="https://unpkg.com/humanbehavior-js@latest/dist/index.min.js"></script>`;
1142
+ const initScript = `<script>
1143
+ // Initialize HumanBehavior SDK
1144
+ // Note: For vanilla HTML, the API key must be hardcoded since env vars aren't available
1145
+ const tracker = HumanBehaviorTracker.init('${this.apiKey}');
1146
+ </script>`;
1147
+ return content.replace(/<\/head>/, ` ${cdnScript}\n ${initScript}\n</head>`);
1148
+ }
1149
+ /**
1150
+ * Inject Astro layout with HumanBehavior component
1151
+ */
1152
+ injectAstroLayout(content) {
1153
+ // Check if HumanBehavior component is already imported
1154
+ if (content.includes('HumanBehavior') || content.includes('humanbehavior-js')) {
1155
+ return content; // Already has HumanBehavior
1156
+ }
1157
+ // Add import inside frontmatter if not present
1158
+ let modifiedContent = content;
1159
+ if (!content.includes('import HumanBehavior')) {
1160
+ const importStatement = 'import HumanBehavior from \'../components/HumanBehavior.astro\';';
1161
+ const frontmatterEndIndex = content.indexOf('---', 3);
1162
+ if (frontmatterEndIndex !== -1) {
1163
+ // Insert import inside frontmatter, before the closing ---
1164
+ modifiedContent = content.slice(0, frontmatterEndIndex) + '\n' + importStatement + '\n' + content.slice(frontmatterEndIndex);
1165
+ }
1166
+ else {
1167
+ // No frontmatter, add at the very beginning
1168
+ modifiedContent = '---\n' + importStatement + '\n---\n\n' + content;
1169
+ }
1170
+ }
1171
+ // Find the closing </body> tag and add HumanBehavior component before it
1172
+ const bodyCloseIndex = modifiedContent.lastIndexOf('</body>');
1173
+ if (bodyCloseIndex === -1) {
1174
+ // No body tag found, append to end
1175
+ return modifiedContent + '\n\n<HumanBehavior />';
1176
+ }
1177
+ // Add component before closing body tag
1178
+ return modifiedContent.slice(0, bodyCloseIndex) + ' <HumanBehavior />\n' + modifiedContent.slice(bodyCloseIndex);
1179
+ }
1180
+ injectNuxtConfig(content) {
1181
+ var _a, _b;
1182
+ if (content.includes('humanBehaviorApiKey')) {
1183
+ return content;
1184
+ }
1185
+ // Enhanced Nuxt 3 support with version detection
1186
+ const hasNuxt3 = (_b = (_a = this.framework) === null || _a === void 0 ? void 0 : _a.features) === null || _b === void 0 ? void 0 : _b.hasNuxt3;
1187
+ if (hasNuxt3) {
1188
+ // Nuxt 3 with runtime config
1189
+ return content.replace(/export default defineNuxtConfig\(\{/, `export default defineNuxtConfig({
1190
+ runtimeConfig: {
1191
+ public: {
1192
+ humanBehaviorApiKey: process.env.NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY
1193
+ }
1194
+ },`);
1195
+ }
1196
+ else {
1197
+ // Nuxt 2 with env config
1198
+ return content.replace(/export default \{/, `export default {
1199
+ env: {
1200
+ humanBehaviorApiKey: process.env.HUMANBEHAVIOR_API_KEY
1201
+ },`);
1202
+ }
1203
+ }
1204
+ injectGatsbyLayout(content) {
1205
+ if (content.includes('HumanBehavior')) {
1206
+ return content;
1207
+ }
1208
+ const importStatement = `import HumanBehavior from './HumanBehavior';`;
1209
+ const componentUsage = `<HumanBehavior apiKey={process.env.GATSBY_HUMANBEHAVIOR_API_KEY || ''} />`;
1210
+ // Add import at the top
1211
+ let modifiedContent = content.replace(/import.*from.*['"]\./, `${importStatement}\n$&`);
1212
+ // Add component before closing body tag
1213
+ modifiedContent = modifiedContent.replace(/(\s*<\/body>)/, `\n ${componentUsage}\n$1`);
1214
+ return modifiedContent;
1215
+ }
1216
+ injectGatsbyBrowser(content) {
1217
+ if (content.includes('HumanBehaviorTracker')) {
1218
+ return content;
1219
+ }
1220
+ const importStatement = `import { HumanBehaviorTracker } from 'humanbehavior-js';`;
1221
+ const initCode = `
1222
+ // Initialize HumanBehavior SDK
1223
+ export const onClientEntry = () => {
1224
+ console.log('Gatsby browser entry point loaded');
1225
+ const apiKey = process.env.GATSBY_HUMANBEHAVIOR_API_KEY;
1226
+ console.log('API Key found:', apiKey ? 'Yes' : 'No');
1227
+ if (apiKey) {
1228
+ const tracker = HumanBehaviorTracker.init(apiKey);
1229
+ console.log('HumanBehavior SDK initialized for Gatsby');
1230
+ } else {
1231
+ console.log('No API key found in environment variables');
1232
+ }
1233
+ };`;
1234
+ // If the file already has content, add the import and init code
1235
+ if (content.trim()) {
1236
+ return `${importStatement}${initCode}\n\n${content}`;
1237
+ }
1238
+ else {
1239
+ // If file is empty, just return the new content
1240
+ return `${importStatement}${initCode}`;
1241
+ }
1242
+ }
1243
+ /**
1244
+ * Helper method to find the best environment file for a framework
1245
+ */
1246
+ findBestEnvFile(framework) {
1247
+ const possibleEnvFiles = [
1248
+ '.env.local',
1249
+ '.env.development.local',
1250
+ '.env.development',
1251
+ '.env.local.development',
1252
+ '.env',
1253
+ '.env.production',
1254
+ '.env.staging'
1255
+ ];
1256
+ // Framework-specific environment variable names
1257
+ const getEnvVarName = (framework) => {
1258
+ // Handle React+Vite specifically
1259
+ if (framework.type === 'react' && framework.bundler === 'vite') {
1260
+ return 'VITE_HUMANBEHAVIOR_API_KEY';
1261
+ }
1262
+ // Framework-specific mappings
1263
+ const envVarNames = {
1264
+ react: 'HUMANBEHAVIOR_API_KEY',
1265
+ nextjs: 'NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY',
1266
+ vue: 'VITE_HUMANBEHAVIOR_API_KEY',
1267
+ svelte: 'PUBLIC_HUMANBEHAVIOR_API_KEY',
1268
+ angular: 'HUMANBEHAVIOR_API_KEY',
1269
+ nuxt: 'NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY',
1270
+ remix: 'HUMANBEHAVIOR_API_KEY',
1271
+ vanilla: 'HUMANBEHAVIOR_API_KEY',
1272
+ astro: 'PUBLIC_HUMANBEHAVIOR_API_KEY',
1273
+ gatsby: 'GATSBY_HUMANBEHAVIOR_API_KEY',
1274
+ node: 'HUMANBEHAVIOR_API_KEY',
1275
+ auto: 'HUMANBEHAVIOR_API_KEY'
1276
+ };
1277
+ return envVarNames[framework.type] || 'HUMANBEHAVIOR_API_KEY';
1278
+ };
1279
+ const envVarName = getEnvVarName(framework);
1280
+ // Check for existing files
1281
+ for (const envFile of possibleEnvFiles) {
1282
+ const fullPath = path.join(this.projectRoot, envFile);
1283
+ if (fs.existsSync(fullPath)) {
1284
+ return { filePath: fullPath, envVarName };
1285
+ }
1286
+ }
1287
+ // Framework-specific default file creation
1288
+ const defaultFiles = {
1289
+ react: '.env.local',
1290
+ nextjs: '.env.local',
1291
+ vue: '.env.local',
1292
+ svelte: '.env',
1293
+ angular: '.env',
1294
+ nuxt: '.env',
1295
+ remix: '.env.local',
1296
+ vanilla: '.env',
1297
+ astro: '.env',
1298
+ gatsby: '.env.development',
1299
+ node: '.env',
1300
+ auto: '.env'
1301
+ };
1302
+ const defaultFile = defaultFiles[framework.type] || '.env';
1303
+ return {
1304
+ filePath: path.join(this.projectRoot, defaultFile),
1305
+ envVarName
1306
+ };
1307
+ }
1308
+ /**
1309
+ * Helper method to create or append to environment files
1310
+ */
1311
+ createEnvironmentModification(framework) {
1312
+ const { filePath, envVarName } = this.findBestEnvFile(framework);
1313
+ // Clean the API key to prevent formatting issues
1314
+ const cleanApiKey = this.apiKey.trim();
1315
+ if (fs.existsSync(filePath)) {
1316
+ // Check if the variable already exists
1317
+ const content = fs.readFileSync(filePath, 'utf8');
1318
+ if (content.includes(envVarName)) {
1319
+ // Variable exists, don't modify
1320
+ return {
1321
+ filePath,
1322
+ action: 'modify',
1323
+ content: content, // No change
1324
+ description: `API key already exists in ${path.basename(filePath)}`
1325
+ };
1326
+ }
1327
+ else {
1328
+ // Append to existing file
1329
+ return {
1330
+ filePath,
1331
+ action: 'append',
1332
+ content: `\n${envVarName}=${cleanApiKey}`,
1333
+ description: `Added API key to existing ${path.basename(filePath)}`
1334
+ };
1335
+ }
1336
+ }
1337
+ else {
1338
+ // Create new file
1339
+ return {
1340
+ filePath,
1341
+ action: 'create',
1342
+ content: `${envVarName}=${cleanApiKey}`,
1343
+ description: `Created ${path.basename(filePath)} with API key`
1344
+ };
1345
+ }
1346
+ }
1347
+ }
1348
+
1349
+ /**
1350
+ * AI-Enhanced HumanBehavior SDK Auto-Installation Wizard
1351
+ *
1352
+ * This wizard uses AI to intelligently detect frameworks, analyze code patterns,
1353
+ * and generate optimal integration code that's both future-proof and backward-compatible.
1354
+ *
1355
+ * 🚀 KEY FEATURES:
1356
+ * - AI-powered framework detection beyond package.json
1357
+ * - Intelligent code pattern analysis
1358
+ * - Future-proof integration strategies
1359
+ * - Backward compatibility with legacy frameworks
1360
+ * - Adaptive code generation for new frameworks
1361
+ * - Smart conflict resolution
1362
+ * - Learning from user feedback
1363
+ * - Centralized AI service (no user API keys required)
1364
+ */
1365
+ /**
1366
+ * Default AI Service Implementation
1367
+ * Uses heuristic analysis when centralized service is not available
1368
+ */
1369
+ class DefaultAIService {
1370
+ analyzeCodePatterns(codeSamples) {
1371
+ return __awaiter(this, void 0, void 0, function* () {
1372
+ return this.analyzeWithHeuristics(codeSamples);
1373
+ });
1374
+ }
1375
+ resolveConflicts(conflicts, framework) {
1376
+ return __awaiter(this, void 0, void 0, function* () {
1377
+ // Default conflict resolution strategies
1378
+ const resolutions = [];
1379
+ for (const conflict of conflicts) {
1380
+ switch (conflict) {
1381
+ case 'existing_humanbehavior_code':
1382
+ resolutions.push('update_existing_integration');
1383
+ break;
1384
+ case 'existing_provider':
1385
+ resolutions.push('merge_providers');
1386
+ break;
1387
+ case 'module_system_conflict':
1388
+ resolutions.push('hybrid_module_support');
1389
+ break;
1390
+ default:
1391
+ resolutions.push('skip_conflict');
1392
+ }
1393
+ }
1394
+ return resolutions;
1395
+ });
1396
+ }
1397
+ generateOptimizations(framework, patterns) {
1398
+ return __awaiter(this, void 0, void 0, function* () {
1399
+ const optimizations = [];
1400
+ // Framework-specific optimizations
1401
+ switch (framework.type) {
1402
+ case 'react':
1403
+ optimizations.push('Use React.memo for performance optimization');
1404
+ optimizations.push('Implement error boundaries for better error tracking');
1405
+ optimizations.push('Consider using React.lazy for code splitting');
1406
+ break;
1407
+ case 'vue':
1408
+ optimizations.push('Use Vue 3 Composition API for better performance');
1409
+ optimizations.push('Implement proper error handling in components');
1410
+ optimizations.push('Consider using Vue Router for navigation tracking');
1411
+ break;
1412
+ case 'angular':
1413
+ optimizations.push('Use Angular standalone components for better tree-shaking');
1414
+ optimizations.push('Implement proper error handling with ErrorHandler');
1415
+ optimizations.push('Consider using Angular signals for state management');
1416
+ break;
1417
+ default:
1418
+ optimizations.push('Enable performance tracking');
1419
+ optimizations.push('Implement error tracking');
1420
+ optimizations.push('Consider progressive enhancement');
1421
+ }
1422
+ return optimizations;
1423
+ });
1424
+ }
1425
+ analyzeWithHeuristics(codeSamples) {
1426
+ const patterns = codeSamples.join(' ').toLowerCase();
1427
+ // Framework detection
1428
+ let framework = { name: 'vanilla', type: 'vanilla' };
1429
+ let confidence = 0.5;
1430
+ if (patterns.includes('nuxt') || patterns.includes('nuxtjs') || patterns.includes('defineNuxtConfig') || patterns.includes('nuxt.config') || patterns.includes('@nuxt/') || patterns.includes('useNuxtApp') || patterns.includes('useRuntimeConfig') || patterns.includes('useSeoMeta') || patterns.includes('useHead') || patterns.includes('useLazyFetch') || patterns.includes('useFetch') || patterns.includes('useAsyncData') || patterns.includes('#app')) {
1431
+ framework = { name: 'nuxt', type: 'nuxt' };
1432
+ confidence = 0.95;
1433
+ }
1434
+ else if (patterns.includes('next') || patterns.includes('nextjs') || patterns.includes('next/link') || patterns.includes('next/image') || patterns.includes('next/navigation') || patterns.includes('next/router') || patterns.includes('getserverSideProps') || patterns.includes('getstaticProps') || patterns.includes('getstaticPaths') || patterns.includes('app/layout') || patterns.includes('app/page') || patterns.includes('pages/')) {
1435
+ framework = { name: 'nextjs', type: 'nextjs' };
1436
+ confidence = 0.95;
1437
+ }
1438
+ else if (patterns.includes('gatsby') || patterns.includes('gatsby-browser') || patterns.includes('gatsby-ssr') || patterns.includes('gatsby-node') || patterns.includes('gatsby-config') || patterns.includes('useStaticQuery') || patterns.includes('graphql')) {
1439
+ framework = { name: 'gatsby', type: 'gatsby' };
1440
+ confidence = 0.95;
1441
+ }
1442
+ else if (patterns.includes('react')) {
1443
+ framework = { name: 'react', type: 'react' };
1444
+ confidence = 0.9;
1445
+ }
1446
+ else if (patterns.includes('vue')) {
1447
+ framework = { name: 'vue', type: 'vue' };
1448
+ confidence = 0.9;
1449
+ }
1450
+ else if (patterns.includes('angular')) {
1451
+ framework = { name: 'angular', type: 'angular' };
1452
+ confidence = 0.9;
1453
+ }
1454
+ else if (patterns.includes('svelte')) {
1455
+ framework = { name: 'svelte', type: 'svelte' };
1456
+ confidence = 0.9;
1457
+ }
1458
+ // Integration strategy
1459
+ let integrationStrategy = 'script';
1460
+ if (framework.type === 'react' || framework.type === 'nextjs' || framework.type === 'gatsby') {
1461
+ integrationStrategy = 'provider';
1462
+ }
1463
+ else if (framework.type === 'vue') {
1464
+ integrationStrategy = 'plugin';
1465
+ }
1466
+ else if (framework.type === 'angular') {
1467
+ integrationStrategy = 'module';
1468
+ }
1469
+ // Compatibility mode
1470
+ let compatibilityMode = 'modern';
1471
+ if (patterns.includes('require(') || patterns.includes('var ')) {
1472
+ compatibilityMode = 'legacy';
1473
+ }
1474
+ return {
1475
+ framework,
1476
+ confidence,
1477
+ patterns: codeSamples,
1478
+ conflicts: [],
1479
+ recommendations: [],
1480
+ integrationStrategy,
1481
+ compatibilityMode
1482
+ };
1483
+ }
1484
+ }
1485
+ class AIEnhancedInstallationWizard extends AutoInstallationWizard {
1486
+ constructor(apiKey, projectRoot = process.cwd(), aiService) {
1487
+ super(apiKey, projectRoot);
1488
+ this.learningCache = new Map();
1489
+ this.patternDatabase = new Map();
1490
+ this.aiService = aiService || new DefaultAIService();
1491
+ this.loadLearningData();
1492
+ }
1493
+ /**
1494
+ * AI-enhanced installation with intelligent analysis
1495
+ */
1496
+ install() {
1497
+ return __awaiter(this, void 0, void 0, function* () {
1498
+ try {
1499
+ // Step 1: AI-powered framework detection
1500
+ const aiAnalysis = yield this.performAICodeAnalysis();
1501
+ // Step 2: Smart framework detection with AI validation
1502
+ this.framework = yield this.detectFrameworkWithAI(aiAnalysis);
1503
+ // Step 3: Generate AI-optimized modifications
1504
+ const modifications = yield this.generateAIOptimizedModifications(aiAnalysis);
1505
+ // Step 4: Apply modifications with conflict resolution
1506
+ yield this.applyModificationsWithAI(modifications, aiAnalysis);
1507
+ // Step 5: Generate intelligent next steps
1508
+ const nextSteps = this.generateAINextSteps(aiAnalysis);
1509
+ // Step 6: Learn from this installation
1510
+ yield this.learnFromInstallation(aiAnalysis, modifications);
1511
+ return {
1512
+ success: true,
1513
+ framework: this.framework,
1514
+ modifications,
1515
+ errors: [],
1516
+ nextSteps,
1517
+ aiAnalysis,
1518
+ learningData: {
1519
+ patterns: aiAnalysis.patterns,
1520
+ framework: this.framework.name,
1521
+ success: true
1522
+ }
1523
+ };
1524
+ }
1525
+ catch (error) {
1526
+ return {
1527
+ success: false,
1528
+ framework: this.framework || { name: 'unknown', type: 'vanilla' },
1529
+ modifications: [],
1530
+ errors: [error instanceof Error ? error.message : 'Unknown error'],
1531
+ nextSteps: [],
1532
+ aiAnalysis: {
1533
+ framework: { name: 'unknown', type: 'vanilla' },
1534
+ confidence: 0,
1535
+ patterns: [],
1536
+ conflicts: [],
1537
+ recommendations: [],
1538
+ integrationStrategy: 'script',
1539
+ compatibilityMode: 'legacy'
1540
+ },
1541
+ learningData: {
1542
+ patterns: [],
1543
+ framework: 'unknown',
1544
+ success: false
1545
+ }
1546
+ };
1547
+ }
1548
+ });
1549
+ }
1550
+ /**
1551
+ * AI-powered code analysis using centralized service
1552
+ */
1553
+ performAICodeAnalysis() {
1554
+ return __awaiter(this, void 0, void 0, function* () {
1555
+ const projectFiles = yield this.scanProjectFiles();
1556
+ const codeSamples = yield this.extractCodeSamples(projectFiles);
1557
+ // Use centralized AI service (no user API key required)
1558
+ return yield this.aiService.analyzeCodePatterns(codeSamples);
1559
+ });
1560
+ }
1561
+ /**
1562
+ * Scan project files for analysis
1563
+ */
1564
+ scanProjectFiles() {
1565
+ return __awaiter(this, void 0, void 0, function* () {
1566
+ const files = [];
1567
+ const scanDir = (dir, depth = 0) => {
1568
+ if (depth > 3)
1569
+ return; // Limit depth
1570
+ try {
1571
+ const items = fs.readdirSync(dir);
1572
+ for (const item of items) {
1573
+ const fullPath = path.join(dir, item);
1574
+ const stat = fs.statSync(fullPath);
1575
+ if (stat.isDirectory() && !item.startsWith('.') && item !== 'node_modules') {
1576
+ scanDir(fullPath, depth + 1);
1577
+ }
1578
+ else if (stat.isFile() && this.isRelevantFile(item)) {
1579
+ files.push(fullPath);
1580
+ }
1581
+ }
1582
+ }
1583
+ catch (error) {
1584
+ // Skip inaccessible directories
1585
+ }
1586
+ };
1587
+ scanDir(this.projectRoot);
1588
+ return files;
1589
+ });
1590
+ }
1591
+ /**
1592
+ * Check if file is relevant for analysis
1593
+ */
1594
+ isRelevantFile(filename) {
1595
+ const relevantExtensions = [
1596
+ '.js', '.jsx', '.ts', '.tsx', '.vue', '.svelte', '.html',
1597
+ '.json', '.config.js', '.config.ts', '.babelrc', '.eslintrc'
1598
+ ];
1599
+ const relevantNames = [
1600
+ 'package.json', 'tsconfig.json', 'vite.config', 'webpack.config',
1601
+ 'next.config', 'nuxt.config', 'angular.json', 'svelte.config',
1602
+ 'app/layout', 'app/page', 'pages/index', 'pages/_app', 'pages/_document'
1603
+ ];
1604
+ return relevantExtensions.some(ext => filename.endsWith(ext)) ||
1605
+ relevantNames.some(name => filename.includes(name));
1606
+ }
1607
+ /**
1608
+ * Extract code samples for AI analysis
1609
+ */
1610
+ extractCodeSamples(files) {
1611
+ return __awaiter(this, void 0, void 0, function* () {
1612
+ const samples = [];
1613
+ for (const file of files.slice(0, 20)) { // Limit to 20 files
1614
+ try {
1615
+ const content = fs.readFileSync(file, 'utf8');
1616
+ const relativePath = path.relative(this.projectRoot, file);
1617
+ // Extract relevant code patterns
1618
+ const patterns = this.extractCodePatterns(content);
1619
+ if (patterns.length > 0) {
1620
+ samples.push(`File: ${relativePath}\n${patterns.join('\n')}`);
1621
+ }
1622
+ }
1623
+ catch (error) {
1624
+ // Skip unreadable files
1625
+ }
1626
+ }
1627
+ return samples;
1628
+ });
1629
+ }
1630
+ /**
1631
+ * Extract relevant code patterns
1632
+ */
1633
+ extractCodePatterns(content) {
1634
+ const patterns = [];
1635
+ // Framework-specific patterns
1636
+ const frameworkPatterns = {
1637
+ react: [
1638
+ /import\s+React\s+from\s+['"]react['"]/gi,
1639
+ /from\s+['"]react['"]/gi,
1640
+ /function\s+\w+\s*\(\s*\)\s*{/gi,
1641
+ /const\s+\w+\s*=\s*\(\s*\)\s*=>\s*{/gi
1642
+ ],
1643
+ vue: [
1644
+ /import\s+{\s*createApp\s*}\s+from\s+['"]vue['"]/gi,
1645
+ /from\s+['"]vue['"]/gi,
1646
+ /<template>/gi,
1647
+ /<script\s+setup>/gi
1648
+ ],
1649
+ angular: [
1650
+ /import\s+{\s*Component\s*}\s+from\s+['"]@angular\/core['"]/gi,
1651
+ /@Component\s*\(\s*{/gi,
1652
+ /from\s+['"]@angular/gi
1653
+ ],
1654
+ svelte: [
1655
+ /<script>/gi,
1656
+ /import\s+.*\s+from\s+['"]svelte/gi,
1657
+ /from\s+['"]svelte/gi
1658
+ ],
1659
+ nextjs: [
1660
+ /import\s+.*\s+from\s+['"]next/gi,
1661
+ /from\s+['"]next/gi,
1662
+ /export\s+default\s+function\s+Page/gi,
1663
+ /export\s+default\s+function\s+Layout/gi,
1664
+ /export\s+default\s+function\s+Loading/gi,
1665
+ /export\s+default\s+function\s+Error/gi,
1666
+ /export\s+default\s+function\s+Not-found/gi,
1667
+ /useRouter\s+from\s+['"]next\/navigation['"]/gi,
1668
+ /useRouter\s+from\s+['"]next\/router['"]/gi,
1669
+ /Link\s+from\s+['"]next\/link['"]/gi,
1670
+ /Image\s+from\s+['"]next\/image['"]/gi,
1671
+ /getServerSideProps/gi,
1672
+ /getStaticProps/gi,
1673
+ /getStaticPaths/gi,
1674
+ /next\.config/gi,
1675
+ /app\/layout\.tsx/gi,
1676
+ /app\/page\.tsx/gi,
1677
+ /pages\/.*\.tsx/gi,
1678
+ /pages\/.*\.jsx/gi,
1679
+ /pages\/.*\.ts/gi,
1680
+ /pages\/.*\.js/gi
1681
+ ],
1682
+ nuxt: [
1683
+ /import\s+.*\s+from\s+['"]nuxt/gi,
1684
+ /from\s+['"]nuxt/gi,
1685
+ /export\s+default\s+defineNuxtConfig/gi,
1686
+ /defineNuxtConfig/gi,
1687
+ /nuxt\.config\.ts/gi,
1688
+ /nuxt\.config\.js/gi,
1689
+ /@nuxt\//gi,
1690
+ /#app/gi,
1691
+ /useNuxtApp/gi,
1692
+ /useRuntimeConfig/gi,
1693
+ /useSeoMeta/gi,
1694
+ /useHead/gi,
1695
+ /useLazyFetch/gi,
1696
+ /useFetch/gi,
1697
+ /useAsyncData/gi,
1698
+ /<NuxtLayout/gi,
1699
+ /<NuxtPage/gi,
1700
+ /NuxtLayout/gi,
1701
+ /NuxtPage/gi,
1702
+ /pages\/.*\.vue/gi,
1703
+ /layouts\/.*\.vue/gi,
1704
+ /components\/.*\.vue/gi,
1705
+ /composables\/.*\.ts/gi,
1706
+ /middleware\/.*\.ts/gi,
1707
+ /server\/.*\.ts/gi,
1708
+ /plugins\/.*\.ts/gi,
1709
+ /public\//gi,
1710
+ /assets\//gi,
1711
+ /content\//gi
1712
+ ]
1713
+ };
1714
+ // Extract patterns for each framework
1715
+ for (const [framework, regexes] of Object.entries(frameworkPatterns)) {
1716
+ for (const regex of regexes) {
1717
+ const matches = content.match(regex);
1718
+ if (matches) {
1719
+ // Add raw patterns for heuristic analysis
1720
+ patterns.push(...matches.slice(0, 3));
1721
+ // Also add formatted patterns for debugging
1722
+ patterns.push(`${framework.toUpperCase()}: ${matches.slice(0, 3).join(', ')}`);
1723
+ }
1724
+ }
1725
+ }
1726
+ // Extract import patterns
1727
+ const importMatches = content.match(/import\s+.*\s+from\s+['"][^'"]+['"]/gi);
1728
+ if (importMatches) {
1729
+ patterns.push(`IMPORTS: ${importMatches.slice(0, 5).join(', ')}`);
1730
+ }
1731
+ // Extract export patterns
1732
+ const exportMatches = content.match(/export\s+.*/gi);
1733
+ if (exportMatches) {
1734
+ patterns.push(`EXPORTS: ${exportMatches.slice(0, 3).join(', ')}`);
1735
+ }
1736
+ return patterns;
1737
+ }
1738
+ /**
1739
+ * AI-enhanced framework detection
1740
+ */
1741
+ detectFrameworkWithAI(aiAnalysis) {
1742
+ const _super = Object.create(null, {
1743
+ detectFramework: { get: () => super.detectFramework }
1744
+ });
1745
+ return __awaiter(this, void 0, void 0, function* () {
1746
+ // Combine AI analysis with traditional detection
1747
+ const traditionalFramework = yield _super.detectFramework.call(this);
1748
+ // Use AI analysis if confidence is high, but preserve bundler info
1749
+ if (aiAnalysis.confidence > 0.8) {
1750
+ return Object.assign(Object.assign({}, aiAnalysis.framework), { bundler: traditionalFramework.bundler, packageManager: traditionalFramework.packageManager, hasTypeScript: traditionalFramework.hasTypeScript, hasRouter: traditionalFramework.hasRouter, projectRoot: this.projectRoot });
1751
+ }
1752
+ // Merge AI insights with traditional detection
1753
+ return Object.assign(Object.assign({}, traditionalFramework), (aiAnalysis.framework.type !== 'vanilla' && {
1754
+ type: aiAnalysis.framework.type,
1755
+ name: aiAnalysis.framework.name
1756
+ }));
1757
+ });
1758
+ }
1759
+ /**
1760
+ * Generate AI-optimized modifications
1761
+ */
1762
+ generateAIOptimizedModifications(aiAnalysis) {
1763
+ const _super = Object.create(null, {
1764
+ generateModifications: { get: () => super.generateModifications }
1765
+ });
1766
+ return __awaiter(this, void 0, void 0, function* () {
1767
+ const baseModifications = yield _super.generateModifications.call(this);
1768
+ // Enhance with AI recommendations
1769
+ const enhancedModifications = baseModifications.map(mod => {
1770
+ return this.enhanceModificationWithAI(mod, aiAnalysis);
1771
+ });
1772
+ // Add AI-specific optimizations
1773
+ const aiOptimizations = this.generateAIOptimizations(aiAnalysis);
1774
+ enhancedModifications.push(...aiOptimizations);
1775
+ return enhancedModifications;
1776
+ });
1777
+ }
1778
+ /**
1779
+ * Enhance modification with AI insights
1780
+ */
1781
+ enhanceModificationWithAI(mod, aiAnalysis) {
1782
+ let enhancedContent = mod.content;
1783
+ // Add compatibility comments
1784
+ if (aiAnalysis.compatibilityMode === 'legacy') {
1785
+ enhancedContent = `// HumanBehavior SDK - Legacy Compatibility Mode\n${enhancedContent}`;
1786
+ }
1787
+ // Add future-proofing comments
1788
+ if (aiAnalysis.integrationStrategy === 'provider') {
1789
+ enhancedContent = `// HumanBehavior SDK - Provider Pattern (Future-proof)\n${enhancedContent}`;
1790
+ }
1791
+ // Add conflict resolution
1792
+ if (aiAnalysis.conflicts.length > 0) {
1793
+ enhancedContent = `// Conflict Resolution: ${aiAnalysis.conflicts.join(', ')}\n${enhancedContent}`;
1794
+ }
1795
+ return Object.assign(Object.assign({}, mod), { content: enhancedContent, description: `${mod.description} (AI-optimized)` });
1796
+ }
1797
+ /**
1798
+ * Generate AI-specific optimizations
1799
+ */
1800
+ generateAIOptimizations(aiAnalysis) {
1801
+ const optimizations = [];
1802
+ // AI optimizations are now handled through environment variables and code injection
1803
+ // No separate config file needed - everything is integrated into the existing codebase
1804
+ return optimizations;
1805
+ }
1806
+ /**
1807
+ * Apply modifications with AI conflict resolution
1808
+ */
1809
+ applyModificationsWithAI(modifications, aiAnalysis) {
1810
+ return __awaiter(this, void 0, void 0, function* () {
1811
+ for (const modification of modifications) {
1812
+ try {
1813
+ // Check for conflicts
1814
+ const conflicts = yield this.detectConflicts(modification);
1815
+ if (conflicts.length > 0) {
1816
+ // Resolve conflicts using centralized AI service
1817
+ const resolutions = yield this.aiService.resolveConflicts(conflicts, aiAnalysis.framework);
1818
+ const resolvedModification = yield this.resolveConflicts(modification, conflicts, resolutions, aiAnalysis);
1819
+ yield this.applyModification(resolvedModification);
1820
+ }
1821
+ else {
1822
+ yield this.applyModification(modification);
1823
+ }
1824
+ }
1825
+ catch (error) {
1826
+ throw new Error(`Failed to apply AI-optimized modification to ${modification.filePath}: ${error}`);
1827
+ }
1828
+ }
1829
+ });
1830
+ }
1831
+ /**
1832
+ * Detect potential conflicts
1833
+ */
1834
+ detectConflicts(modification) {
1835
+ return __awaiter(this, void 0, void 0, function* () {
1836
+ const conflicts = [];
1837
+ if (fs.existsSync(modification.filePath)) {
1838
+ const existingContent = fs.readFileSync(modification.filePath, 'utf8');
1839
+ // Check for existing HumanBehavior code
1840
+ if (existingContent.includes('HumanBehavior') || existingContent.includes('humanbehavior')) {
1841
+ conflicts.push('existing_humanbehavior_code');
1842
+ }
1843
+ // Check for conflicting providers/plugins
1844
+ if (modification.content.includes('Provider') && existingContent.includes('Provider')) {
1845
+ conflicts.push('existing_provider');
1846
+ }
1847
+ // Check for TypeScript conflicts
1848
+ if (modification.content.includes('import') && existingContent.includes('require(')) {
1849
+ conflicts.push('module_system_conflict');
1850
+ }
1851
+ }
1852
+ return conflicts;
1853
+ });
1854
+ }
1855
+ /**
1856
+ * Resolve conflicts with AI
1857
+ */
1858
+ resolveConflicts(modification, conflicts, resolutions, aiAnalysis) {
1859
+ return __awaiter(this, void 0, void 0, function* () {
1860
+ let resolvedContent = modification.content;
1861
+ for (let i = 0; i < conflicts.length; i++) {
1862
+ const conflict = conflicts[i];
1863
+ const resolution = resolutions[i];
1864
+ switch (resolution) {
1865
+ case 'update_existing_integration':
1866
+ resolvedContent = `// Updated HumanBehavior Integration\n${resolvedContent}`;
1867
+ break;
1868
+ case 'merge_providers':
1869
+ resolvedContent = resolvedContent.replace(/<HumanBehaviorProvider/g, '<HumanBehaviorProvider key="updated"');
1870
+ break;
1871
+ case 'hybrid_module_support':
1872
+ resolvedContent = `// Hybrid module system support\n${resolvedContent}`;
1873
+ break;
1874
+ case 'skip_conflict':
1875
+ // Skip this modification
1876
+ return Object.assign(Object.assign({}, modification), { content: '', description: `${modification.description} (skipped due to conflict)` });
1877
+ default:
1878
+ // Default resolution
1879
+ resolvedContent = `// Conflict resolved: ${conflict}\n${resolvedContent}`;
1880
+ }
1881
+ }
1882
+ return Object.assign(Object.assign({}, modification), { content: resolvedContent, description: `${modification.description} (conflict-resolved)` });
1883
+ });
1884
+ }
1885
+ /**
1886
+ * Apply single modification
1887
+ */
1888
+ applyModification(modification) {
1889
+ return __awaiter(this, void 0, void 0, function* () {
1890
+ if (!modification.content)
1891
+ return; // Skip empty modifications
1892
+ const dir = path.dirname(modification.filePath);
1893
+ if (!fs.existsSync(dir)) {
1894
+ fs.mkdirSync(dir, { recursive: true });
1895
+ }
1896
+ switch (modification.action) {
1897
+ case 'create':
1898
+ fs.writeFileSync(modification.filePath, modification.content);
1899
+ break;
1900
+ case 'modify':
1901
+ fs.writeFileSync(modification.filePath, modification.content);
1902
+ break;
1903
+ case 'append':
1904
+ fs.appendFileSync(modification.filePath, '\n' + modification.content);
1905
+ break;
1906
+ }
1907
+ });
1908
+ }
1909
+ /**
1910
+ * Generate AI-enhanced next steps
1911
+ */
1912
+ generateAINextSteps(aiAnalysis) {
1913
+ const steps = [
1914
+ '✅ AI-optimized SDK installation completed!',
1915
+ `🎯 Framework detected: ${aiAnalysis.framework.name} (confidence: ${Math.round(aiAnalysis.confidence * 100)}%)`,
1916
+ `🔧 Integration strategy: ${aiAnalysis.integrationStrategy}`,
1917
+ `🔄 Compatibility mode: ${aiAnalysis.compatibilityMode}`,
1918
+ '🚀 Your app is now tracking user behavior with AI-optimized configuration'
1919
+ ];
1920
+ if (aiAnalysis.recommendations.length > 0) {
1921
+ steps.push('💡 AI Recommendations:');
1922
+ aiAnalysis.recommendations.forEach(rec => steps.push(` • ${rec}`));
1923
+ }
1924
+ return steps;
1925
+ }
1926
+ /**
1927
+ * Learn from installation for future improvements
1928
+ */
1929
+ learnFromInstallation(aiAnalysis, modifications) {
1930
+ return __awaiter(this, void 0, void 0, function* () {
1931
+ const learningData = {
1932
+ timestamp: new Date().toISOString(),
1933
+ framework: aiAnalysis.framework.name,
1934
+ patterns: aiAnalysis.patterns,
1935
+ integrationStrategy: aiAnalysis.integrationStrategy,
1936
+ compatibilityMode: aiAnalysis.compatibilityMode,
1937
+ modifications: modifications.length,
1938
+ success: true
1939
+ };
1940
+ // Store learning data
1941
+ this.learningCache.set(`${aiAnalysis.framework.name}_${Date.now()}`, learningData);
1942
+ // Update pattern database
1943
+ if (!this.patternDatabase.has(aiAnalysis.framework.name)) {
1944
+ this.patternDatabase.set(aiAnalysis.framework.name, []);
1945
+ }
1946
+ this.patternDatabase.get(aiAnalysis.framework.name).push(learningData);
1947
+ // Save to disk
1948
+ yield this.saveLearningData();
1949
+ });
1950
+ }
1951
+ /**
1952
+ * Load learning data from disk
1953
+ */
1954
+ loadLearningData() {
1955
+ // Don't load learning data from user's project - keep it in memory only
1956
+ // This prevents cluttering the user's project with internal files
1957
+ }
1958
+ /**
1959
+ * Save learning data to disk
1960
+ */
1961
+ saveLearningData() {
1962
+ return __awaiter(this, void 0, void 0, function* () {
1963
+ // Don't save learning data to user's project - keep it in memory only
1964
+ // This prevents cluttering the user's project with internal files
1965
+ });
1966
+ }
1967
+ /**
1968
+ * Get AI insights for a specific framework
1969
+ */
1970
+ getAIInsights(frameworkName) {
1971
+ return this.patternDatabase.get(frameworkName) || [];
1972
+ }
1973
+ /**
1974
+ * Get learning statistics
1975
+ */
1976
+ getLearningStats() {
1977
+ const stats = {
1978
+ totalInstallations: this.learningCache.size,
1979
+ frameworks: {},
1980
+ patterns: {}
1981
+ };
1982
+ for (const [framework, data] of this.patternDatabase.entries()) {
1983
+ stats.frameworks[framework] = data.length;
1984
+ }
1985
+ return stats;
1986
+ }
1987
+ }
1988
+ /**
1989
+ * Browser-based AI installation wizard
1990
+ */
1991
+ class AIBrowserInstallationWizard {
1992
+ constructor(apiKey, aiService) {
1993
+ this.apiKey = apiKey;
1994
+ this.aiService = aiService || new DefaultAIService();
1995
+ }
1996
+ install() {
1997
+ return __awaiter(this, void 0, void 0, function* () {
1998
+ try {
1999
+ // AI-powered browser detection
2000
+ const aiAnalysis = yield this.performBrowserAIAnalysis();
2001
+ // Generate AI-optimized browser modifications
2002
+ const modifications = this.generateAIBrowserModifications(aiAnalysis);
2003
+ return {
2004
+ success: true,
2005
+ framework: aiAnalysis.framework,
2006
+ modifications,
2007
+ errors: [],
2008
+ nextSteps: [
2009
+ '✅ AI-optimized browser integration ready!',
2010
+ `🎯 Framework detected: ${aiAnalysis.framework.name}`,
2011
+ `🔧 Integration strategy: ${aiAnalysis.integrationStrategy}`,
2012
+ '📋 Copy the generated code to your project',
2013
+ '🚀 Your app will be ready to track user behavior'
2014
+ ],
2015
+ aiAnalysis,
2016
+ learningData: {
2017
+ patterns: aiAnalysis.patterns,
2018
+ framework: aiAnalysis.framework.name,
2019
+ success: true
2020
+ }
2021
+ };
2022
+ }
2023
+ catch (error) {
2024
+ return {
2025
+ success: false,
2026
+ framework: { name: 'unknown', type: 'vanilla' },
2027
+ modifications: [],
2028
+ errors: [error instanceof Error ? error.message : 'Unknown error'],
2029
+ nextSteps: [],
2030
+ aiAnalysis: {
2031
+ framework: { name: 'unknown', type: 'vanilla' },
2032
+ confidence: 0,
2033
+ patterns: [],
2034
+ conflicts: [],
2035
+ recommendations: [],
2036
+ integrationStrategy: 'script',
2037
+ compatibilityMode: 'legacy'
2038
+ },
2039
+ learningData: {
2040
+ patterns: [],
2041
+ framework: 'unknown',
2042
+ success: false
2043
+ }
2044
+ };
2045
+ }
2046
+ });
2047
+ }
2048
+ performBrowserAIAnalysis() {
2049
+ return __awaiter(this, void 0, void 0, function* () {
2050
+ // Browser-based framework detection
2051
+ this.detectBrowserFramework();
2052
+ // Analyze browser environment
2053
+ const patterns = this.analyzeBrowserPatterns();
2054
+ // Use centralized AI service for analysis
2055
+ const codeSamples = [`Browser Environment: ${patterns.join(', ')}`];
2056
+ return yield this.aiService.analyzeCodePatterns(codeSamples);
2057
+ });
2058
+ }
2059
+ detectBrowserFramework() {
2060
+ if (typeof window !== 'undefined') {
2061
+ if (window.React) {
2062
+ return { name: 'react', type: 'react' };
2063
+ }
2064
+ if (window.Vue) {
2065
+ return { name: 'vue', type: 'vue' };
2066
+ }
2067
+ if (window.angular) {
2068
+ return { name: 'angular', type: 'angular' };
2069
+ }
2070
+ }
2071
+ return { name: 'vanilla', type: 'vanilla' };
2072
+ }
2073
+ analyzeBrowserPatterns() {
2074
+ const patterns = [];
2075
+ if (typeof window !== 'undefined') {
2076
+ // Analyze global objects
2077
+ if (window.React)
2078
+ patterns.push('React global detected');
2079
+ if (window.Vue)
2080
+ patterns.push('Vue global detected');
2081
+ if (window.angular)
2082
+ patterns.push('Angular global detected');
2083
+ // Analyze DOM patterns
2084
+ if (document.querySelector('[data-reactroot]'))
2085
+ patterns.push('React DOM detected');
2086
+ if (document.querySelector('[data-vue]'))
2087
+ patterns.push('Vue DOM detected');
2088
+ // Analyze script patterns
2089
+ const scripts = document.querySelectorAll('script');
2090
+ scripts.forEach(script => {
2091
+ if (script.src.includes('react'))
2092
+ patterns.push('React script detected');
2093
+ if (script.src.includes('vue'))
2094
+ patterns.push('Vue script detected');
2095
+ });
2096
+ }
2097
+ return patterns;
2098
+ }
2099
+ generateAIBrowserModifications(aiAnalysis) {
2100
+ const modifications = [];
2101
+ switch (aiAnalysis.framework.type) {
2102
+ case 'react':
2103
+ modifications.push({
2104
+ filePath: 'App.jsx',
2105
+ action: 'create',
2106
+ content: `// AI-Optimized React Integration
2107
+ import { HumanBehaviorProvider } from 'humanbehavior-js/react';
2108
+
2109
+ function App() {
2110
+ return (
2111
+ <HumanBehaviorProvider
2112
+ apiKey="${this.apiKey}"
2113
+ config={{
2114
+ // AI-generated optimizations
2115
+ enablePerformanceTracking: true,
2116
+ enableErrorTracking: true,
2117
+ framework: '${aiAnalysis.framework.name}',
2118
+ integrationStrategy: '${aiAnalysis.integrationStrategy}'
2119
+ }}
2120
+ >
2121
+ {/* Your app components */}
2122
+ </HumanBehaviorProvider>
2123
+ );
2124
+ }
2125
+
2126
+ export default App;`,
2127
+ description: 'AI-optimized React component with HumanBehaviorProvider'
2128
+ });
2129
+ break;
2130
+ default:
2131
+ modifications.push({
2132
+ filePath: 'humanbehavior-init.js',
2133
+ action: 'create',
2134
+ content: `// AI-Optimized Vanilla JS Integration
2135
+ import { HumanBehaviorTracker } from 'humanbehavior-js';
2136
+
2137
+ const tracker = HumanBehaviorTracker.init('${this.apiKey}', {
2138
+ // AI-generated configuration
2139
+ framework: '${aiAnalysis.framework.name}',
2140
+ integrationStrategy: '${aiAnalysis.integrationStrategy}',
2141
+ compatibilityMode: '${aiAnalysis.compatibilityMode}',
2142
+ enablePerformanceTracking: true,
2143
+ enableErrorTracking: true
2144
+ });`,
2145
+ description: 'AI-optimized vanilla JS initialization'
2146
+ });
2147
+ }
2148
+ return modifications;
2149
+ }
2150
+ }
2151
+
2152
+ /**
2153
+ * Remote AI Service Implementation
2154
+ *
2155
+ * This connects to your deployed Lambda function via API Gateway
2156
+ */
2157
+ class RemoteAIService {
2158
+ constructor(config) {
2159
+ this.config = Object.assign({ timeout: 10000 }, config);
2160
+ }
2161
+ /**
2162
+ * Analyze code patterns using your deployed AI service
2163
+ */
2164
+ analyzeCodePatterns(codeSamples) {
2165
+ return __awaiter(this, void 0, void 0, function* () {
2166
+ try {
2167
+ const response = yield fetch(`${this.config.apiEndpoint}/analyze`, {
2168
+ method: 'POST',
2169
+ headers: {
2170
+ 'Content-Type': 'application/json',
2171
+ },
2172
+ body: JSON.stringify({ codeSamples }),
2173
+ signal: AbortSignal.timeout(this.config.timeout || 10000)
2174
+ });
2175
+ if (!response.ok) {
2176
+ throw new Error(`AI service returned ${response.status}: ${response.statusText}`);
2177
+ }
2178
+ const result = yield response.json();
2179
+ return result.analysis;
2180
+ }
2181
+ catch (error) {
2182
+ console.warn('Remote AI service failed, falling back to heuristic analysis:', error);
2183
+ return this.performHeuristicAnalysis(codeSamples);
2184
+ }
2185
+ });
2186
+ }
2187
+ /**
2188
+ * Resolve conflicts using your deployed AI service
2189
+ */
2190
+ resolveConflicts(conflicts, framework) {
2191
+ return __awaiter(this, void 0, void 0, function* () {
2192
+ try {
2193
+ const response = yield fetch(`${this.config.apiEndpoint}/resolve-conflicts`, {
2194
+ method: 'POST',
2195
+ headers: {
2196
+ 'Content-Type': 'application/json',
2197
+ },
2198
+ body: JSON.stringify({ conflicts, framework }),
2199
+ signal: AbortSignal.timeout(this.config.timeout || 10000)
2200
+ });
2201
+ if (!response.ok) {
2202
+ throw new Error(`AI service returned ${response.status}: ${response.statusText}`);
2203
+ }
2204
+ const result = yield response.json();
2205
+ return result.resolutions || [];
2206
+ }
2207
+ catch (error) {
2208
+ console.warn('Remote AI conflict resolution failed, using heuristic approach:', error);
2209
+ return this.resolveConflictsHeuristic(conflicts, framework);
2210
+ }
2211
+ });
2212
+ }
2213
+ /**
2214
+ * Generate optimizations using your deployed AI service
2215
+ */
2216
+ generateOptimizations(framework, patterns) {
2217
+ return __awaiter(this, void 0, void 0, function* () {
2218
+ try {
2219
+ const response = yield fetch(`${this.config.apiEndpoint}/optimize`, {
2220
+ method: 'POST',
2221
+ headers: {
2222
+ 'Content-Type': 'application/json',
2223
+ },
2224
+ body: JSON.stringify({ framework, patterns }),
2225
+ signal: AbortSignal.timeout(this.config.timeout || 10000)
2226
+ });
2227
+ if (!response.ok) {
2228
+ throw new Error(`AI service returned ${response.status}: ${response.statusText}`);
2229
+ }
2230
+ const result = yield response.json();
2231
+ return result.optimizations || [];
2232
+ }
2233
+ catch (error) {
2234
+ console.warn('Remote AI optimization generation failed, using heuristic approach:', error);
2235
+ return this.generateOptimizationsHeuristic(framework, patterns);
2236
+ }
2237
+ });
2238
+ }
2239
+ /**
2240
+ * Heuristic analysis fallback
2241
+ */
2242
+ performHeuristicAnalysis(codeSamples) {
2243
+ const patterns = codeSamples.join(' ').toLowerCase();
2244
+ // Framework detection
2245
+ let framework = { name: 'vanilla', type: 'vanilla' };
2246
+ let confidence = 0.5;
2247
+ if (patterns.includes('nuxt') || patterns.includes('nuxtjs') || patterns.includes('defineNuxtConfig') || patterns.includes('nuxt.config') || patterns.includes('@nuxt/') || patterns.includes('useNuxtApp') || patterns.includes('useRuntimeConfig') || patterns.includes('useSeoMeta') || patterns.includes('useHead') || patterns.includes('useLazyFetch') || patterns.includes('useFetch') || patterns.includes('useAsyncData') || patterns.includes('#app')) {
2248
+ framework = { name: 'nuxt', type: 'nuxt' };
2249
+ confidence = 0.95;
2250
+ }
2251
+ else if (patterns.includes('next') || patterns.includes('nextjs') || patterns.includes('next/link') || patterns.includes('next/image') || patterns.includes('next/navigation') || patterns.includes('next/router') || patterns.includes('getserverSideProps') || patterns.includes('getstaticProps') || patterns.includes('getstaticPaths') || patterns.includes('app/layout') || patterns.includes('app/page') || patterns.includes('pages/')) {
2252
+ framework = { name: 'nextjs', type: 'nextjs' };
2253
+ confidence = 0.95;
2254
+ }
2255
+ else if (patterns.includes('gatsby') || patterns.includes('gatsby-browser') || patterns.includes('gatsby-ssr') || patterns.includes('gatsby-node') || patterns.includes('gatsby-config') || patterns.includes('useStaticQuery') || patterns.includes('graphql')) {
2256
+ framework = { name: 'gatsby', type: 'gatsby' };
2257
+ confidence = 0.95;
2258
+ }
2259
+ else if (patterns.includes('react')) {
2260
+ framework = { name: 'react', type: 'react' };
2261
+ confidence = 0.9;
2262
+ }
2263
+ else if (patterns.includes('vue')) {
2264
+ framework = { name: 'vue', type: 'vue' };
2265
+ confidence = 0.9;
2266
+ }
2267
+ else if (patterns.includes('angular')) {
2268
+ framework = { name: 'angular', type: 'angular' };
2269
+ confidence = 0.9;
2270
+ }
2271
+ else if (patterns.includes('svelte')) {
2272
+ framework = { name: 'svelte', type: 'svelte' };
2273
+ confidence = 0.9;
2274
+ }
2275
+ else if (patterns.includes('astro')) {
2276
+ framework = { name: 'astro', type: 'astro' };
2277
+ confidence = 0.9;
2278
+ }
2279
+ // Integration strategy
2280
+ let integrationStrategy = 'script';
2281
+ if (framework.type === 'react' || framework.type === 'nextjs' || framework.type === 'gatsby') {
2282
+ integrationStrategy = 'provider';
2283
+ }
2284
+ else if (framework.type === 'vue') {
2285
+ integrationStrategy = 'plugin';
2286
+ }
2287
+ else if (framework.type === 'angular') {
2288
+ integrationStrategy = 'module';
2289
+ }
2290
+ // Compatibility mode
2291
+ let compatibilityMode = 'modern';
2292
+ if (patterns.includes('require(') || patterns.includes('var ')) {
2293
+ compatibilityMode = 'legacy';
2294
+ }
2295
+ return {
2296
+ framework,
2297
+ confidence,
2298
+ patterns: codeSamples,
2299
+ conflicts: [],
2300
+ recommendations: [],
2301
+ integrationStrategy,
2302
+ compatibilityMode
2303
+ };
2304
+ }
2305
+ /**
2306
+ * Heuristic conflict resolution
2307
+ */
2308
+ resolveConflictsHeuristic(conflicts, framework) {
2309
+ const resolutions = [];
2310
+ for (const conflict of conflicts) {
2311
+ switch (conflict) {
2312
+ case 'existing_humanbehavior_code':
2313
+ resolutions.push('update_existing_integration');
2314
+ break;
2315
+ case 'existing_provider':
2316
+ resolutions.push('merge_providers');
2317
+ break;
2318
+ case 'module_system_conflict':
2319
+ resolutions.push('hybrid_module_support');
2320
+ break;
2321
+ default:
2322
+ resolutions.push('skip_conflict');
2323
+ }
2324
+ }
2325
+ return resolutions;
2326
+ }
2327
+ /**
2328
+ * Heuristic optimization generation
2329
+ */
2330
+ generateOptimizationsHeuristic(framework, patterns) {
2331
+ const optimizations = [];
2332
+ switch (framework.type) {
2333
+ case 'react':
2334
+ optimizations.push('Use React.memo for performance optimization');
2335
+ optimizations.push('Implement error boundaries for better error tracking');
2336
+ optimizations.push('Consider using React.lazy for code splitting');
2337
+ break;
2338
+ case 'vue':
2339
+ optimizations.push('Use Vue 3 Composition API for better performance');
2340
+ optimizations.push('Implement proper error handling in components');
2341
+ optimizations.push('Consider using Vue Router for navigation tracking');
2342
+ break;
2343
+ case 'angular':
2344
+ optimizations.push('Use Angular standalone components for better tree-shaking');
2345
+ optimizations.push('Implement proper error handling with ErrorHandler');
2346
+ optimizations.push('Consider using Angular signals for state management');
2347
+ break;
2348
+ default:
2349
+ optimizations.push('Enable performance tracking');
2350
+ optimizations.push('Implement error tracking');
2351
+ optimizations.push('Consider progressive enhancement');
2352
+ }
2353
+ return optimizations;
2354
+ }
2355
+ }
2356
+
2357
+ /**
2358
+ * Manual Framework Installation Wizard
2359
+ *
2360
+ * This wizard allows users to manually specify their framework instead of auto-detection.
2361
+ * Useful when auto-detection fails or users want more control.
2362
+ */
2363
+ class ManualFrameworkInstallationWizard extends AutoInstallationWizard {
2364
+ constructor(apiKey, projectRoot = process.cwd(), framework) {
2365
+ super(apiKey, projectRoot);
2366
+ this.selectedFramework = framework.toLowerCase();
2367
+ this.framework = this.createFrameworkInfo(this.selectedFramework);
2368
+ }
2369
+ /**
2370
+ * Manual installation with user-specified framework
2371
+ */
2372
+ install() {
2373
+ return __awaiter(this, void 0, void 0, function* () {
2374
+ try {
2375
+ // Step 1: Handle framework selection
2376
+ if (this.selectedFramework === 'auto') {
2377
+ // Use full AI detection for "Other" option
2378
+ this.framework = yield this.runFullDetection();
2379
+ }
2380
+ else {
2381
+ // Set framework based on user selection
2382
+ this.framework = this.createFrameworkInfo(this.selectedFramework);
2383
+ if (!this.framework) {
2384
+ this.framework = { name: 'unknown', type: 'vanilla' };
2385
+ }
2386
+ // Step 2: Run full detection logic to find entry points, file names, etc.
2387
+ const detectedFramework = yield this.runFullDetection();
2388
+ // Step 3: Merge manual framework with detected details
2389
+ this.framework = Object.assign(Object.assign({}, detectedFramework), { name: this.framework.name, type: this.framework.type });
2390
+ }
2391
+ // Step 4: Install package
2392
+ yield this.installPackage();
2393
+ // Step 5: Generate and apply code modifications
2394
+ const modifications = yield this.generateModifications();
2395
+ yield this.applyModifications(modifications);
2396
+ // Step 6: Generate next steps
2397
+ const nextSteps = this.generateManualNextSteps();
2398
+ return {
2399
+ success: true,
2400
+ framework: this.framework,
2401
+ modifications,
2402
+ errors: [],
2403
+ nextSteps,
2404
+ selectedFramework: this.selectedFramework,
2405
+ manualMode: true
2406
+ };
2407
+ }
2408
+ catch (error) {
2409
+ return {
2410
+ success: false,
2411
+ framework: this.framework || { name: 'unknown', type: 'vanilla' },
2412
+ modifications: [],
2413
+ errors: [error instanceof Error ? error.message : 'Unknown error'],
2414
+ nextSteps: [],
2415
+ selectedFramework: this.selectedFramework,
2416
+ manualMode: true
2417
+ };
2418
+ }
2419
+ });
2420
+ }
2421
+ /**
2422
+ * Run full detection logic to find entry points, file names, bundler, etc.
2423
+ */
2424
+ runFullDetection() {
2425
+ return __awaiter(this, void 0, void 0, function* () {
2426
+ if (this.selectedFramework === 'auto') {
2427
+ // Use AI service for auto-detection
2428
+ const aiService = new RemoteAIService({
2429
+ apiEndpoint: 'https://ik3zxh4790.execute-api.us-east-1.amazonaws.com/prod'
2430
+ });
2431
+ // Use AI service directly for detection
2432
+ const projectFiles = yield this.scanProjectFiles();
2433
+ const codeSamples = yield this.extractCodeSamples(projectFiles);
2434
+ const aiAnalysis = yield aiService.analyzeCodePatterns(codeSamples);
2435
+ return aiAnalysis.framework;
2436
+ }
2437
+ else {
2438
+ // Use traditional detection for manual frameworks
2439
+ const tempWizard = new AutoInstallationWizard(this.apiKey, this.projectRoot);
2440
+ const detected = yield tempWizard.detectFramework();
2441
+ return detected;
2442
+ }
2443
+ });
2444
+ }
2445
+ /**
2446
+ * Scan project files for analysis
2447
+ */
2448
+ scanProjectFiles() {
2449
+ return __awaiter(this, void 0, void 0, function* () {
2450
+ const files = [];
2451
+ const scanDir = (dir, depth = 0) => {
2452
+ if (depth > 3)
2453
+ return; // Limit depth
2454
+ try {
2455
+ const items = fs.readdirSync(dir);
2456
+ for (const item of items) {
2457
+ const fullPath = path.join(dir, item);
2458
+ const stat = fs.statSync(fullPath);
2459
+ if (stat.isDirectory() && !item.startsWith('.') && item !== 'node_modules') {
2460
+ scanDir(fullPath, depth + 1);
2461
+ }
2462
+ else if (stat.isFile() && this.isRelevantFile(item)) {
2463
+ files.push(fullPath);
2464
+ }
2465
+ }
2466
+ }
2467
+ catch (error) {
2468
+ // Skip inaccessible directories
2469
+ }
2470
+ };
2471
+ scanDir(this.projectRoot);
2472
+ return files;
2473
+ });
2474
+ }
2475
+ /**
2476
+ * Check if file is relevant for analysis
2477
+ */
2478
+ isRelevantFile(filename) {
2479
+ const relevantExtensions = [
2480
+ '.js', '.jsx', '.ts', '.tsx', '.vue', '.svelte', '.html',
2481
+ '.json', '.config.js', '.config.ts', '.babelrc', '.eslintrc'
2482
+ ];
2483
+ const relevantNames = [
2484
+ 'package.json', 'tsconfig.json', 'vite.config', 'webpack.config',
2485
+ 'next.config', 'nuxt.config', 'angular.json', 'svelte.config'
2486
+ ];
2487
+ return relevantExtensions.some(ext => filename.endsWith(ext)) ||
2488
+ relevantNames.some(name => filename.includes(name));
2489
+ }
2490
+ /**
2491
+ * Extract code samples for AI analysis
2492
+ */
2493
+ extractCodeSamples(files) {
2494
+ return __awaiter(this, void 0, void 0, function* () {
2495
+ const samples = [];
2496
+ for (const file of files.slice(0, 20)) { // Limit to 20 files
2497
+ try {
2498
+ const content = fs.readFileSync(file, 'utf8');
2499
+ const relativePath = path.relative(this.projectRoot, file);
2500
+ samples.push(`File: ${relativePath}\n${content.substring(0, 1000)}`);
2501
+ }
2502
+ catch (error) {
2503
+ // Skip unreadable files
2504
+ }
2505
+ }
2506
+ return samples;
2507
+ });
2508
+ }
2509
+ /**
2510
+ * Create framework info based on user selection
2511
+ */
2512
+ createFrameworkInfo(framework) {
2513
+ const frameworkMap = {
2514
+ 'react': { name: 'react', type: 'react' },
2515
+ 'nextjs': { name: 'nextjs', type: 'nextjs' },
2516
+ 'next': { name: 'nextjs', type: 'nextjs' },
2517
+ 'vue': { name: 'vue', type: 'vue' },
2518
+ 'nuxt': { name: 'nuxt', type: 'nuxt' },
2519
+ 'nuxtjs': { name: 'nuxt', type: 'nuxt' },
2520
+ 'angular': { name: 'angular', type: 'angular' },
2521
+ 'svelte': { name: 'svelte', type: 'svelte' },
2522
+ 'sveltekit': { name: 'svelte', type: 'svelte' },
2523
+ 'remix': { name: 'remix', type: 'remix' },
2524
+ 'astro': { name: 'astro', type: 'astro' },
2525
+ 'gatsby': { name: 'gatsby', type: 'gatsby' },
2526
+ 'vanilla': { name: 'vanilla', type: 'vanilla' },
2527
+ 'node': { name: 'node', type: 'node' },
2528
+ 'auto': { name: 'auto-detected', type: 'auto' }
2529
+ };
2530
+ return frameworkMap[framework] || { name: framework, type: 'vanilla' };
2531
+ }
2532
+ /**
2533
+ * Override framework detection to use manual selection
2534
+ */
2535
+ detectFramework() {
2536
+ return __awaiter(this, void 0, void 0, function* () {
2537
+ return this.framework || { name: 'unknown', type: 'vanilla' };
2538
+ });
2539
+ }
2540
+ /**
2541
+ * Generate next steps with manual mode info
2542
+ */
2543
+ generateManualNextSteps() {
2544
+ var _a;
2545
+ return [
2546
+ '✅ Manual framework installation completed!',
2547
+ `🎯 Selected framework: ${((_a = this.framework) === null || _a === void 0 ? void 0 : _a.name) || 'unknown'}`,
2548
+ `🔧 Integration strategy: ${this.getIntegrationStrategy()}`,
2549
+ '🚀 Your app is now ready to track user behavior',
2550
+ '📊 View sessions in your HumanBehavior dashboard'
2551
+ ];
2552
+ }
2553
+ /**
2554
+ * Get integration strategy based on framework
2555
+ */
2556
+ getIntegrationStrategy() {
2557
+ var _a;
2558
+ if (!((_a = this.framework) === null || _a === void 0 ? void 0 : _a.type))
2559
+ return 'script';
2560
+ switch (this.framework.type) {
2561
+ case 'react':
2562
+ case 'nextjs':
2563
+ return 'provider';
2564
+ case 'vue':
2565
+ return 'plugin';
2566
+ case 'angular':
2567
+ return 'module';
2568
+ default:
2569
+ return 'script';
2570
+ }
2571
+ }
2572
+ }
2573
+
2574
+ /**
2575
+ * AI-Enhanced HumanBehavior SDK Auto-Installation CLI
2576
+ *
2577
+ * Usage: npx humanbehavior-js ai-auto-install [api-key]
2578
+ *
2579
+ * This tool uses AI to intelligently detect frameworks, analyze code patterns,
2580
+ * and generate optimal integration code that's both future-proof and backward-compatible.
2581
+ */
2582
+ class AIAutoInstallCLI {
2583
+ constructor(options) {
2584
+ this.options = options;
2585
+ }
2586
+ run() {
2587
+ return __awaiter(this, void 0, void 0, function* () {
2588
+ clack.intro('🤖 AI-Enhanced HumanBehavior SDK Auto-Installation');
2589
+ try {
2590
+ // Get API key
2591
+ const apiKey = yield this.getApiKey();
2592
+ if (!apiKey) {
2593
+ clack.cancel('API key is required');
2594
+ process.exit(1);
2595
+ }
2596
+ // Get project path
2597
+ const projectPath = this.options.projectPath || process.cwd();
2598
+ // Choose framework
2599
+ const framework = yield this.chooseFramework();
2600
+ if (!framework) {
2601
+ clack.cancel('Installation cancelled.');
2602
+ process.exit(0);
2603
+ }
2604
+ // Confirm installation
2605
+ if (!this.options.yes) {
2606
+ const confirmed = yield this.confirmInstallation(projectPath, framework);
2607
+ if (!confirmed) {
2608
+ clack.cancel('Installation cancelled.');
2609
+ process.exit(0);
2610
+ }
2611
+ }
2612
+ // Run installation
2613
+ const spinner = clack.spinner();
2614
+ spinner.start('🔍 Analyzing your project with AI...');
2615
+ const wizard = new ManualFrameworkInstallationWizard(apiKey, projectPath, framework);
2616
+ const result = yield wizard.install();
2617
+ spinner.stop('Analysis complete!');
2618
+ // Display results
2619
+ this.displayResults(result, framework);
2620
+ }
2621
+ catch (error) {
2622
+ clack.cancel(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`);
2623
+ process.exit(1);
2624
+ }
2625
+ });
2626
+ }
2627
+ getApiKey() {
2628
+ return __awaiter(this, void 0, void 0, function* () {
2629
+ if (this.options.apiKey) {
2630
+ return this.options.apiKey;
2631
+ }
2632
+ const apiKey = yield clack.text({
2633
+ message: 'Enter your HumanBehavior API key:',
2634
+ placeholder: 'hb_...',
2635
+ validate: (value) => {
2636
+ if (!value)
2637
+ return 'API key is required';
2638
+ if (!value.startsWith('hb_'))
2639
+ return 'API key should start with "hb_"';
2640
+ return undefined;
2641
+ }
2642
+ });
2643
+ return apiKey;
2644
+ });
2645
+ }
2646
+ confirmInstallation(projectPath, framework) {
2647
+ return __awaiter(this, void 0, void 0, function* () {
2648
+ const confirmed = yield clack.confirm({
2649
+ message: `Ready to install HumanBehavior SDK in ${projectPath} for ${framework}?`
2650
+ });
2651
+ return confirmed;
2652
+ });
2653
+ }
2654
+ chooseFramework() {
2655
+ return __awaiter(this, void 0, void 0, function* () {
2656
+ const framework = yield clack.select({
2657
+ message: 'Select your framework:',
2658
+ options: [
2659
+ { label: 'React', value: 'react' },
2660
+ { label: 'Next.js', value: 'nextjs' },
2661
+ { label: 'Vue', value: 'vue' },
2662
+ { label: 'Angular', value: 'angular' },
2663
+ { label: 'Svelte', value: 'svelte' },
2664
+ { label: 'Nuxt.js', value: 'nuxt' },
2665
+ { label: 'Remix', value: 'remix' },
2666
+ { label: 'Astro', value: 'astro' },
2667
+ { label: 'Gatsby', value: 'gatsby' },
2668
+ { label: 'Vanilla JS/TS', value: 'vanilla' }
2669
+ ]
2670
+ });
2671
+ return framework;
2672
+ });
2673
+ }
2674
+ displayResults(result, framework) {
2675
+ if (result.success) {
2676
+ clack.outro('🎉 Installation completed successfully!');
2677
+ // Display framework info
2678
+ clack.note(`Framework detected: ${result.framework.name} (${result.framework.type})`, 'Framework Info');
2679
+ // Display modifications
2680
+ if (result.modifications && result.modifications.length > 0) {
2681
+ const modifications = result.modifications.map((mod) => `${mod.action}: ${mod.filePath} - ${mod.description}`);
2682
+ clack.note(modifications.join('\n'), 'Files Modified');
2683
+ }
2684
+ // Display next steps
2685
+ if (result.nextSteps && result.nextSteps.length > 0) {
2686
+ clack.note(result.nextSteps.join('\n'), 'Next Steps');
2687
+ }
2688
+ // Display AI insights if available
2689
+ if (result.aiAnalysis) {
2690
+ clack.note(`Confidence: ${Math.round(result.aiAnalysis.confidence * 100)}%`, 'AI Analysis');
2691
+ if (result.aiAnalysis.recommendations && result.aiAnalysis.recommendations.length > 0) {
2692
+ clack.note(result.aiAnalysis.recommendations.join('\n'), 'AI Recommendations');
2693
+ }
2694
+ }
2695
+ }
2696
+ else {
2697
+ clack.cancel('Installation failed');
2698
+ if (result.errors && result.errors.length > 0) {
2699
+ clack.note(result.errors.join('\n'), 'Errors');
2700
+ }
2701
+ }
2702
+ }
2703
+ }
2704
+ function parseArgs$1() {
2705
+ const args = process.argv.slice(2);
2706
+ const options = {};
2707
+ for (let i = 0; i < args.length; i++) {
2708
+ const arg = args[i];
2709
+ switch (arg) {
2710
+ case '--help':
2711
+ case '-h':
2712
+ showHelp$1();
2713
+ process.exit(0);
2714
+ break;
2715
+ case '--yes':
2716
+ case '-y':
2717
+ options.yes = true;
2718
+ break;
2719
+ case '--dry-run':
2720
+ options.dryRun = true;
2721
+ break;
2722
+ case '--project':
2723
+ case '-p':
2724
+ options.projectPath = args[++i];
2725
+ break;
2726
+ case '--framework':
2727
+ case '-f':
2728
+ options.framework = args[++i];
2729
+ break;
2730
+ default:
2731
+ if (!options.apiKey && !arg.startsWith('-')) {
2732
+ options.apiKey = arg;
2733
+ }
2734
+ break;
2735
+ }
2736
+ }
2737
+ return options;
2738
+ }
2739
+ function showHelp$1() {
2740
+ console.log(`
2741
+ 🤖 HumanBehavior SDK AI Auto-Installation
2742
+
2743
+ Usage: npx humanbehavior-js ai-auto-install [api-key] [options]
2744
+
2745
+ Options:
2746
+ -h, --help Show this help message
2747
+ -y, --yes Skip all prompts and use defaults
2748
+ --dry-run Show what would be changed without making changes
2749
+
2750
+ -p, --project <path> Specify project directory
2751
+ -f, --framework <name> Specify framework manually
2752
+
2753
+ Examples:
2754
+ npx humanbehavior-js ai-auto-install
2755
+ npx humanbehavior-js ai-auto-install hb_your_api_key_here
2756
+ npx humanbehavior-js ai-auto-install --project ./my-app --ai
2757
+ npx humanbehavior-js ai-auto-install --framework react --yes
2758
+ `);
2759
+ }
2760
+ // Main execution
2761
+ if (import.meta.url === `file://${process.argv[1]}`) {
2762
+ const options = parseArgs$1();
2763
+ const cli = new AIAutoInstallCLI(options);
2764
+ cli.run().catch((error) => {
2765
+ clack.cancel(`Unexpected error: ${error.message}`);
2766
+ process.exit(1);
2767
+ });
2768
+ }
2769
+
2770
+ /**
2771
+ * HumanBehavior SDK Auto-Installation CLI
2772
+ *
2773
+ * Usage: npx humanbehavior-js auto-install [api-key]
2774
+ *
2775
+ * This tool automatically detects the user's framework and modifies their codebase
2776
+ * to integrate the SDK with minimal user intervention.
2777
+ */
2778
+ class AutoInstallCLI {
2779
+ constructor(options) {
2780
+ this.options = options;
2781
+ }
2782
+ run() {
2783
+ return __awaiter(this, void 0, void 0, function* () {
2784
+ clack.intro('🚀 HumanBehavior SDK Auto-Installation');
2785
+ try {
2786
+ // Get API key
2787
+ const apiKey = yield this.getApiKey();
2788
+ if (!apiKey) {
2789
+ clack.cancel('API key is required');
2790
+ process.exit(1);
2791
+ }
2792
+ // Get project path
2793
+ const projectPath = this.options.projectPath || process.cwd();
2794
+ // Choose framework
2795
+ const framework = yield this.chooseFramework();
2796
+ if (!framework) {
2797
+ clack.cancel('Installation cancelled.');
2798
+ process.exit(0);
2799
+ }
2800
+ // Confirm installation
2801
+ if (!this.options.yes) {
2802
+ const confirmed = yield this.confirmInstallation(projectPath, framework);
2803
+ if (!confirmed) {
2804
+ clack.cancel('Installation cancelled.');
2805
+ process.exit(0);
2806
+ }
2807
+ }
2808
+ // Run installation
2809
+ const spinner = clack.spinner();
2810
+ spinner.start('🔍 Analyzing your project...');
2811
+ const wizard = new ManualFrameworkInstallationWizard(apiKey, projectPath, framework);
2812
+ const result = yield wizard.install();
2813
+ spinner.stop('Detection complete!');
2814
+ // Display results
2815
+ this.displayResults(result);
2816
+ }
2817
+ catch (error) {
2818
+ clack.cancel(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`);
2819
+ process.exit(1);
2820
+ }
2821
+ });
2822
+ }
2823
+ getApiKey() {
2824
+ return __awaiter(this, void 0, void 0, function* () {
2825
+ if (this.options.apiKey) {
2826
+ return this.options.apiKey;
2827
+ }
2828
+ const apiKey = yield clack.text({
2829
+ message: 'Enter your HumanBehavior API key:',
2830
+ placeholder: 'hb_...',
2831
+ validate: (value) => {
2832
+ if (!value)
2833
+ return 'API key is required';
2834
+ if (!value.startsWith('hb_'))
2835
+ return 'API key should start with "hb_"';
2836
+ return undefined;
2837
+ }
2838
+ });
2839
+ return apiKey;
2840
+ });
2841
+ }
2842
+ chooseFramework() {
2843
+ return __awaiter(this, void 0, void 0, function* () {
2844
+ const framework = yield clack.select({
2845
+ message: 'Select your framework:',
2846
+ options: [
2847
+ { label: 'React', value: 'react' },
2848
+ { label: 'Next.js', value: 'nextjs' },
2849
+ { label: 'Vue', value: 'vue' },
2850
+ { label: 'Angular', value: 'angular' },
2851
+ { label: 'Svelte', value: 'svelte' },
2852
+ { label: 'Nuxt.js', value: 'nuxt' },
2853
+ { label: 'Remix', value: 'remix' },
2854
+ { label: 'Astro', value: 'astro' },
2855
+ { label: 'Gatsby', value: 'gatsby' },
2856
+ { label: 'Vanilla JS/TS', value: 'vanilla' }
2857
+ ]
2858
+ });
2859
+ return framework;
2860
+ });
2861
+ }
2862
+ confirmInstallation(projectPath, framework) {
2863
+ return __awaiter(this, void 0, void 0, function* () {
2864
+ const confirmed = yield clack.confirm({
2865
+ message: `Ready to install HumanBehavior SDK in ${projectPath} for ${framework}?`
2866
+ });
2867
+ return confirmed;
2868
+ });
2869
+ }
2870
+ displayResults(result) {
2871
+ if (result.success) {
2872
+ clack.outro('🎉 Installation completed successfully!');
2873
+ // Display framework info
2874
+ clack.note(`Framework detected: ${result.framework.name} (${result.framework.type})`, 'Framework Info');
2875
+ // Display modifications
2876
+ if (result.modifications && result.modifications.length > 0) {
2877
+ const modifications = result.modifications.map((mod) => `${mod.action}: ${mod.filePath} - ${mod.description}`);
2878
+ clack.note(modifications.join('\n'), 'Files Modified');
2879
+ }
2880
+ // Display next steps
2881
+ if (result.nextSteps && result.nextSteps.length > 0) {
2882
+ clack.note(result.nextSteps.join('\n'), 'Next Steps');
2883
+ }
2884
+ }
2885
+ else {
2886
+ clack.cancel('Installation failed');
2887
+ if (result.errors && result.errors.length > 0) {
2888
+ clack.note(result.errors.join('\n'), 'Errors');
2889
+ }
2890
+ }
2891
+ }
2892
+ }
2893
+ function parseArgs() {
2894
+ const args = process.argv.slice(2);
2895
+ const options = {};
2896
+ for (let i = 0; i < args.length; i++) {
2897
+ const arg = args[i];
2898
+ switch (arg) {
2899
+ case '--help':
2900
+ case '-h':
2901
+ showHelp();
2902
+ process.exit(0);
2903
+ break;
2904
+ case '--yes':
2905
+ case '-y':
2906
+ options.yes = true;
2907
+ break;
2908
+ case '--dry-run':
2909
+ options.dryRun = true;
2910
+ break;
2911
+ case '--project':
2912
+ case '-p':
2913
+ options.projectPath = args[++i];
2914
+ break;
2915
+ default:
2916
+ if (!options.apiKey && !arg.startsWith('-')) {
2917
+ options.apiKey = arg;
2918
+ }
2919
+ break;
2920
+ }
2921
+ }
2922
+ return options;
2923
+ }
2924
+ function showHelp() {
2925
+ console.log(`
2926
+ 🚀 HumanBehavior SDK Auto-Installation
2927
+
2928
+ Usage: npx humanbehavior-js auto-install [api-key] [options]
2929
+
2930
+ This tool automatically detects your framework and integrates the HumanBehavior SDK.
2931
+
2932
+ Options:
2933
+ -h, --help Show this help message
2934
+ -y, --yes Skip all prompts and use defaults
2935
+ --dry-run Show what would be changed without making changes
2936
+ -p, --project <path> Specify project directory
2937
+
2938
+ Examples:
2939
+ npx humanbehavior-js auto-install
2940
+ npx humanbehavior-js auto-install hb_your_api_key_here
2941
+ npx humanbehavior-js auto-install --project ./my-app --yes
2942
+ `);
2943
+ }
2944
+ // Main execution
2945
+ if (import.meta.url === `file://${process.argv[1]}`) {
2946
+ const options = parseArgs();
2947
+ const cli = new AutoInstallCLI(options);
2948
+ cli.run().catch((error) => {
2949
+ clack.cancel(`Unexpected error: ${error.message}`);
2950
+ process.exit(1);
2951
+ });
2952
+ }
2953
+
2954
+ /**
2955
+ * Centralized AI Service Implementation
2956
+ *
2957
+ * This service runs on your backend infrastructure and provides AI-powered
2958
+ * code analysis without requiring users to provide their own API keys.
2959
+ *
2960
+ * The service can be deployed as:
2961
+ * - AWS Lambda function
2962
+ * - Docker container
2963
+ * - Express.js server
2964
+ * - Cloud function
2965
+ */
2966
+ /**
2967
+ * Centralized AI Service Implementation
2968
+ * This runs on your backend infrastructure
2969
+ */
2970
+ class CentralizedAIService {
2971
+ constructor(config) {
2972
+ this.cache = new Map();
2973
+ this.config = Object.assign({ openaiModel: 'gpt-4', maxTokens: 2000, temperature: 0.3, enableCaching: true, cacheTTL: 3600 }, config);
2974
+ this.initializeOpenAI();
2975
+ }
2976
+ /**
2977
+ * Initialize OpenAI client
2978
+ */
2979
+ initializeOpenAI() {
2980
+ try {
2981
+ // Import OpenAI dynamically to avoid bundling issues
2982
+ const { OpenAI } = require('openai');
2983
+ this.openai = new OpenAI({
2984
+ apiKey: this.config.openaiApiKey
2985
+ });
2986
+ }
2987
+ catch (error) {
2988
+ console.warn('OpenAI not available, falling back to heuristic analysis');
2989
+ this.openai = null;
2990
+ }
2991
+ }
2992
+ /**
2993
+ * Analyze code patterns using AI
2994
+ */
2995
+ analyzeCodePatterns(codeSamples) {
2996
+ return __awaiter(this, void 0, void 0, function* () {
2997
+ const request = {
2998
+ codeSamples,
2999
+ timestamp: new Date().toISOString()
3000
+ };
3001
+ // Check cache first
3002
+ const cacheKey = this.generateCacheKey(request);
3003
+ if (this.config.enableCaching) {
3004
+ const cached = this.cache.get(cacheKey);
3005
+ if (cached && this.isCacheValid(cached.timestamp)) {
3006
+ return cached.analysis;
3007
+ }
3008
+ }
3009
+ const analysis = yield this.performAIAnalysis(request);
3010
+ // Cache the result
3011
+ if (this.config.enableCaching) {
3012
+ this.cache.set(cacheKey, {
3013
+ analysis,
3014
+ timestamp: Date.now()
3015
+ });
3016
+ }
3017
+ return analysis;
3018
+ });
3019
+ }
3020
+ /**
3021
+ * Resolve conflicts using AI
3022
+ */
3023
+ resolveConflicts(conflicts, framework) {
3024
+ return __awaiter(this, void 0, void 0, function* () {
3025
+ var _a, _b;
3026
+ const request = {
3027
+ conflicts,
3028
+ framework,
3029
+ codeContext: 'HumanBehavior SDK integration'
3030
+ };
3031
+ if (!this.openai) {
3032
+ return this.resolveConflictsHeuristic(conflicts, framework);
3033
+ }
3034
+ try {
3035
+ const prompt = this.buildConflictResolutionPrompt(request);
3036
+ const response = yield this.openai.chat.completions.create({
3037
+ model: this.config.openaiModel,
3038
+ messages: [
3039
+ {
3040
+ role: 'system',
3041
+ content: 'You are an expert at resolving code integration conflicts. Provide specific resolution strategies.'
3042
+ },
3043
+ {
3044
+ role: 'user',
3045
+ content: prompt
3046
+ }
3047
+ ],
3048
+ max_tokens: this.config.maxTokens,
3049
+ temperature: this.config.temperature
3050
+ });
3051
+ const content = (_b = (_a = response.choices[0]) === null || _a === void 0 ? void 0 : _a.message) === null || _b === void 0 ? void 0 : _b.content;
3052
+ if (content && typeof content === 'string') {
3053
+ return this.parseConflictResolutions(content);
3054
+ }
3055
+ return [];
3056
+ }
3057
+ catch (error) {
3058
+ console.warn('AI conflict resolution failed, using heuristic approach:', error instanceof Error ? error.message : 'Unknown error');
3059
+ }
3060
+ return this.resolveConflictsHeuristic(conflicts, framework);
3061
+ });
3062
+ }
3063
+ /**
3064
+ * Generate optimizations using AI
3065
+ */
3066
+ generateOptimizations(framework, patterns) {
3067
+ return __awaiter(this, void 0, void 0, function* () {
3068
+ var _a, _b;
3069
+ const request = {
3070
+ framework,
3071
+ patterns,
3072
+ projectContext: 'HumanBehavior SDK integration'
3073
+ };
3074
+ if (!this.openai) {
3075
+ return this.generateOptimizationsHeuristic(framework, patterns);
3076
+ }
3077
+ try {
3078
+ const prompt = this.buildOptimizationPrompt(request);
3079
+ const response = yield this.openai.chat.completions.create({
3080
+ model: this.config.openaiModel,
3081
+ messages: [
3082
+ {
3083
+ role: 'system',
3084
+ content: 'You are an expert at optimizing code integration. Provide specific, actionable recommendations.'
3085
+ },
3086
+ {
3087
+ role: 'user',
3088
+ content: prompt
3089
+ }
3090
+ ],
3091
+ max_tokens: this.config.maxTokens,
3092
+ temperature: this.config.temperature
3093
+ });
3094
+ const content = (_b = (_a = response.choices[0]) === null || _a === void 0 ? void 0 : _a.message) === null || _b === void 0 ? void 0 : _b.content;
3095
+ if (content) {
3096
+ return this.parseOptimizations(content);
3097
+ }
3098
+ }
3099
+ catch (error) {
3100
+ console.warn('AI optimization generation failed, using heuristic approach:', error instanceof Error ? error.message : 'Unknown error');
3101
+ }
3102
+ return this.generateOptimizationsHeuristic(framework, patterns);
3103
+ });
3104
+ }
3105
+ /**
3106
+ * Perform AI analysis
3107
+ */
3108
+ performAIAnalysis(request) {
3109
+ return __awaiter(this, void 0, void 0, function* () {
3110
+ var _a, _b;
3111
+ if (!this.openai) {
3112
+ return this.performHeuristicAnalysis(request);
3113
+ }
3114
+ try {
3115
+ const prompt = this.buildAnalysisPrompt(request);
3116
+ const response = yield this.openai.chat.completions.create({
3117
+ model: this.config.openaiModel,
3118
+ messages: [
3119
+ {
3120
+ role: 'system',
3121
+ content: 'You are an expert at analyzing code patterns and determining optimal integration strategies. Provide detailed analysis in JSON format.'
3122
+ },
3123
+ {
3124
+ role: 'user',
3125
+ content: prompt
3126
+ }
3127
+ ],
3128
+ max_tokens: this.config.maxTokens,
3129
+ temperature: this.config.temperature,
3130
+ response_format: { type: 'json_object' }
3131
+ });
3132
+ const content = (_b = (_a = response.choices[0]) === null || _a === void 0 ? void 0 : _a.message) === null || _b === void 0 ? void 0 : _b.content;
3133
+ if (content) {
3134
+ return this.parseAnalysisResult(content);
3135
+ }
3136
+ }
3137
+ catch (error) {
3138
+ console.warn('AI analysis failed, using heuristic approach:', error instanceof Error ? error.message : 'Unknown error');
3139
+ }
3140
+ return this.performHeuristicAnalysis(request);
3141
+ });
3142
+ }
3143
+ /**
3144
+ * Build analysis prompt
3145
+ */
3146
+ buildAnalysisPrompt(request) {
3147
+ return `Analyze these code samples to determine the framework and integration strategy:
3148
+
3149
+ ${request.codeSamples.join('\n\n')}
3150
+
3151
+ Provide analysis in JSON format with:
3152
+ - framework: { name, type, confidence (0-1) }
3153
+ - patterns: array of detected patterns
3154
+ - conflicts: array of potential conflicts
3155
+ - recommendations: array of integration recommendations
3156
+ - integrationStrategy: "provider" | "plugin" | "module" | "script" | "standalone"
3157
+ - compatibilityMode: "modern" | "legacy" | "hybrid"
3158
+
3159
+ Focus on:
3160
+ 1. Framework detection beyond package.json
3161
+ 2. Code patterns and architecture
3162
+ 3. Integration compatibility
3163
+ 4. Future-proof strategies
3164
+ 5. Backward compatibility needs
3165
+
3166
+ Respond with valid JSON only.`;
3167
+ }
3168
+ /**
3169
+ * Build conflict resolution prompt
3170
+ */
3171
+ buildConflictResolutionPrompt(request) {
3172
+ return `Resolve these integration conflicts for ${request.framework.name}:
3173
+
3174
+ Conflicts: ${request.conflicts.join(', ')}
3175
+
3176
+ Framework: ${request.framework.name} (${request.framework.type})
3177
+ Context: ${request.codeContext}
3178
+
3179
+ Provide specific resolution strategies for each conflict. Options:
3180
+ - update_existing_integration: Update existing code
3181
+ - merge_providers: Merge multiple providers
3182
+ - hybrid_module_support: Support both module systems
3183
+ - skip_conflict: Skip the modification
3184
+ - custom_resolution: Custom resolution strategy
3185
+
3186
+ Respond with a JSON array of resolution strategies.`;
3187
+ }
3188
+ /**
3189
+ * Build optimization prompt
3190
+ */
3191
+ buildOptimizationPrompt(request) {
3192
+ return `Generate optimizations for ${request.framework.name} integration:
3193
+
3194
+ Framework: ${request.framework.name} (${request.framework.type})
3195
+ Patterns: ${request.patterns.join(', ')}
3196
+ Context: ${request.projectContext}
3197
+
3198
+ Provide specific, actionable optimization recommendations for:
3199
+ 1. Performance improvements
3200
+ 2. Error handling
3201
+ 3. Code organization
3202
+ 4. Future-proofing
3203
+ 5. Backward compatibility
3204
+
3205
+ Respond with a JSON array of optimization recommendations.`;
3206
+ }
3207
+ /**
3208
+ * Parse analysis result
3209
+ */
3210
+ parseAnalysisResult(content) {
3211
+ try {
3212
+ const result = JSON.parse(content);
3213
+ return {
3214
+ framework: result.framework || { name: 'vanilla', type: 'vanilla' },
3215
+ confidence: result.confidence || 0.5,
3216
+ patterns: result.patterns || [],
3217
+ conflicts: result.conflicts || [],
3218
+ recommendations: result.recommendations || [],
3219
+ integrationStrategy: result.integrationStrategy || 'script',
3220
+ compatibilityMode: result.compatibilityMode || 'modern'
3221
+ };
3222
+ }
3223
+ catch (error) {
3224
+ console.warn('Failed to parse AI analysis result:', error);
3225
+ return this.getDefaultAnalysis();
3226
+ }
3227
+ }
3228
+ /**
3229
+ * Parse conflict resolutions
3230
+ */
3231
+ parseConflictResolutions(content) {
3232
+ try {
3233
+ const result = JSON.parse(content);
3234
+ return Array.isArray(result) ? result : [];
3235
+ }
3236
+ catch (error) {
3237
+ console.warn('Failed to parse conflict resolutions:', error);
3238
+ return [];
3239
+ }
3240
+ }
3241
+ /**
3242
+ * Parse optimizations
3243
+ */
3244
+ parseOptimizations(content) {
3245
+ try {
3246
+ const result = JSON.parse(content);
3247
+ return Array.isArray(result) ? result : [];
3248
+ }
3249
+ catch (error) {
3250
+ console.warn('Failed to parse optimizations:', error);
3251
+ return [];
3252
+ }
3253
+ }
3254
+ /**
3255
+ * Heuristic analysis fallback
3256
+ */
3257
+ performHeuristicAnalysis(request) {
3258
+ const patterns = request.codeSamples.join(' ').toLowerCase();
3259
+ // Framework detection
3260
+ let framework = { name: 'vanilla', type: 'vanilla' };
3261
+ let confidence = 0.5;
3262
+ if (patterns.includes('react')) {
3263
+ framework = { name: 'react', type: 'react' };
3264
+ confidence = 0.9;
3265
+ }
3266
+ else if (patterns.includes('vue')) {
3267
+ framework = { name: 'vue', type: 'vue' };
3268
+ confidence = 0.9;
3269
+ }
3270
+ else if (patterns.includes('angular')) {
3271
+ framework = { name: 'angular', type: 'angular' };
3272
+ confidence = 0.9;
3273
+ }
3274
+ else if (patterns.includes('svelte')) {
3275
+ framework = { name: 'svelte', type: 'svelte' };
3276
+ confidence = 0.9;
3277
+ }
3278
+ else if (patterns.includes('next')) {
3279
+ framework = { name: 'nextjs', type: 'nextjs' };
3280
+ confidence = 0.9;
3281
+ }
3282
+ else if (patterns.includes('nuxt')) {
3283
+ framework = { name: 'nuxt', type: 'nuxt' };
3284
+ confidence = 0.9;
3285
+ }
3286
+ // Integration strategy
3287
+ let integrationStrategy = 'script';
3288
+ if (framework.type === 'react' || framework.type === 'nextjs') {
3289
+ integrationStrategy = 'provider';
3290
+ }
3291
+ else if (framework.type === 'vue') {
3292
+ integrationStrategy = 'plugin';
3293
+ }
3294
+ else if (framework.type === 'angular') {
3295
+ integrationStrategy = 'module';
3296
+ }
3297
+ // Compatibility mode
3298
+ let compatibilityMode = 'modern';
3299
+ if (patterns.includes('require(') || patterns.includes('var ')) {
3300
+ compatibilityMode = 'legacy';
3301
+ }
3302
+ return {
3303
+ framework,
3304
+ confidence,
3305
+ patterns: request.codeSamples,
3306
+ conflicts: [],
3307
+ recommendations: [],
3308
+ integrationStrategy,
3309
+ compatibilityMode
3310
+ };
3311
+ }
3312
+ /**
3313
+ * Heuristic conflict resolution
3314
+ */
3315
+ resolveConflictsHeuristic(conflicts, framework) {
3316
+ const resolutions = [];
3317
+ for (const conflict of conflicts) {
3318
+ switch (conflict) {
3319
+ case 'existing_humanbehavior_code':
3320
+ resolutions.push('update_existing_integration');
3321
+ break;
3322
+ case 'existing_provider':
3323
+ resolutions.push('merge_providers');
3324
+ break;
3325
+ case 'module_system_conflict':
3326
+ resolutions.push('hybrid_module_support');
3327
+ break;
3328
+ default:
3329
+ resolutions.push('skip_conflict');
3330
+ }
3331
+ }
3332
+ return resolutions;
3333
+ }
3334
+ /**
3335
+ * Heuristic optimization generation
3336
+ */
3337
+ generateOptimizationsHeuristic(framework, patterns) {
3338
+ const optimizations = [];
3339
+ switch (framework.type) {
3340
+ case 'react':
3341
+ optimizations.push('Use React.memo for performance optimization');
3342
+ optimizations.push('Implement error boundaries for better error tracking');
3343
+ optimizations.push('Consider using React.lazy for code splitting');
3344
+ break;
3345
+ case 'vue':
3346
+ optimizations.push('Use Vue 3 Composition API for better performance');
3347
+ optimizations.push('Implement proper error handling in components');
3348
+ optimizations.push('Consider using Vue Router for navigation tracking');
3349
+ break;
3350
+ case 'angular':
3351
+ optimizations.push('Use Angular standalone components for better tree-shaking');
3352
+ optimizations.push('Implement proper error handling with ErrorHandler');
3353
+ optimizations.push('Consider using Angular signals for state management');
3354
+ break;
3355
+ default:
3356
+ optimizations.push('Enable performance tracking');
3357
+ optimizations.push('Implement error tracking');
3358
+ optimizations.push('Consider progressive enhancement');
3359
+ }
3360
+ return optimizations;
3361
+ }
3362
+ /**
3363
+ * Generate cache key
3364
+ */
3365
+ generateCacheKey(request) {
3366
+ const content = JSON.stringify(request);
3367
+ return Buffer.from(content).toString('base64').substring(0, 32);
3368
+ }
3369
+ /**
3370
+ * Check if cache is valid
3371
+ */
3372
+ isCacheValid(timestamp) {
3373
+ const now = Date.now();
3374
+ const ttl = (this.config.cacheTTL || 3600) * 1000; // Convert to milliseconds
3375
+ return (now - timestamp) < ttl;
3376
+ }
3377
+ /**
3378
+ * Get default analysis
3379
+ */
3380
+ getDefaultAnalysis() {
3381
+ return {
3382
+ framework: { name: 'vanilla', type: 'vanilla' },
3383
+ confidence: 0.5,
3384
+ patterns: [],
3385
+ conflicts: [],
3386
+ recommendations: [],
3387
+ integrationStrategy: 'script',
3388
+ compatibilityMode: 'modern'
3389
+ };
3390
+ }
3391
+ /**
3392
+ * Get service statistics
3393
+ */
3394
+ getStats() {
3395
+ return {
3396
+ cacheSize: this.cache.size,
3397
+ config: {
3398
+ model: this.config.openaiModel,
3399
+ maxTokens: this.config.maxTokens,
3400
+ temperature: this.config.temperature,
3401
+ caching: this.config.enableCaching
3402
+ },
3403
+ openaiAvailable: !!this.openai
3404
+ };
3405
+ }
3406
+ /**
3407
+ * Clear cache
3408
+ */
3409
+ clearCache() {
3410
+ this.cache.clear();
3411
+ }
3412
+ }
3413
+
3414
+ export { AIAutoInstallCLI, AIBrowserInstallationWizard, AIEnhancedInstallationWizard, AutoInstallCLI, AutoInstallationWizard, CentralizedAIService, AutoInstallationWizard as InstallWizard, RemoteAIService };
3415
+ //# sourceMappingURL=index.js.map