humanbehavior-js 0.3.6 → 0.3.8

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 (59) hide show
  1. package/WIZARD_USAGE_GUIDE.md +381 -0
  2. package/dist/cjs/angular/index.cjs +53 -0
  3. package/dist/cjs/angular/index.cjs.map +1 -0
  4. package/dist/cjs/index.cjs +14230 -0
  5. package/dist/cjs/index.cjs.map +1 -0
  6. package/dist/cjs/install-wizard.cjs +1157 -0
  7. package/dist/cjs/install-wizard.cjs.map +1 -0
  8. package/dist/cjs/react/index.cjs +14387 -0
  9. package/dist/cjs/react/index.cjs.map +1 -0
  10. package/dist/cjs/remix/index.cjs +57 -0
  11. package/dist/cjs/remix/index.cjs.map +1 -0
  12. package/dist/cjs/svelte/index.cjs +13 -0
  13. package/dist/cjs/svelte/index.cjs.map +1 -0
  14. package/dist/cjs/vue/index.cjs +16 -0
  15. package/dist/cjs/vue/index.cjs.map +1 -0
  16. package/dist/cli/auto-install.js +1170 -0
  17. package/dist/cli/auto-install.js.map +1 -0
  18. package/dist/esm/angular/index.js +49 -0
  19. package/dist/esm/angular/index.js.map +1 -0
  20. package/dist/esm/index.js +12160 -3894
  21. package/dist/esm/index.js.map +1 -1
  22. package/dist/esm/install-wizard.js +1134 -0
  23. package/dist/esm/install-wizard.js.map +1 -0
  24. package/dist/esm/react/index.js +14113 -70
  25. package/dist/esm/react/index.js.map +1 -1
  26. package/dist/esm/remix/index.js +47 -0
  27. package/dist/esm/remix/index.js.map +1 -0
  28. package/dist/esm/svelte/index.js +11 -0
  29. package/dist/esm/svelte/index.js.map +1 -0
  30. package/dist/esm/vue/index.js +14 -0
  31. package/dist/esm/vue/index.js.map +1 -0
  32. package/dist/index.min.js +1 -15
  33. package/dist/index.min.js.map +1 -1
  34. package/dist/types/angular/index.d.ts +240 -0
  35. package/dist/types/index.d.ts +2 -2
  36. package/dist/types/install-wizard.d.ts +126 -0
  37. package/dist/types/react/index.d.ts +212 -3
  38. package/dist/types/remix/index.d.ts +10 -0
  39. package/dist/types/svelte/index.d.ts +216 -0
  40. package/dist/types/vue/index.d.ts +10 -0
  41. package/package.json +41 -9
  42. package/readme.md +72 -3
  43. package/rollup.config.js +263 -13
  44. package/src/angular/index.ts +54 -0
  45. package/src/api.ts +19 -2
  46. package/src/cli/auto-install.ts +225 -0
  47. package/src/index.ts +5 -2
  48. package/src/install-wizard.ts +1304 -0
  49. package/src/react/AutoInstallWizard.tsx +557 -0
  50. package/src/react/browser.ts +8 -0
  51. package/src/react/index.tsx +2 -4
  52. package/src/remix/index.ts +16 -0
  53. package/src/svelte/index.ts +8 -0
  54. package/src/tracker.ts +54 -24
  55. package/src/vue/index.ts +18 -0
  56. package/dist/cjs/index.js +0 -5967
  57. package/dist/cjs/index.js.map +0 -1
  58. package/dist/cjs/react/index.js +0 -346
  59. package/dist/cjs/react/index.js.map +0 -1
@@ -0,0 +1,1170 @@
1
+ #!/usr/bin/env node
2
+ import * as fs from 'fs';
3
+ import * as path from 'path';
4
+ import * as readline from 'readline';
5
+
6
+ /******************************************************************************
7
+ Copyright (c) Microsoft Corporation.
8
+
9
+ Permission to use, copy, modify, and/or distribute this software for any
10
+ purpose with or without fee is hereby granted.
11
+
12
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
13
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
14
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
15
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
16
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
17
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
18
+ PERFORMANCE OF THIS SOFTWARE.
19
+ ***************************************************************************** */
20
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
21
+
22
+
23
+ function __awaiter(thisArg, _arguments, P, generator) {
24
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
25
+ return new (P || (P = Promise))(function (resolve, reject) {
26
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
27
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
28
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
29
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
30
+ });
31
+ }
32
+
33
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
34
+ var e = new Error(message);
35
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
36
+ };
37
+
38
+ /**
39
+ * HumanBehavior SDK Auto-Installation Wizard
40
+ *
41
+ * This wizard automatically detects the user's framework and modifies their codebase
42
+ * to integrate the SDK with minimal user intervention.
43
+ */
44
+ class AutoInstallationWizard {
45
+ constructor(apiKey, projectRoot = process.cwd()) {
46
+ this.framework = null;
47
+ this.apiKey = apiKey;
48
+ this.projectRoot = projectRoot;
49
+ }
50
+ /**
51
+ * Main installation method - detects framework and auto-installs
52
+ */
53
+ install() {
54
+ return __awaiter(this, void 0, void 0, function* () {
55
+ try {
56
+ // Step 1: Detect framework
57
+ this.framework = yield this.detectFramework();
58
+ // Step 2: Install package
59
+ yield this.installPackage();
60
+ // Step 3: Generate and apply code modifications
61
+ const modifications = yield this.generateModifications();
62
+ yield this.applyModifications(modifications);
63
+ // Step 4: Generate next steps
64
+ const nextSteps = this.generateNextSteps();
65
+ return {
66
+ success: true,
67
+ framework: this.framework,
68
+ modifications,
69
+ errors: [],
70
+ nextSteps
71
+ };
72
+ }
73
+ catch (error) {
74
+ return {
75
+ success: false,
76
+ framework: this.framework || { name: 'unknown', type: 'vanilla' },
77
+ modifications: [],
78
+ errors: [error instanceof Error ? error.message : 'Unknown error'],
79
+ nextSteps: []
80
+ };
81
+ }
82
+ });
83
+ }
84
+ /**
85
+ * Detect the current framework and project setup
86
+ */
87
+ detectFramework() {
88
+ return __awaiter(this, void 0, void 0, function* () {
89
+ const packageJsonPath = path.join(this.projectRoot, 'package.json');
90
+ if (!fs.existsSync(packageJsonPath)) {
91
+ return {
92
+ name: 'vanilla',
93
+ type: 'vanilla',
94
+ projectRoot: this.projectRoot
95
+ };
96
+ }
97
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
98
+ const dependencies = Object.assign(Object.assign({}, packageJson.dependencies), packageJson.devDependencies);
99
+ // Detect framework
100
+ let framework = {
101
+ name: 'vanilla',
102
+ type: 'vanilla',
103
+ projectRoot: this.projectRoot
104
+ };
105
+ if (dependencies.nuxt) {
106
+ framework = {
107
+ name: 'nuxt',
108
+ type: 'nuxt',
109
+ hasTypeScript: !!dependencies.typescript,
110
+ hasRouter: true,
111
+ projectRoot: this.projectRoot
112
+ };
113
+ }
114
+ else if (dependencies.next) {
115
+ framework = {
116
+ name: 'nextjs',
117
+ type: 'nextjs',
118
+ hasTypeScript: !!dependencies.typescript || !!dependencies['@types/node'],
119
+ hasRouter: true,
120
+ projectRoot: this.projectRoot
121
+ };
122
+ }
123
+ else if (dependencies['@remix-run/react'] || dependencies['@remix-run/dev']) {
124
+ framework = {
125
+ name: 'remix',
126
+ type: 'remix',
127
+ hasTypeScript: !!dependencies.typescript || !!dependencies['@types/react'],
128
+ hasRouter: true,
129
+ projectRoot: this.projectRoot
130
+ };
131
+ }
132
+ else if (dependencies.react) {
133
+ framework = {
134
+ name: 'react',
135
+ type: 'react',
136
+ hasTypeScript: !!dependencies.typescript || !!dependencies['@types/react'],
137
+ hasRouter: !!dependencies['react-router-dom'] || !!dependencies['react-router'],
138
+ projectRoot: this.projectRoot
139
+ };
140
+ }
141
+ else if (dependencies.vue) {
142
+ framework = {
143
+ name: 'vue',
144
+ type: 'vue',
145
+ hasTypeScript: !!dependencies.typescript || !!dependencies['@vue/cli-service'],
146
+ hasRouter: !!dependencies['vue-router'],
147
+ projectRoot: this.projectRoot
148
+ };
149
+ }
150
+ else if (dependencies['@angular/core']) {
151
+ framework = {
152
+ name: 'angular',
153
+ type: 'angular',
154
+ hasTypeScript: true,
155
+ hasRouter: true,
156
+ projectRoot: this.projectRoot
157
+ };
158
+ }
159
+ else if (dependencies.svelte) {
160
+ framework = {
161
+ name: 'svelte',
162
+ type: 'svelte',
163
+ hasTypeScript: !!dependencies.typescript || !!dependencies['svelte-check'],
164
+ hasRouter: !!dependencies['svelte-routing'] || !!dependencies['@sveltejs/kit'],
165
+ projectRoot: this.projectRoot
166
+ };
167
+ }
168
+ // Detect bundler
169
+ if (dependencies.vite) {
170
+ framework.bundler = 'vite';
171
+ }
172
+ else if (dependencies.webpack) {
173
+ framework.bundler = 'webpack';
174
+ }
175
+ else if (dependencies.esbuild) {
176
+ framework.bundler = 'esbuild';
177
+ }
178
+ else if (dependencies.rollup) {
179
+ framework.bundler = 'rollup';
180
+ }
181
+ // Detect package manager
182
+ if (fs.existsSync(path.join(this.projectRoot, 'yarn.lock'))) {
183
+ framework.packageManager = 'yarn';
184
+ }
185
+ else if (fs.existsSync(path.join(this.projectRoot, 'pnpm-lock.yaml'))) {
186
+ framework.packageManager = 'pnpm';
187
+ }
188
+ else {
189
+ framework.packageManager = 'npm';
190
+ }
191
+ return framework;
192
+ });
193
+ }
194
+ /**
195
+ * Install the SDK package
196
+ */
197
+ installPackage() {
198
+ return __awaiter(this, void 0, void 0, function* () {
199
+ var _a, _b;
200
+ const { execSync } = yield import('child_process');
201
+ const command = ((_a = this.framework) === null || _a === void 0 ? void 0 : _a.packageManager) === 'yarn'
202
+ ? 'yarn add humanbehavior-js'
203
+ : ((_b = this.framework) === null || _b === void 0 ? void 0 : _b.packageManager) === 'pnpm'
204
+ ? 'pnpm add humanbehavior-js'
205
+ : 'npm install humanbehavior-js';
206
+ try {
207
+ execSync(command, { cwd: this.projectRoot, stdio: 'inherit' });
208
+ }
209
+ catch (error) {
210
+ throw new Error(`Failed to install humanbehavior-js: ${error}`);
211
+ }
212
+ });
213
+ }
214
+ /**
215
+ * Generate code modifications based on framework
216
+ */
217
+ generateModifications() {
218
+ return __awaiter(this, void 0, void 0, function* () {
219
+ var _a;
220
+ const modifications = [];
221
+ switch ((_a = this.framework) === null || _a === void 0 ? void 0 : _a.type) {
222
+ case 'react':
223
+ modifications.push(...yield this.generateReactModifications());
224
+ break;
225
+ case 'nextjs':
226
+ modifications.push(...yield this.generateNextJSModifications());
227
+ break;
228
+ case 'nuxt':
229
+ modifications.push(...yield this.generateNuxtModifications());
230
+ break;
231
+ case 'remix':
232
+ modifications.push(...yield this.generateRemixModifications());
233
+ break;
234
+ case 'vue':
235
+ modifications.push(...yield this.generateVueModifications());
236
+ break;
237
+ case 'angular':
238
+ modifications.push(...yield this.generateAngularModifications());
239
+ break;
240
+ case 'svelte':
241
+ modifications.push(...yield this.generateSvelteModifications());
242
+ break;
243
+ default:
244
+ modifications.push(...yield this.generateVanillaModifications());
245
+ }
246
+ return modifications;
247
+ });
248
+ }
249
+ /**
250
+ * Generate React-specific modifications
251
+ */
252
+ generateReactModifications() {
253
+ return __awaiter(this, void 0, void 0, function* () {
254
+ const modifications = [];
255
+ // Find main App component or index file
256
+ const appFile = this.findReactAppFile();
257
+ if (appFile) {
258
+ const content = fs.readFileSync(appFile, 'utf8');
259
+ const modifiedContent = this.injectReactProvider(content, appFile);
260
+ modifications.push({
261
+ filePath: appFile,
262
+ action: 'modify',
263
+ content: modifiedContent,
264
+ description: 'Added HumanBehaviorProvider to React app'
265
+ });
266
+ }
267
+ // Create or append to environment file
268
+ modifications.push(this.createEnvironmentModification(this.framework));
269
+ return modifications;
270
+ });
271
+ }
272
+ /**
273
+ * Generate Next.js-specific modifications
274
+ */
275
+ generateNextJSModifications() {
276
+ return __awaiter(this, void 0, void 0, function* () {
277
+ const modifications = [];
278
+ // Check for App Router
279
+ const appLayoutFile = path.join(this.projectRoot, 'src', 'app', 'layout.tsx');
280
+ const pagesLayoutFile = path.join(this.projectRoot, 'src', 'pages', '_app.tsx');
281
+ if (fs.existsSync(appLayoutFile)) {
282
+ // Create providers.tsx file for App Router
283
+ modifications.push({
284
+ filePath: path.join(this.projectRoot, 'src', 'app', 'providers.tsx'),
285
+ action: 'create',
286
+ content: `'use client';
287
+
288
+ import { HumanBehaviorProvider } from 'humanbehavior-js/react';
289
+
290
+ export function Providers({ children }: { children: React.ReactNode }) {
291
+ return (
292
+ <HumanBehaviorProvider apiKey={process.env.NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY}>
293
+ {children}
294
+ </HumanBehaviorProvider>
295
+ );
296
+ }`,
297
+ description: 'Created providers.tsx file for Next.js App Router'
298
+ });
299
+ // Modify layout.tsx to use the provider
300
+ const content = fs.readFileSync(appLayoutFile, 'utf8');
301
+ const modifiedContent = this.injectNextJSAppRouter(content);
302
+ modifications.push({
303
+ filePath: appLayoutFile,
304
+ action: 'modify',
305
+ content: modifiedContent,
306
+ description: 'Added Providers wrapper to Next.js App Router layout'
307
+ });
308
+ }
309
+ else if (fs.existsSync(pagesLayoutFile)) {
310
+ // Create providers.tsx file for Pages Router
311
+ modifications.push({
312
+ filePath: path.join(this.projectRoot, 'src', 'components', 'providers.tsx'),
313
+ action: 'create',
314
+ content: `'use client';
315
+
316
+ import { HumanBehaviorProvider } from 'humanbehavior-js/react';
317
+
318
+ export function Providers({ children }: { children: React.ReactNode }) {
319
+ return (
320
+ <HumanBehaviorProvider apiKey={process.env.NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY}>
321
+ {children}
322
+ </HumanBehaviorProvider>
323
+ );
324
+ }`,
325
+ description: 'Created providers.tsx file for Pages Router'
326
+ });
327
+ // Modify _app.tsx to use the provider
328
+ const content = fs.readFileSync(pagesLayoutFile, 'utf8');
329
+ const modifiedContent = this.injectNextJSPagesRouter(content);
330
+ modifications.push({
331
+ filePath: pagesLayoutFile,
332
+ action: 'modify',
333
+ content: modifiedContent,
334
+ description: 'Added Providers wrapper to Next.js Pages Router'
335
+ });
336
+ }
337
+ // Create or append to environment file
338
+ modifications.push(this.createEnvironmentModification(this.framework));
339
+ return modifications;
340
+ });
341
+ }
342
+ /**
343
+ * Generate Nuxt-specific modifications
344
+ */
345
+ generateNuxtModifications() {
346
+ return __awaiter(this, void 0, void 0, function* () {
347
+ const modifications = [];
348
+ // Create plugin file for Nuxt (in app directory)
349
+ const pluginFile = path.join(this.projectRoot, 'app', 'plugins', 'humanbehavior.client.ts');
350
+ modifications.push({
351
+ filePath: pluginFile,
352
+ action: 'create',
353
+ content: `import { HumanBehaviorTracker } from 'humanbehavior-js';
354
+
355
+ export default defineNuxtPlugin(() => {
356
+ const config = useRuntimeConfig();
357
+
358
+ // Initialize HumanBehavior SDK (client-side only)
359
+ if (typeof window !== 'undefined') {
360
+ const apiKey = config.public.humanBehaviorApiKey;
361
+ console.log('HumanBehavior: API key:', apiKey ? 'present' : 'missing');
362
+
363
+ if (apiKey) {
364
+ try {
365
+ const tracker = HumanBehaviorTracker.init(apiKey);
366
+ console.log('HumanBehavior: Tracker initialized successfully');
367
+ } catch (error) {
368
+ console.error('HumanBehavior: Failed to initialize tracker:', error);
369
+ }
370
+ } else {
371
+ console.error('HumanBehavior: No API key found in runtime config');
372
+ }
373
+ }
374
+ });`,
375
+ description: 'Created Nuxt plugin for HumanBehavior SDK in app directory'
376
+ });
377
+ // Create environment configuration
378
+ const nuxtConfigFile = path.join(this.projectRoot, 'nuxt.config.ts');
379
+ if (fs.existsSync(nuxtConfigFile)) {
380
+ const content = fs.readFileSync(nuxtConfigFile, 'utf8');
381
+ const modifiedContent = this.injectNuxtConfig(content);
382
+ modifications.push({
383
+ filePath: nuxtConfigFile,
384
+ action: 'modify',
385
+ content: modifiedContent,
386
+ description: 'Added HumanBehavior runtime config to Nuxt config'
387
+ });
388
+ }
389
+ // Create or append to environment file
390
+ modifications.push(this.createEnvironmentModification(this.framework));
391
+ return modifications;
392
+ });
393
+ }
394
+ /**
395
+ * Generate Remix-specific modifications
396
+ */
397
+ generateRemixModifications() {
398
+ return __awaiter(this, void 0, void 0, function* () {
399
+ const modifications = [];
400
+ // Find root.tsx file
401
+ const rootFile = path.join(this.projectRoot, 'app', 'root.tsx');
402
+ if (fs.existsSync(rootFile)) {
403
+ const content = fs.readFileSync(rootFile, 'utf8');
404
+ const modifiedContent = this.injectRemixProvider(content);
405
+ modifications.push({
406
+ filePath: rootFile,
407
+ action: 'modify',
408
+ content: modifiedContent,
409
+ description: 'Added HumanBehaviorProvider to Remix root component'
410
+ });
411
+ }
412
+ // Create or append to environment file
413
+ modifications.push(this.createEnvironmentModification(this.framework));
414
+ return modifications;
415
+ });
416
+ }
417
+ /**
418
+ * Generate Vue-specific modifications
419
+ */
420
+ generateVueModifications() {
421
+ return __awaiter(this, void 0, void 0, function* () {
422
+ const modifications = [];
423
+ // Find main.js or main.ts
424
+ const mainFile = this.findVueMainFile();
425
+ if (mainFile) {
426
+ const content = fs.readFileSync(mainFile, 'utf8');
427
+ const modifiedContent = this.injectVuePlugin(content);
428
+ modifications.push({
429
+ filePath: mainFile,
430
+ action: 'modify',
431
+ content: modifiedContent,
432
+ description: 'Added HumanBehaviorPlugin to Vue app'
433
+ });
434
+ }
435
+ // Create or append to environment file
436
+ modifications.push(this.createEnvironmentModification(this.framework));
437
+ return modifications;
438
+ });
439
+ }
440
+ /**
441
+ * Generate Angular-specific modifications
442
+ */
443
+ generateAngularModifications() {
444
+ return __awaiter(this, void 0, void 0, function* () {
445
+ const modifications = [];
446
+ // Check for modern Angular (standalone components) vs legacy (NgModule)
447
+ const appModuleFile = path.join(this.projectRoot, 'src', 'app', 'app.module.ts');
448
+ const appComponentFile = path.join(this.projectRoot, 'src', 'app', 'app.ts');
449
+ const mainFile = path.join(this.projectRoot, 'src', 'main.ts');
450
+ const isModernAngular = fs.existsSync(appComponentFile) && !fs.existsSync(appModuleFile);
451
+ if (isModernAngular) {
452
+ // Modern Angular 17+ with standalone components
453
+ if (fs.existsSync(mainFile)) {
454
+ const content = fs.readFileSync(mainFile, 'utf8');
455
+ const modifiedContent = this.injectAngularStandaloneInit(content);
456
+ modifications.push({
457
+ filePath: mainFile,
458
+ action: 'modify',
459
+ content: modifiedContent,
460
+ description: 'Added HumanBehavior initialization to Angular main.ts'
461
+ });
462
+ }
463
+ }
464
+ else if (fs.existsSync(appModuleFile)) {
465
+ // Legacy Angular with NgModule
466
+ const content = fs.readFileSync(appModuleFile, 'utf8');
467
+ const modifiedContent = this.injectAngularModule(content);
468
+ modifications.push({
469
+ filePath: appModuleFile,
470
+ action: 'modify',
471
+ content: modifiedContent,
472
+ description: 'Added HumanBehaviorModule to Angular app'
473
+ });
474
+ }
475
+ // Handle Angular environment file (legacy structure)
476
+ const envFile = path.join(this.projectRoot, 'src', 'environments', 'environment.ts');
477
+ if (fs.existsSync(envFile)) {
478
+ const content = fs.readFileSync(envFile, 'utf8');
479
+ if (!content.includes('humanBehaviorApiKey')) {
480
+ const modifiedContent = content.replace(/export const environment = {([\s\S]*?)};/, `export const environment = {
481
+ $1,
482
+ humanBehaviorApiKey: process.env['HUMANBEHAVIOR_API_KEY'] || ''
483
+ };`);
484
+ modifications.push({
485
+ filePath: envFile,
486
+ action: 'modify',
487
+ content: modifiedContent,
488
+ description: 'Added API key to Angular environment'
489
+ });
490
+ }
491
+ }
492
+ // Create or append to environment file
493
+ modifications.push(this.createEnvironmentModification(this.framework));
494
+ return modifications;
495
+ });
496
+ }
497
+ /**
498
+ * Generate Svelte-specific modifications
499
+ */
500
+ generateSvelteModifications() {
501
+ return __awaiter(this, void 0, void 0, function* () {
502
+ const modifications = [];
503
+ // Check for SvelteKit
504
+ const svelteConfigFile = path.join(this.projectRoot, 'svelte.config.js');
505
+ const isSvelteKit = fs.existsSync(svelteConfigFile);
506
+ if (isSvelteKit) {
507
+ // SvelteKit - create layout file
508
+ const layoutFile = path.join(this.projectRoot, 'src', 'routes', '+layout.svelte');
509
+ if (fs.existsSync(layoutFile)) {
510
+ const content = fs.readFileSync(layoutFile, 'utf8');
511
+ const modifiedContent = this.injectSvelteKitLayout(content);
512
+ modifications.push({
513
+ filePath: layoutFile,
514
+ action: 'modify',
515
+ content: modifiedContent,
516
+ description: 'Added HumanBehavior store to SvelteKit layout'
517
+ });
518
+ }
519
+ }
520
+ else {
521
+ // Regular Svelte - modify main file
522
+ const mainFile = this.findSvelteMainFile();
523
+ if (mainFile) {
524
+ const content = fs.readFileSync(mainFile, 'utf8');
525
+ const modifiedContent = this.injectSvelteStore(content);
526
+ modifications.push({
527
+ filePath: mainFile,
528
+ action: 'modify',
529
+ content: modifiedContent,
530
+ description: 'Added HumanBehavior store to Svelte app'
531
+ });
532
+ }
533
+ }
534
+ // Create or append to environment file
535
+ modifications.push(this.createEnvironmentModification(this.framework));
536
+ return modifications;
537
+ });
538
+ }
539
+ /**
540
+ * Generate vanilla JS/TS modifications
541
+ */
542
+ generateVanillaModifications() {
543
+ return __awaiter(this, void 0, void 0, function* () {
544
+ const modifications = [];
545
+ // Find HTML file to inject script
546
+ const htmlFile = this.findHTMLFile();
547
+ if (htmlFile) {
548
+ const content = fs.readFileSync(htmlFile, 'utf8');
549
+ const modifiedContent = this.injectVanillaScript(content);
550
+ modifications.push({
551
+ filePath: htmlFile,
552
+ action: 'modify',
553
+ content: modifiedContent,
554
+ description: 'Added HumanBehavior CDN script to HTML file'
555
+ });
556
+ }
557
+ // Create or append to environment file
558
+ modifications.push(this.createEnvironmentModification(this.framework));
559
+ return modifications;
560
+ });
561
+ }
562
+ /**
563
+ * Apply modifications to the codebase
564
+ */
565
+ applyModifications(modifications) {
566
+ return __awaiter(this, void 0, void 0, function* () {
567
+ for (const modification of modifications) {
568
+ try {
569
+ const dir = path.dirname(modification.filePath);
570
+ if (!fs.existsSync(dir)) {
571
+ fs.mkdirSync(dir, { recursive: true });
572
+ }
573
+ switch (modification.action) {
574
+ case 'create':
575
+ fs.writeFileSync(modification.filePath, modification.content);
576
+ break;
577
+ case 'modify':
578
+ fs.writeFileSync(modification.filePath, modification.content);
579
+ break;
580
+ case 'append':
581
+ fs.appendFileSync(modification.filePath, '\n' + modification.content);
582
+ break;
583
+ }
584
+ }
585
+ catch (error) {
586
+ throw new Error(`Failed to apply modification to ${modification.filePath}: ${error}`);
587
+ }
588
+ }
589
+ });
590
+ }
591
+ /**
592
+ * Generate next steps for the user
593
+ */
594
+ generateNextSteps() {
595
+ var _a, _b;
596
+ const steps = [
597
+ 'āœ… SDK installed and configured automatically!',
598
+ 'šŸš€ Your app is now tracking user behavior',
599
+ 'šŸ“Š View sessions in your HumanBehavior dashboard',
600
+ 'šŸ”§ Customize tracking in your code as needed'
601
+ ];
602
+ 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') {
603
+ steps.push('šŸ’” Use the useHumanBehavior() hook to track custom events');
604
+ }
605
+ return steps;
606
+ }
607
+ // Helper methods for file detection and content injection
608
+ findReactAppFile() {
609
+ const possibleFiles = [
610
+ 'src/App.jsx', 'src/App.js', 'src/App.tsx', 'src/App.ts',
611
+ 'src/index.js', 'src/index.tsx', 'src/main.js', 'src/main.tsx'
612
+ ];
613
+ for (const file of possibleFiles) {
614
+ const fullPath = path.join(this.projectRoot, file);
615
+ if (fs.existsSync(fullPath)) {
616
+ return fullPath;
617
+ }
618
+ }
619
+ return null;
620
+ }
621
+ findVueMainFile() {
622
+ const possibleFiles = [
623
+ 'src/main.js', 'src/main.ts', 'src/main.jsx', 'src/main.tsx'
624
+ ];
625
+ for (const file of possibleFiles) {
626
+ const fullPath = path.join(this.projectRoot, file);
627
+ if (fs.existsSync(fullPath)) {
628
+ return fullPath;
629
+ }
630
+ }
631
+ return null;
632
+ }
633
+ findSvelteMainFile() {
634
+ const possibleFiles = [
635
+ 'src/main.js', 'src/main.ts', 'src/main.svelte'
636
+ ];
637
+ for (const file of possibleFiles) {
638
+ const fullPath = path.join(this.projectRoot, file);
639
+ if (fs.existsSync(fullPath)) {
640
+ return fullPath;
641
+ }
642
+ }
643
+ return null;
644
+ }
645
+ findHTMLFile() {
646
+ const possibleFiles = ['index.html', 'public/index.html', 'dist/index.html'];
647
+ for (const file of possibleFiles) {
648
+ const fullPath = path.join(this.projectRoot, file);
649
+ if (fs.existsSync(fullPath)) {
650
+ return fullPath;
651
+ }
652
+ }
653
+ return null;
654
+ }
655
+ injectReactProvider(content, filePath) {
656
+ var _a;
657
+ filePath.endsWith('.tsx') || filePath.endsWith('.ts');
658
+ // Check if already has HumanBehaviorProvider
659
+ if (content.includes('HumanBehaviorProvider')) {
660
+ return content;
661
+ }
662
+ // Determine the correct environment variable syntax based on bundler
663
+ const isVite = ((_a = this.framework) === null || _a === void 0 ? void 0 : _a.bundler) === 'vite';
664
+ const envVar = isVite
665
+ ? 'import.meta.env.VITE_HUMANBEHAVIOR_API_KEY!'
666
+ : 'process.env.HUMANBEHAVIOR_API_KEY!';
667
+ const importStatement = `import { HumanBehaviorProvider } from 'humanbehavior-js/react';`;
668
+ // Simple injection - in production, you'd want more sophisticated parsing
669
+ if (content.includes('function App()') || content.includes('const App =')) {
670
+ return content.replace(/(function App\(\)|const App =)/, `${importStatement}\n\n$1`).replace(/return \(([\s\S]*?)\);/, `return (
671
+ <HumanBehaviorProvider apiKey={${envVar}}>
672
+ $1
673
+ </HumanBehaviorProvider>
674
+ );`);
675
+ }
676
+ return `${importStatement}\n\n${content}`;
677
+ }
678
+ injectNextJSAppRouter(content) {
679
+ if (content.includes('Providers')) {
680
+ return content;
681
+ }
682
+ const importStatement = `import { Providers } from './providers';`;
683
+ // First, add the import statement
684
+ let modifiedContent = content.replace(/export default function RootLayout/, `${importStatement}\n\nexport default function RootLayout`);
685
+ // Then wrap the body content with Providers
686
+ // Use a more specific approach to handle the body content
687
+ modifiedContent = modifiedContent.replace(/<body([^>]*)>([\s\S]*?)<\/body>/, (match, bodyAttrs, bodyContent) => {
688
+ // Trim whitespace and newlines from bodyContent
689
+ const trimmedContent = bodyContent.trim();
690
+ return `<body${bodyAttrs}>
691
+ <Providers>
692
+ ${trimmedContent}
693
+ </Providers>
694
+ </body>`;
695
+ });
696
+ return modifiedContent;
697
+ }
698
+ injectNextJSPagesRouter(content) {
699
+ if (content.includes('Providers')) {
700
+ return content;
701
+ }
702
+ const importStatement = `import { Providers } from '../components/providers';`;
703
+ return content.replace(/function MyApp/, `${importStatement}\n\nfunction MyApp`).replace(/return \(([\s\S]*?)\);/, `return (
704
+ <Providers>
705
+ $1
706
+ </Providers>
707
+ );`);
708
+ }
709
+ injectRemixProvider(content) {
710
+ if (content.includes('HumanBehaviorProvider')) {
711
+ return content;
712
+ }
713
+ const importStatement = `import { HumanBehaviorProvider, createHumanBehaviorLoader } from 'humanbehavior-js/remix';`;
714
+ const useLoaderDataImport = `import { useLoaderData } from "@remix-run/react";`;
715
+ // Add imports more robustly
716
+ let modifiedContent = content;
717
+ // Add HumanBehaviorProvider import - find the last import and add after it
718
+ if (!content.includes('HumanBehaviorProvider')) {
719
+ const lastImportIndex = modifiedContent.lastIndexOf('import');
720
+ if (lastImportIndex !== -1) {
721
+ const nextLineIndex = modifiedContent.indexOf('\n', lastImportIndex);
722
+ if (nextLineIndex !== -1) {
723
+ modifiedContent = modifiedContent.slice(0, nextLineIndex + 1) +
724
+ importStatement + '\n' +
725
+ modifiedContent.slice(nextLineIndex + 1);
726
+ }
727
+ else {
728
+ modifiedContent = modifiedContent + '\n' + importStatement;
729
+ }
730
+ }
731
+ else {
732
+ modifiedContent = importStatement + '\n' + modifiedContent;
733
+ }
734
+ }
735
+ // Add useLoaderData import - find the last import and add after it
736
+ if (!content.includes('useLoaderData')) {
737
+ const lastImportIndex = modifiedContent.lastIndexOf('import');
738
+ if (lastImportIndex !== -1) {
739
+ const nextLineIndex = modifiedContent.indexOf('\n', lastImportIndex);
740
+ if (nextLineIndex !== -1) {
741
+ modifiedContent = modifiedContent.slice(0, nextLineIndex + 1) +
742
+ useLoaderDataImport + '\n' +
743
+ modifiedContent.slice(nextLineIndex + 1);
744
+ }
745
+ else {
746
+ modifiedContent = modifiedContent + '\n' + useLoaderDataImport;
747
+ }
748
+ }
749
+ else {
750
+ modifiedContent = useLoaderDataImport + '\n' + modifiedContent;
751
+ }
752
+ }
753
+ // Add loader function before the App component
754
+ if (!content.includes('export const loader')) {
755
+ modifiedContent = modifiedContent.replace(/export default function App\(\)/, `export const loader = createHumanBehaviorLoader();
756
+
757
+ export default function App()`);
758
+ }
759
+ // Wrap the App component content with HumanBehaviorProvider
760
+ modifiedContent = modifiedContent.replace(/export default function App\(\) \{[\s\S]*?return \(([\s\S]*?)\);[\s\S]*?\}/, `export default function App() {
761
+ const data = useLoaderData<typeof loader>();
762
+
763
+ return (
764
+ <HumanBehaviorProvider apiKey={data.ENV.HUMANBEHAVIOR_API_KEY}>
765
+ $1
766
+ </HumanBehaviorProvider>
767
+ );
768
+ }`);
769
+ return modifiedContent;
770
+ }
771
+ injectVuePlugin(content) {
772
+ if (content.includes('HumanBehaviorPlugin')) {
773
+ return content;
774
+ }
775
+ const importStatement = `import { HumanBehaviorPlugin } from 'humanbehavior-js/vue';`;
776
+ const pluginUsage = `app.use(HumanBehaviorPlugin, {
777
+ apiKey: import.meta.env.VITE_HUMANBEHAVIOR_API_KEY
778
+ });`;
779
+ // Handle both Vue 2 and Vue 3 patterns
780
+ if (content.includes('createApp')) {
781
+ // Vue 3
782
+ return content.replace(/import.*from.*['"]vue['"]/, `$&\n${importStatement}`).replace(/app\.mount\(/, `${pluginUsage}\n\napp.mount(`);
783
+ }
784
+ else {
785
+ // Vue 2
786
+ return content.replace(/import.*from.*['"]vue['"]/, `$&\n${importStatement}`).replace(/new Vue\(/, `${pluginUsage}\n\nnew Vue(`);
787
+ }
788
+ }
789
+ injectAngularModule(content) {
790
+ if (content.includes('HumanBehaviorModule')) {
791
+ return content;
792
+ }
793
+ const importStatement = `import { HumanBehaviorModule } from 'humanbehavior-js/angular';`;
794
+ const environmentImport = `import { environment } from '../environments/environment';`;
795
+ // Add environment import if not present
796
+ let modifiedContent = content;
797
+ if (!content.includes('environment')) {
798
+ modifiedContent = content.replace(/import.*from.*['"]@angular/, `${environmentImport}\n$&`);
799
+ }
800
+ return modifiedContent.replace(/imports:\s*\[([\s\S]*?)\]/, `imports: [
801
+ $1,
802
+ HumanBehaviorModule.forRoot({
803
+ apiKey: environment.humanBehaviorApiKey
804
+ })
805
+ ]`).replace(/import.*from.*['"]@angular/, `$&\n${importStatement}`);
806
+ }
807
+ injectAngularStandaloneInit(content) {
808
+ if (content.includes('initializeHumanBehavior')) {
809
+ return content;
810
+ }
811
+ const importStatement = `import { initializeHumanBehavior } from 'humanbehavior-js/angular';`;
812
+ // Add import at the top
813
+ let modifiedContent = content.replace(/import.*from.*['"]@angular/, `${importStatement}\n$&`);
814
+ // Add initialization after bootstrapApplication
815
+ modifiedContent = modifiedContent.replace(/(bootstrapApplication\([^}]+\}?\)(?:\s*\.catch[^;]+;)?)/, `$1
816
+
817
+ // Initialize HumanBehavior SDK (client-side only)
818
+ if (typeof window !== 'undefined') {
819
+ const tracker = initializeHumanBehavior(
820
+ '${this.apiKey}'
821
+ );
822
+ }`);
823
+ return modifiedContent;
824
+ }
825
+ injectSvelteStore(content) {
826
+ if (content.includes('humanBehaviorStore')) {
827
+ return content;
828
+ }
829
+ const importStatement = `import { humanBehaviorStore } from 'humanbehavior-js/svelte';`;
830
+ const initCode = `humanBehaviorStore.init(process.env.PUBLIC_HUMANBEHAVIOR_API_KEY || '');`;
831
+ return `${importStatement}\n${initCode}\n\n${content}`;
832
+ }
833
+ injectSvelteKitLayout(content) {
834
+ if (content.includes('humanBehaviorStore')) {
835
+ return content;
836
+ }
837
+ const importStatement = `import { humanBehaviorStore } from 'humanbehavior-js/svelte';`;
838
+ const envImport = `import { PUBLIC_HUMANBEHAVIOR_API_KEY } from '$env/static/public';`;
839
+ const initCode = `humanBehaviorStore.init(PUBLIC_HUMANBEHAVIOR_API_KEY || '');`;
840
+ // Add to script section - handle different script tag patterns
841
+ if (content.includes('<script lang="ts">')) {
842
+ return content.replace(/<script lang="ts">/, `<script lang="ts">\n\t${envImport}\n\t${importStatement}\n\t${initCode}`);
843
+ }
844
+ else if (content.includes('<script>')) {
845
+ return content.replace(/<script>/, `<script>\n\t${envImport}\n\t${importStatement}\n\t${initCode}`);
846
+ }
847
+ else if (content.includes('<script context="module">')) {
848
+ return content.replace(/<script\s+context="module">/, `<script context="module">\n\t${envImport}\n\t${importStatement}\n\t${initCode}`);
849
+ }
850
+ else {
851
+ // If no script tag found, add one at the beginning
852
+ return content.replace(/<svelte:head>/, `<script lang="ts">\n\t${envImport}\n\t${importStatement}\n\t${initCode}\n</script>\n\n<svelte:head>`);
853
+ }
854
+ }
855
+ injectVanillaScript(content) {
856
+ if (content.includes('humanbehavior-js')) {
857
+ return content;
858
+ }
859
+ const cdnScript = `<script src="https://unpkg.com/humanbehavior-js@latest/dist/index.min.js"></script>`;
860
+ const initScript = `<script>
861
+ // Initialize HumanBehavior SDK
862
+ // Note: For vanilla HTML, the API key must be hardcoded since env vars aren't available
863
+ const tracker = HumanBehaviorTracker.init('${this.apiKey}');
864
+ </script>`;
865
+ return content.replace(/<\/head>/, ` ${cdnScript}\n ${initScript}\n</head>`);
866
+ }
867
+ injectNuxtConfig(content) {
868
+ if (content.includes('humanBehaviorApiKey')) {
869
+ return content;
870
+ }
871
+ // Add runtime config by inserting it after the opening brace
872
+ return content.replace(/export default defineNuxtConfig\(\{/, `export default defineNuxtConfig({
873
+ runtimeConfig: {
874
+ public: {
875
+ humanBehaviorApiKey: process.env.NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY
876
+ }
877
+ },`);
878
+ }
879
+ /**
880
+ * Helper method to find the best environment file for a framework
881
+ */
882
+ findBestEnvFile(framework) {
883
+ const possibleEnvFiles = [
884
+ '.env.local',
885
+ '.env.development.local',
886
+ '.env.development',
887
+ '.env.local.development',
888
+ '.env',
889
+ '.env.production',
890
+ '.env.staging'
891
+ ];
892
+ // Framework-specific environment variable names
893
+ const getEnvVarName = (framework) => {
894
+ // Handle React+Vite specifically
895
+ if (framework.type === 'react' && framework.bundler === 'vite') {
896
+ return 'VITE_HUMANBEHAVIOR_API_KEY';
897
+ }
898
+ // Framework-specific mappings
899
+ const envVarNames = {
900
+ react: 'HUMANBEHAVIOR_API_KEY',
901
+ nextjs: 'NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY',
902
+ vue: 'VITE_HUMANBEHAVIOR_API_KEY',
903
+ svelte: 'PUBLIC_HUMANBEHAVIOR_API_KEY',
904
+ angular: 'HUMANBEHAVIOR_API_KEY',
905
+ nuxt: 'NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY',
906
+ remix: 'HUMANBEHAVIOR_API_KEY',
907
+ vanilla: 'HUMANBEHAVIOR_API_KEY',
908
+ node: 'HUMANBEHAVIOR_API_KEY'
909
+ };
910
+ return envVarNames[framework.type] || 'HUMANBEHAVIOR_API_KEY';
911
+ };
912
+ const envVarName = getEnvVarName(framework);
913
+ // Check for existing files
914
+ for (const envFile of possibleEnvFiles) {
915
+ const fullPath = path.join(this.projectRoot, envFile);
916
+ if (fs.existsSync(fullPath)) {
917
+ return { filePath: fullPath, envVarName };
918
+ }
919
+ }
920
+ // Framework-specific default file creation
921
+ const defaultFiles = {
922
+ react: '.env.local',
923
+ nextjs: '.env.local',
924
+ vue: '.env.local',
925
+ svelte: '.env',
926
+ angular: '.env',
927
+ nuxt: '.env',
928
+ remix: '.env.local',
929
+ vanilla: '.env',
930
+ node: '.env'
931
+ };
932
+ const defaultFile = defaultFiles[framework.type] || '.env';
933
+ return {
934
+ filePath: path.join(this.projectRoot, defaultFile),
935
+ envVarName
936
+ };
937
+ }
938
+ /**
939
+ * Helper method to create or append to environment files
940
+ */
941
+ createEnvironmentModification(framework) {
942
+ const { filePath, envVarName } = this.findBestEnvFile(framework);
943
+ if (fs.existsSync(filePath)) {
944
+ // Check if the variable already exists
945
+ const content = fs.readFileSync(filePath, 'utf8');
946
+ if (content.includes(envVarName)) {
947
+ // Variable exists, don't modify
948
+ return {
949
+ filePath,
950
+ action: 'modify',
951
+ content: content, // No change
952
+ description: `API key already exists in ${path.basename(filePath)}`
953
+ };
954
+ }
955
+ else {
956
+ // Append to existing file
957
+ return {
958
+ filePath,
959
+ action: 'append',
960
+ content: `\n${envVarName}=${this.apiKey}`,
961
+ description: `Added API key to existing ${path.basename(filePath)}`
962
+ };
963
+ }
964
+ }
965
+ else {
966
+ // Create new file
967
+ return {
968
+ filePath,
969
+ action: 'create',
970
+ content: `${envVarName}=${this.apiKey}`,
971
+ description: `Created ${path.basename(filePath)} with API key`
972
+ };
973
+ }
974
+ }
975
+ }
976
+
977
+ /**
978
+ * HumanBehavior SDK Auto-Installation CLI
979
+ *
980
+ * Usage: npx humanbehavior-js auto-install [api-key]
981
+ *
982
+ * This tool automatically detects the user's framework and modifies their codebase
983
+ * to integrate the SDK with minimal user intervention.
984
+ */
985
+ class AutoInstallCLI {
986
+ constructor(options) {
987
+ this.options = options;
988
+ this.rl = readline.createInterface({
989
+ input: process.stdin,
990
+ output: process.stdout
991
+ });
992
+ }
993
+ run() {
994
+ return __awaiter(this, void 0, void 0, function* () {
995
+ console.log('šŸš€ HumanBehavior SDK Auto-Installation');
996
+ console.log('=====================================\n');
997
+ try {
998
+ // Get API key
999
+ const apiKey = yield this.getApiKey();
1000
+ if (!apiKey) {
1001
+ console.error('āŒ API key is required');
1002
+ process.exit(1);
1003
+ }
1004
+ // Get project path
1005
+ const projectPath = this.options.projectPath || process.cwd();
1006
+ // Confirm installation
1007
+ if (!this.options.yes) {
1008
+ const confirmed = yield this.confirmInstallation(projectPath);
1009
+ if (!confirmed) {
1010
+ console.log('Installation cancelled.');
1011
+ process.exit(0);
1012
+ }
1013
+ }
1014
+ // Run auto-installation
1015
+ console.log('šŸ” Detecting your project setup...');
1016
+ const wizard = new AutoInstallationWizard(apiKey, projectPath);
1017
+ const result = yield wizard.install();
1018
+ // Display results
1019
+ this.displayResults(result);
1020
+ }
1021
+ catch (error) {
1022
+ console.error('āŒ Error:', error instanceof Error ? error.message : error);
1023
+ process.exit(1);
1024
+ }
1025
+ finally {
1026
+ this.rl.close();
1027
+ }
1028
+ });
1029
+ }
1030
+ getApiKey() {
1031
+ return __awaiter(this, void 0, void 0, function* () {
1032
+ if (this.options.apiKey) {
1033
+ return this.options.apiKey;
1034
+ }
1035
+ return new Promise((resolve) => {
1036
+ this.rl.question('Enter your HumanBehavior API key: ', (answer) => {
1037
+ resolve(answer.trim());
1038
+ });
1039
+ });
1040
+ });
1041
+ }
1042
+ confirmInstallation(projectPath) {
1043
+ return __awaiter(this, void 0, void 0, function* () {
1044
+ console.log(`šŸ“ Project path: ${projectPath}`);
1045
+ console.log('āš ļø This will modify your codebase to integrate HumanBehavior SDK.');
1046
+ console.log(' The following changes will be made:');
1047
+ console.log(' - Install humanbehavior-js package');
1048
+ console.log(' - Modify your main app file');
1049
+ console.log(' - Create environment files');
1050
+ console.log(' - Add SDK initialization code\n');
1051
+ return new Promise((resolve) => {
1052
+ this.rl.question('Continue with auto-installation? (y/n): ', (answer) => {
1053
+ resolve(answer.toLowerCase() === 'y' || answer.toLowerCase() === 'yes');
1054
+ });
1055
+ });
1056
+ });
1057
+ }
1058
+ displayResults(result) {
1059
+ if (result.success) {
1060
+ console.log('\nāœ… Installation completed successfully!');
1061
+ console.log(`šŸ“¦ Framework detected: ${result.framework.name}`);
1062
+ if (result.framework.bundler) {
1063
+ console.log(`šŸ”§ Bundler: ${result.framework.bundler}`);
1064
+ }
1065
+ if (result.framework.packageManager) {
1066
+ console.log(`šŸ“‹ Package Manager: ${result.framework.packageManager}`);
1067
+ }
1068
+ console.log('\nšŸ“ Changes made:');
1069
+ result.modifications.forEach((mod) => {
1070
+ console.log(` ${mod.action === 'create' ? 'āž•' : 'āœļø'} ${mod.description}`);
1071
+ console.log(` ${mod.filePath}`);
1072
+ });
1073
+ console.log('\nšŸŽÆ Next steps:');
1074
+ result.nextSteps.forEach((step) => {
1075
+ console.log(` ${step}`);
1076
+ });
1077
+ console.log('\nšŸš€ Your app is now ready to track user behavior!');
1078
+ console.log('šŸ“Š View sessions in your HumanBehavior dashboard');
1079
+ }
1080
+ else {
1081
+ console.log('\nāŒ Installation failed:');
1082
+ result.errors.forEach((error) => {
1083
+ console.log(` ${error}`);
1084
+ });
1085
+ console.log('\nšŸ’” Try running with --help for more options');
1086
+ }
1087
+ }
1088
+ }
1089
+ // CLI argument parsing
1090
+ function parseArgs() {
1091
+ const args = process.argv.slice(2);
1092
+ const options = {};
1093
+ for (let i = 0; i < args.length; i++) {
1094
+ const arg = args[i];
1095
+ if (arg === '--yes' || arg === '-y') {
1096
+ options.yes = true;
1097
+ }
1098
+ else if (arg === '--dry-run' || arg === '-d') {
1099
+ options.dryRun = true;
1100
+ }
1101
+ else if (arg === '--project' || arg === '-p') {
1102
+ options.projectPath = args[i + 1];
1103
+ i++;
1104
+ }
1105
+ else if (arg === '--help' || arg === '-h') {
1106
+ showHelp();
1107
+ process.exit(0);
1108
+ }
1109
+ else if (!options.apiKey) {
1110
+ options.apiKey = arg;
1111
+ }
1112
+ }
1113
+ return options;
1114
+ }
1115
+ function showHelp() {
1116
+ console.log(`
1117
+ HumanBehavior SDK Auto-Installation CLI
1118
+
1119
+ Usage: npx humanbehavior-js auto-install [api-key] [options]
1120
+
1121
+ This tool automatically detects your project's framework and modifies your codebase
1122
+ to integrate the HumanBehavior SDK with minimal user intervention.
1123
+
1124
+ Arguments:
1125
+ api-key Your HumanBehavior API key
1126
+
1127
+ Options:
1128
+ -y, --yes Skip all prompts and use defaults
1129
+ -d, --dry-run Show what would be changed without making changes
1130
+ -p, --project <path> Project directory (default: current directory)
1131
+ -h, --help Show this help message
1132
+
1133
+ Examples:
1134
+ npx humanbehavior-js auto-install your-api-key
1135
+ npx humanbehavior-js auto-install your-api-key --yes
1136
+ npx humanbehavior-js auto-install your-api-key -p /path/to/project
1137
+
1138
+ Supported Frameworks:
1139
+ āœ… React (CRA, Vite, Webpack)
1140
+ āœ… Next.js (App Router, Pages Router)
1141
+ āœ… Vue (Vue CLI, Vite)
1142
+ āœ… Angular
1143
+ āœ… Svelte (SvelteKit, Vite)
1144
+ āœ… Vanilla JS/TS
1145
+ āœ… Node.js (CommonJS & ESM)
1146
+
1147
+ The tool will:
1148
+ 1. šŸ” Auto-detect your project's framework and setup
1149
+ 2. šŸ“¦ Install the humanbehavior-js package
1150
+ 3. āœļø Modify your codebase to integrate the SDK
1151
+ 4. šŸ”§ Create environment files with your API key
1152
+ 5. šŸš€ Make your app ready to track user behavior
1153
+ `);
1154
+ }
1155
+ // Main execution
1156
+ if (import.meta.url === `file://${process.argv[1]}`) {
1157
+ const options = parseArgs();
1158
+ if (process.argv.length < 3 || process.argv.includes('--help') || process.argv.includes('-h')) {
1159
+ showHelp();
1160
+ process.exit(0);
1161
+ }
1162
+ const cli = new AutoInstallCLI(options);
1163
+ cli.run().catch((error) => {
1164
+ console.error('āŒ Fatal error:', error);
1165
+ process.exit(1);
1166
+ });
1167
+ }
1168
+
1169
+ export { AutoInstallCLI };
1170
+ //# sourceMappingURL=auto-install.js.map