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