humanbehavior-js 0.4.28 → 0.5.0

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