@posthog/wizard 1.21.1 → 1.23.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.
@@ -1,390 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.runEventSetupWizard = runEventSetupWizard;
40
- const clack_utils_1 = require("../utils/clack-utils");
41
- const clack_1 = __importDefault(require("../utils/clack"));
42
- const fs = __importStar(require("fs/promises"));
43
- const path = __importStar(require("path"));
44
- const chalk_1 = __importDefault(require("chalk"));
45
- const query_1 = require("../utils/query");
46
- const zod_1 = require("zod");
47
- const file_utils_1 = require("../utils/file-utils");
48
- const package_json_1 = require("../utils/package-json");
49
- const semver = __importStar(require("semver"));
50
- const debug_1 = require("../utils/debug");
51
- const analytics_1 = require("../utils/analytics");
52
- // Analytics constants
53
- const WIZARD_INTERACTION = 'wizard interaction';
54
- const INTEGRATION_NAME = 'event-setup';
55
- // Schema for file selection from AI
56
- const FileSelectionSchema = zod_1.z.object({
57
- files: zod_1.z.array(zod_1.z.string()).max(10),
58
- });
59
- // Schema for enhanced file with events
60
- const EnhancedFileSchema = zod_1.z.object({
61
- filePath: zod_1.z.string(),
62
- content: zod_1.z.string(),
63
- events: zod_1.z.array(zod_1.z.object({
64
- name: zod_1.z.string(),
65
- description: zod_1.z.string(),
66
- })),
67
- });
68
- async function runEventSetupWizard(options) {
69
- if (options.debug) {
70
- (0, debug_1.enableDebugLogs)();
71
- }
72
- clack_1.default.intro(`Let's do a first pass on PostHog event tracking for your project.
73
-
74
- We'll start by analyzing your project structure, then choose up to ten files to enhance. Use git to discard any events you're not happy with.
75
-
76
- This will give you a starting point, then you can add any events that we missed.
77
- `);
78
- // Check for uncommitted changes
79
- if ((0, clack_utils_1.isInGitRepo)()) {
80
- const uncommittedOrUntrackedFiles = (0, clack_utils_1.getUncommittedOrUntrackedFiles)();
81
- if (uncommittedOrUntrackedFiles.length) {
82
- clack_1.default.log.warn(`You have uncommitted or untracked files in your repo:
83
-
84
- ${uncommittedOrUntrackedFiles.join('\n')}
85
-
86
- The event setup wizard will modify multiple files. For the best experience, commit or stash your changes first.`);
87
- const continueWithDirtyRepo = await (0, clack_utils_1.abortIfCancelled)(clack_1.default.confirm({
88
- message: 'Do you want to continue anyway?',
89
- }));
90
- if (!continueWithDirtyRepo) {
91
- analytics_1.analytics.capture(WIZARD_INTERACTION, {
92
- action: 'aborted due to uncommitted changes',
93
- integration: INTEGRATION_NAME,
94
- });
95
- return (0, clack_utils_1.abort)('Please commit your changes and try again.', 0);
96
- }
97
- analytics_1.analytics.capture(WIZARD_INTERACTION, {
98
- action: 'continued with uncommitted changes',
99
- integration: INTEGRATION_NAME,
100
- });
101
- }
102
- }
103
- const cloudRegion = options.cloudRegion ?? (await (0, clack_utils_1.askForCloudRegion)());
104
- const { accessToken, projectId } = await (0, clack_utils_1.getOrAskForProjectData)({
105
- ...options,
106
- cloudRegion,
107
- });
108
- // Check if this is a Next.js 15.3+ project with instrumentation-client
109
- const packageJson = await (0, clack_utils_1.getPackageDotJson)(options);
110
- const isNextJs = (0, package_json_1.hasPackageInstalled)('next', packageJson);
111
- if (!isNextJs) {
112
- return (0, clack_utils_1.abort)('This feature is only available for Next.js projects.');
113
- }
114
- const nextVersion = (0, package_json_1.getPackageVersion)('next', packageJson);
115
- const isNext15_3Plus = nextVersion && semver.gte(nextVersion, '15.3.0');
116
- analytics_1.analytics.setTag('nextjs-version', nextVersion);
117
- if (!isNext15_3Plus) {
118
- analytics_1.analytics.capture(WIZARD_INTERACTION, {
119
- action: 'aborted due to nextjs version',
120
- integration: INTEGRATION_NAME,
121
- nextjsVersion: nextVersion,
122
- });
123
- return (0, clack_utils_1.abort)('This feature requires Next.js 15.3.0 or higher.');
124
- }
125
- // Check for instrumentation-client file
126
- const allFiles = await (0, file_utils_1.getAllFilesInProject)(options.installDir);
127
- const instrumentationFiles = allFiles.filter((f) => f.includes('instrumentation') &&
128
- (f.endsWith('.ts') || f.endsWith('.js')) &&
129
- (f.includes('client') || f.includes('Client')));
130
- if (instrumentationFiles.length === 0) {
131
- analytics_1.analytics.capture(WIZARD_INTERACTION, {
132
- action: 'aborted due to missing instrumentation-client',
133
- integration: INTEGRATION_NAME,
134
- });
135
- return (0, clack_utils_1.abort)('No instrumentation-client file found. Please set up Next.js instrumentation-client first. Try using this wizard to do it!');
136
- }
137
- analytics_1.analytics.capture(WIZARD_INTERACTION, {
138
- action: 'started event setup',
139
- integration: INTEGRATION_NAME,
140
- instrumentationFilesCount: instrumentationFiles.length,
141
- });
142
- // Get the project file tree
143
- const s = clack_1.default.spinner();
144
- s.start('Analyzing your project structure');
145
- const projectFiles = await (0, file_utils_1.getAllFilesInProject)(options.installDir);
146
- const relativeFiles = projectFiles
147
- .map((f) => path.relative(options.installDir, f))
148
- .filter((f) => {
149
- // Exclude instrumentation files and next.config
150
- const isInstrumentation = f.includes('instrumentation') &&
151
- (f.endsWith('.ts') || f.endsWith('.js'));
152
- const isNextConfig = f.startsWith('next.config.') || f === 'next.config';
153
- return !isInstrumentation && !isNextConfig;
154
- });
155
- (0, debug_1.debug)('Total files found:', projectFiles.length);
156
- (0, debug_1.debug)('Files after filtering:', relativeFiles.length);
157
- s.stop('Project structure analyzed');
158
- analytics_1.analytics.capture(WIZARD_INTERACTION, {
159
- action: 'analyzed project structure',
160
- integration: INTEGRATION_NAME,
161
- totalFiles: projectFiles.length,
162
- eligibleFiles: relativeFiles.length,
163
- });
164
- // Send file tree to AI to get 10 most useful files
165
- s.start('Selecting some files to enhance with events...');
166
- const fileSelectionPrompt = `Given this Next.js 15.3+ project structure and package.json, select up to 10 CLIENT-SIDE FILES for adding PostHog analytics events.
167
-
168
- IMPORTANT: Only select files that:
169
- - Have "use client" directive at the top, OR
170
- - Use React hooks (useState, useEffect, etc.), OR
171
- - Have event handlers (onClick, onSubmit, onChange)
172
-
173
- DO NOT select:
174
- - API routes (files in /api/ or route.ts/route.js files)
175
- - Server Components (files without "use client" and no hooks/handlers)
176
- - Layout files (layout.tsx/layout.js)
177
- - Configuration files
178
- - Pure utility files
179
-
180
- Focus on:
181
- - User interaction points (buttons, forms, navigation)
182
- - Key user flows (auth, checkout, main features)
183
- - Business-critical paths
184
- - Files that represent important user actions
185
-
186
- Package.json:
187
- ${JSON.stringify(packageJson, null, 2)}
188
-
189
- Project files:
190
- ${relativeFiles.join('\n')}
191
-
192
- Return file paths for client-side files ONLY that would benefit most from analytics tracking. If there are fewer than 10 suitable client files, return only those.`;
193
- let selectedFiles = [];
194
- try {
195
- const response = await (0, query_1.query)({
196
- message: fileSelectionPrompt,
197
- model: 'gemini-2.5-flash',
198
- region: cloudRegion,
199
- schema: FileSelectionSchema,
200
- accessToken,
201
- projectId,
202
- });
203
- selectedFiles = response.files;
204
- s.stop(`Selected ${selectedFiles.length} files for event tracking`);
205
- analytics_1.analytics.capture(WIZARD_INTERACTION, {
206
- action: 'selected files for tracking',
207
- integration: INTEGRATION_NAME,
208
- filesSelected: selectedFiles.length,
209
- });
210
- }
211
- catch (error) {
212
- s.stop('Failed to select files');
213
- analytics_1.analytics.capture(WIZARD_INTERACTION, {
214
- action: 'file selection failed',
215
- integration: INTEGRATION_NAME,
216
- error: error instanceof Error ? error.message : 'Unknown error',
217
- });
218
- return (0, clack_utils_1.abort)('Could not analyze project structure. Please try again.');
219
- }
220
- // Read the selected files and enhance them with events
221
- clack_1.default.log.info('Files selected for event tracking:');
222
- selectedFiles.forEach((file, index) => {
223
- clack_1.default.log.info(` ${index + 1}. ${file}`);
224
- });
225
- const enhancedFiles = [];
226
- clack_1.default.log.info("\nEnhancing files with event tracking. Changes will be applied as they come in. Use your git interface to review new events. Feel free to toss anything you don't like...");
227
- for (const filePath of selectedFiles) {
228
- const fileSpinner = clack_1.default.spinner();
229
- fileSpinner.start(`Analyzing ${filePath}`);
230
- try {
231
- const fullPath = path.join(options.installDir, filePath);
232
- const fileContent = await fs.readFile(fullPath, 'utf8');
233
- const enhancePrompt = `You are enhancing a REAL production, client-side Next.js file with PostHog analytics. This is NOT an example or tutorial - add events to the ACTUAL code provided.
234
-
235
- - REQUIRED: import posthog from 'posthog-js'
236
- - Track events with: posthog.capture('event-name', { property: 'value' })
237
- - NEVER import PostHogClient from '@/app/posthog'
238
- - NEVER create functions with 'use server'
239
-
240
- CRITICAL INSTRUCTIONS:
241
- - This is a REAL file from a production codebase
242
- - DO NOT add placeholder comments like "// In a real app..." or "// This is an example..."
243
- - DO NOT modify the existing business logic or add simulation code
244
- - DO NOT add any tutorial-style comments
245
- - ONLY add PostHog event tracking to the existing, real functionality
246
- - DO NOT create wrapper functions around existing functions just to add tracking
247
- - Add tracking code directly inside existing functions where appropriate
248
- - NEVER import new packages or libraries that aren't already used in the file
249
- - ONLY use imports that already exist in the file or the PostHog imports specified
250
- - DO NOT assume any authentication library (Clerk, Auth.js, etc.) is available
251
-
252
- FORBIDDEN - NEVER DO THESE:
253
- - NEVER add 'use client' or 'use server' directives at the top of the file, or in functions
254
- - NEVER define new server actions (functions with "use server") in Client Components
255
- - NEVER create inline "use server" functions in files that have "use client"
256
- - NEVER use useEffect to track page views or component renders
257
- - NEVER track events like "page_viewed", "form_viewed", "component_rendered", "flow_started", "page_opened" etc
258
- - NEVER track that someone simply arrived at or viewed a page
259
- - NEVER change the file's existing client/server architecture
260
- - NEVER add events on component mount or render - only on actual user interactions
261
- - Track events on user interactions like clicks, form submissions, etc.
262
-
263
- Technical Rules:
264
- - This is a client-side file suitable for event tracking
265
- - REQUIRED IMPORT: import posthog from 'posthog-js'
266
- - Use the existing posthog instance for all tracking
267
- - Example: posthog.capture('button-clicked', { buttonId: 'submit' })
268
- - Focus on tracking user interactions in the UI components
269
- - Track events like button clicks, form submissions, navigation, etc.
270
- - Add 1-2 high-value events that track the ACTUAL user actions in this file
271
- - Use descriptive event names (lowercase-hyphenated) based on what the code ACTUALLY does
272
- - Include properties that capture REAL data from the existing code
273
- - For user identification: ONLY use user data that's already available in the code
274
- - DO NOT add code to fetch user IDs or authentication state if not already available in the file
275
- - Do not change the formatting of the file; only add events
276
- - Do not set timestamps on events; PostHog will do this automatically
277
- - Always return the entire file content, not just the changes
278
- - NEVER add events that correspond to page views; PostHog tracks these automatically
279
- - NEVER INSERT "use client" or "use server" directives
280
-
281
- File path: ${filePath}
282
- File content:
283
- ${fileContent}
284
-
285
- IMPORTANT: If this file only renders UI without any user interactions (no buttons, forms, or actions),
286
- or if the only possible events would be pageview-like (e.g., "form-viewed", "page-opened", "flow-started"),
287
- then SKIP THIS FILE by returning the original content unchanged. We only want to track actual user actions,
288
- not that someone looked at a page.
289
-
290
- Return the enhanced file with PostHog tracking added to the EXISTING functionality. List the events you added.`;
291
- const response = await (0, query_1.query)({
292
- message: enhancePrompt,
293
- model: 'gemini-2.5-pro',
294
- region: cloudRegion,
295
- schema: EnhancedFileSchema,
296
- accessToken,
297
- projectId,
298
- });
299
- // Apply changes immediately
300
- if (response.content !== fileContent) {
301
- await (0, file_utils_1.updateFile)({
302
- filePath,
303
- oldContent: fileContent,
304
- newContent: response.content,
305
- }, options);
306
- enhancedFiles.push({
307
- filePath,
308
- events: response.events,
309
- });
310
- fileSpinner.stop(`✓ Enhanced ${filePath} with ${response.events.length} events`);
311
- analytics_1.analytics.capture(WIZARD_INTERACTION, {
312
- action: 'enhanced file',
313
- integration: INTEGRATION_NAME,
314
- filePath,
315
- eventsAdded: response.events.length,
316
- });
317
- }
318
- else {
319
- fileSpinner.stop(`No changes needed for ${filePath}`);
320
- analytics_1.analytics.capture(WIZARD_INTERACTION, {
321
- action: 'file skipped',
322
- integration: INTEGRATION_NAME,
323
- filePath,
324
- reason: 'no events to add',
325
- });
326
- }
327
- }
328
- catch (error) {
329
- fileSpinner.stop(`✗ Failed to enhance ${filePath}`);
330
- (0, debug_1.debug)('Error enhancing file:', error);
331
- analytics_1.analytics.capture(WIZARD_INTERACTION, {
332
- action: 'file enhancement failed',
333
- integration: INTEGRATION_NAME,
334
- filePath,
335
- error: error instanceof Error ? error.message : 'Unknown error',
336
- });
337
- }
338
- }
339
- // Generate event tracking report
340
- const generateMarkdown = () => {
341
- let md = `# Event tracking report\n\n`;
342
- md += `This document lists all PostHog events that have been automatically added to your Next.js application.\n\n`;
343
- md += `## Events by File\n\n`;
344
- enhancedFiles.forEach((file) => {
345
- if (file.events.length > 0) {
346
- md += `### ${file.filePath}\n\n`;
347
- file.events.forEach((event) => {
348
- md += `- **${event.name}**: ${event.description}\n`;
349
- });
350
- md += `\n`;
351
- }
352
- });
353
- md += `\n## Events still awaiting implementation\n`;
354
- md += `- (human: you can fill these in)`;
355
- md += `\n---\n\n`;
356
- md += `## Next Steps\n\n`;
357
- md += `1. Review the changes made to your files\n`;
358
- md += `2. Test that events are being captured correctly\n`;
359
- md += `3. Create insights and dashboards in PostHog\n`;
360
- md += `4. Make a list of events we missed above. Knock them out yourself, or give this file to an agent.\n\n`;
361
- md += `Learn more about what to measure with PostHog and why: https://posthog.com/docs/new-to-posthog/getting-hogpilled\n`;
362
- return md;
363
- };
364
- const markdownContent = generateMarkdown();
365
- const fileName = 'event-tracking-report.md';
366
- const filePath = path.join(options.installDir, fileName);
367
- await fs.writeFile(filePath, markdownContent);
368
- // Summary
369
- const totalEvents = enhancedFiles.reduce((sum, file) => sum + file.events.length, 0);
370
- analytics_1.analytics.capture(WIZARD_INTERACTION, {
371
- action: 'event setup completed',
372
- integration: INTEGRATION_NAME,
373
- totalEvents,
374
- filesEnhanced: enhancedFiles.length,
375
- filesProcessed: selectedFiles.length,
376
- });
377
- analytics_1.analytics.setTag('event-setup-total-events', totalEvents);
378
- analytics_1.analytics.setTag('event-setup-files-enhanced', enhancedFiles.length);
379
- clack_1.default.outro(`Success! Added ${chalk_1.default.bold(totalEvents.toString())} events across ${chalk_1.default.bold(enhancedFiles.length.toString())} files.
380
-
381
- Event tracking plan saved to: ${chalk_1.default.cyan(fileName)}
382
-
383
- Next steps:
384
- 1. Review changes with your favorite git tool
385
- 2. Revert unwanted changes with ${chalk_1.default.bold('git checkout <file>')}
386
- 3. Test that events are being captured in your PostHog project
387
- 4. Create insights in PostHog
388
- `);
389
- }
390
- //# sourceMappingURL=event-setup.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"event-setup.js","sourceRoot":"","sources":["../../../src/nextjs/event-setup.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,kDAoYC;AA/aD,sDAQ8B;AAC9B,2DAAmC;AAEnC,gDAAkC;AAClC,2CAA6B;AAC7B,kDAA0B;AAC1B,0CAAuC;AACvC,6BAAwB;AACxB,oDAAuE;AACvE,wDAA+E;AAC/E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IlB,eAAK,CAAC,IAAI,CAAC,qBAAqB,CAAC;;;KAGlE,CACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n abort,\n getOrAskForProjectData,\n askForCloudRegion,\n getPackageDotJson,\n getUncommittedOrUntrackedFiles,\n isInGitRepo,\n abortIfCancelled,\n} from '../utils/clack-utils';\nimport clack from '../utils/clack';\nimport { WizardOptions } from '../utils/types';\nimport * as fs from 'fs/promises';\nimport * as path from 'path';\nimport chalk from 'chalk';\nimport { query } from '../utils/query';\nimport { z } from 'zod';\nimport { getAllFilesInProject, updateFile } from '../utils/file-utils';\nimport { getPackageVersion, hasPackageInstalled } from '../utils/package-json';\nimport * as semver from 'semver';\nimport { enableDebugLogs, debug } from '../utils/debug';\nimport { analytics } from '../utils/analytics';\n\n// Analytics constants\nconst WIZARD_INTERACTION = 'wizard interaction';\nconst INTEGRATION_NAME = 'event-setup';\n\n// Schema for file selection from AI\nconst FileSelectionSchema = z.object({\n files: z.array(z.string()).max(10),\n});\n\n// Schema for enhanced file with events\nconst EnhancedFileSchema = z.object({\n filePath: z.string(),\n content: z.string(),\n events: z.array(\n z.object({\n name: z.string(),\n description: z.string(),\n }),\n ),\n});\n\nexport async function runEventSetupWizard(\n options: WizardOptions,\n): Promise<void> {\n if (options.debug) {\n enableDebugLogs();\n }\n\n clack.intro(\n `Let's do a first pass on PostHog event tracking for your project.\n \n We'll start by analyzing your project structure, then choose up to ten files to enhance. Use git to discard any events you're not happy with.\n\n This will give you a starting point, then you can add any events that we missed.\n `,\n );\n\n // Check for uncommitted changes\n if (isInGitRepo()) {\n const uncommittedOrUntrackedFiles = getUncommittedOrUntrackedFiles();\n if (uncommittedOrUntrackedFiles.length) {\n clack.log.warn(\n `You have uncommitted or untracked files in your repo:\n\n${uncommittedOrUntrackedFiles.join('\\n')}\n\nThe event setup wizard will modify multiple files. For the best experience, commit or stash your changes first.`,\n );\n const continueWithDirtyRepo = await abortIfCancelled(\n clack.confirm({\n message: 'Do you want to continue anyway?',\n }),\n );\n if (!continueWithDirtyRepo) {\n analytics.capture(WIZARD_INTERACTION, {\n action: 'aborted due to uncommitted changes',\n integration: INTEGRATION_NAME,\n });\n return abort('Please commit your changes and try again.', 0);\n }\n analytics.capture(WIZARD_INTERACTION, {\n action: 'continued with uncommitted changes',\n integration: INTEGRATION_NAME,\n });\n }\n }\n\n const cloudRegion = options.cloudRegion ?? (await askForCloudRegion());\n\n const { accessToken, projectId } = await getOrAskForProjectData({\n ...options,\n cloudRegion,\n });\n\n // Check if this is a Next.js 15.3+ project with instrumentation-client\n const packageJson = await getPackageDotJson(options);\n const isNextJs = hasPackageInstalled('next', packageJson);\n\n if (!isNextJs) {\n return abort('This feature is only available for Next.js projects.');\n }\n\n const nextVersion = getPackageVersion('next', packageJson);\n const isNext15_3Plus = nextVersion && semver.gte(nextVersion, '15.3.0');\n\n analytics.setTag('nextjs-version', nextVersion);\n\n if (!isNext15_3Plus) {\n analytics.capture(WIZARD_INTERACTION, {\n action: 'aborted due to nextjs version',\n integration: INTEGRATION_NAME,\n nextjsVersion: nextVersion,\n });\n return abort('This feature requires Next.js 15.3.0 or higher.');\n }\n\n // Check for instrumentation-client file\n const allFiles = await getAllFilesInProject(options.installDir);\n const instrumentationFiles = allFiles.filter(\n (f) =>\n f.includes('instrumentation') &&\n (f.endsWith('.ts') || f.endsWith('.js')) &&\n (f.includes('client') || f.includes('Client')),\n );\n\n if (instrumentationFiles.length === 0) {\n analytics.capture(WIZARD_INTERACTION, {\n action: 'aborted due to missing instrumentation-client',\n integration: INTEGRATION_NAME,\n });\n return abort(\n 'No instrumentation-client file found. Please set up Next.js instrumentation-client first. Try using this wizard to do it!',\n );\n }\n\n analytics.capture(WIZARD_INTERACTION, {\n action: 'started event setup',\n integration: INTEGRATION_NAME,\n instrumentationFilesCount: instrumentationFiles.length,\n });\n\n // Get the project file tree\n const s = clack.spinner();\n s.start('Analyzing your project structure');\n\n const projectFiles = await getAllFilesInProject(options.installDir);\n const relativeFiles = projectFiles\n .map((f) => path.relative(options.installDir, f))\n .filter((f) => {\n // Exclude instrumentation files and next.config\n const isInstrumentation =\n f.includes('instrumentation') &&\n (f.endsWith('.ts') || f.endsWith('.js'));\n const isNextConfig = f.startsWith('next.config.') || f === 'next.config';\n return !isInstrumentation && !isNextConfig;\n });\n\n debug('Total files found:', projectFiles.length);\n debug('Files after filtering:', relativeFiles.length);\n s.stop('Project structure analyzed');\n\n analytics.capture(WIZARD_INTERACTION, {\n action: 'analyzed project structure',\n integration: INTEGRATION_NAME,\n totalFiles: projectFiles.length,\n eligibleFiles: relativeFiles.length,\n });\n\n // Send file tree to AI to get 10 most useful files\n s.start('Selecting some files to enhance with events...');\n\n const fileSelectionPrompt = `Given this Next.js 15.3+ project structure and package.json, select up to 10 CLIENT-SIDE FILES for adding PostHog analytics events.\n \n IMPORTANT: Only select files that:\n - Have \"use client\" directive at the top, OR\n - Use React hooks (useState, useEffect, etc.), OR \n - Have event handlers (onClick, onSubmit, onChange)\n \n DO NOT select:\n - API routes (files in /api/ or route.ts/route.js files)\n - Server Components (files without \"use client\" and no hooks/handlers)\n - Layout files (layout.tsx/layout.js)\n - Configuration files\n - Pure utility files\n \n Focus on:\n - User interaction points (buttons, forms, navigation)\n - Key user flows (auth, checkout, main features)\n - Business-critical paths\n - Files that represent important user actions\n \n Package.json:\n ${JSON.stringify(packageJson, null, 2)}\n \n Project files:\n ${relativeFiles.join('\\n')}\n \n Return file paths for client-side files ONLY that would benefit most from analytics tracking. If there are fewer than 10 suitable client files, return only those.`;\n\n let selectedFiles: string[] = [];\n try {\n const response = await query({\n message: fileSelectionPrompt,\n model: 'gemini-2.5-flash',\n region: cloudRegion,\n schema: FileSelectionSchema,\n accessToken,\n projectId,\n });\n selectedFiles = response.files;\n s.stop(`Selected ${selectedFiles.length} files for event tracking`);\n analytics.capture(WIZARD_INTERACTION, {\n action: 'selected files for tracking',\n integration: INTEGRATION_NAME,\n filesSelected: selectedFiles.length,\n });\n } catch (error) {\n s.stop('Failed to select files');\n analytics.capture(WIZARD_INTERACTION, {\n action: 'file selection failed',\n integration: INTEGRATION_NAME,\n error: error instanceof Error ? error.message : 'Unknown error',\n });\n return abort('Could not analyze project structure. Please try again.');\n }\n\n // Read the selected files and enhance them with events\n clack.log.info('Files selected for event tracking:');\n selectedFiles.forEach((file, index) => {\n clack.log.info(` ${index + 1}. ${file}`);\n });\n\n const enhancedFiles: Array<{\n filePath: string;\n events: Array<{ name: string; description: string }>;\n }> = [];\n\n clack.log.info(\n \"\\nEnhancing files with event tracking. Changes will be applied as they come in. Use your git interface to review new events. Feel free to toss anything you don't like...\",\n );\n\n for (const filePath of selectedFiles) {\n const fileSpinner = clack.spinner();\n fileSpinner.start(`Analyzing ${filePath}`);\n\n try {\n const fullPath = path.join(options.installDir, filePath);\n const fileContent = await fs.readFile(fullPath, 'utf8');\n\n const enhancePrompt = `You are enhancing a REAL production, client-side Next.js file with PostHog analytics. This is NOT an example or tutorial - add events to the ACTUAL code provided.\n \n - REQUIRED: import posthog from 'posthog-js'\n - Track events with: posthog.capture('event-name', { property: 'value' })\n - NEVER import PostHogClient from '@/app/posthog'\n - NEVER create functions with 'use server'\n\n CRITICAL INSTRUCTIONS:\n - This is a REAL file from a production codebase\n - DO NOT add placeholder comments like \"// In a real app...\" or \"// This is an example...\"\n - DO NOT modify the existing business logic or add simulation code\n - DO NOT add any tutorial-style comments\n - ONLY add PostHog event tracking to the existing, real functionality\n - DO NOT create wrapper functions around existing functions just to add tracking\n - Add tracking code directly inside existing functions where appropriate\n - NEVER import new packages or libraries that aren't already used in the file\n - ONLY use imports that already exist in the file or the PostHog imports specified\n - DO NOT assume any authentication library (Clerk, Auth.js, etc.) is available\n \n FORBIDDEN - NEVER DO THESE:\n - NEVER add 'use client' or 'use server' directives at the top of the file, or in functions\n - NEVER define new server actions (functions with \"use server\") in Client Components\n - NEVER create inline \"use server\" functions in files that have \"use client\"\n - NEVER use useEffect to track page views or component renders\n - NEVER track events like \"page_viewed\", \"form_viewed\", \"component_rendered\", \"flow_started\", \"page_opened\" etc\n - NEVER track that someone simply arrived at or viewed a page\n - NEVER change the file's existing client/server architecture\n - NEVER add events on component mount or render - only on actual user interactions\n - Track events on user interactions like clicks, form submissions, etc.\n \n Technical Rules:\n - This is a client-side file suitable for event tracking\n - REQUIRED IMPORT: import posthog from 'posthog-js'\n - Use the existing posthog instance for all tracking\n - Example: posthog.capture('button-clicked', { buttonId: 'submit' })\n - Focus on tracking user interactions in the UI components\n - Track events like button clicks, form submissions, navigation, etc.\n - Add 1-2 high-value events that track the ACTUAL user actions in this file\n - Use descriptive event names (lowercase-hyphenated) based on what the code ACTUALLY does\n - Include properties that capture REAL data from the existing code\n - For user identification: ONLY use user data that's already available in the code\n - DO NOT add code to fetch user IDs or authentication state if not already available in the file\n - Do not change the formatting of the file; only add events\n - Do not set timestamps on events; PostHog will do this automatically\n - Always return the entire file content, not just the changes\n - NEVER add events that correspond to page views; PostHog tracks these automatically\n - NEVER INSERT \"use client\" or \"use server\" directives\n \n File path: ${filePath}\n File content:\n ${fileContent}\n \n IMPORTANT: If this file only renders UI without any user interactions (no buttons, forms, or actions), \n or if the only possible events would be pageview-like (e.g., \"form-viewed\", \"page-opened\", \"flow-started\"),\n then SKIP THIS FILE by returning the original content unchanged. We only want to track actual user actions,\n not that someone looked at a page.\n \n Return the enhanced file with PostHog tracking added to the EXISTING functionality. List the events you added.`;\n\n const response = await query({\n message: enhancePrompt,\n model: 'gemini-2.5-pro',\n region: cloudRegion,\n schema: EnhancedFileSchema,\n accessToken,\n projectId,\n });\n\n // Apply changes immediately\n if (response.content !== fileContent) {\n await updateFile(\n {\n filePath,\n oldContent: fileContent,\n newContent: response.content,\n },\n options,\n );\n\n enhancedFiles.push({\n filePath,\n events: response.events,\n });\n\n fileSpinner.stop(\n `✓ Enhanced ${filePath} with ${response.events.length} events`,\n );\n analytics.capture(WIZARD_INTERACTION, {\n action: 'enhanced file',\n integration: INTEGRATION_NAME,\n filePath,\n eventsAdded: response.events.length,\n });\n } else {\n fileSpinner.stop(`No changes needed for ${filePath}`);\n analytics.capture(WIZARD_INTERACTION, {\n action: 'file skipped',\n integration: INTEGRATION_NAME,\n filePath,\n reason: 'no events to add',\n });\n }\n } catch (error) {\n fileSpinner.stop(`✗ Failed to enhance ${filePath}`);\n debug('Error enhancing file:', error);\n analytics.capture(WIZARD_INTERACTION, {\n action: 'file enhancement failed',\n integration: INTEGRATION_NAME,\n filePath,\n error: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n }\n\n // Generate event tracking report\n const generateMarkdown = () => {\n let md = `# Event tracking report\\n\\n`;\n md += `This document lists all PostHog events that have been automatically added to your Next.js application.\\n\\n`;\n md += `## Events by File\\n\\n`;\n\n enhancedFiles.forEach((file) => {\n if (file.events.length > 0) {\n md += `### ${file.filePath}\\n\\n`;\n file.events.forEach((event) => {\n md += `- **${event.name}**: ${event.description}\\n`;\n });\n md += `\\n`;\n }\n });\n\n md += `\\n## Events still awaiting implementation\\n`;\n md += `- (human: you can fill these in)`;\n\n md += `\\n---\\n\\n`;\n md += `## Next Steps\\n\\n`;\n md += `1. Review the changes made to your files\\n`;\n md += `2. Test that events are being captured correctly\\n`;\n md += `3. Create insights and dashboards in PostHog\\n`;\n md += `4. Make a list of events we missed above. Knock them out yourself, or give this file to an agent.\\n\\n`;\n md += `Learn more about what to measure with PostHog and why: https://posthog.com/docs/new-to-posthog/getting-hogpilled\\n`;\n return md;\n };\n\n const markdownContent = generateMarkdown();\n const fileName = 'event-tracking-report.md';\n const filePath = path.join(options.installDir, fileName);\n\n await fs.writeFile(filePath, markdownContent);\n\n // Summary\n const totalEvents = enhancedFiles.reduce(\n (sum, file) => sum + file.events.length,\n 0,\n );\n\n analytics.capture(WIZARD_INTERACTION, {\n action: 'event setup completed',\n integration: INTEGRATION_NAME,\n totalEvents,\n filesEnhanced: enhancedFiles.length,\n filesProcessed: selectedFiles.length,\n });\n\n analytics.setTag('event-setup-total-events', totalEvents);\n analytics.setTag('event-setup-files-enhanced', enhancedFiles.length);\n\n clack.outro(\n `Success! Added ${chalk.bold(\n totalEvents.toString(),\n )} events across ${chalk.bold(enhancedFiles.length.toString())} files.\n \n Event tracking plan saved to: ${chalk.cyan(fileName)}\n \n Next steps:\n 1. Review changes with your favorite git tool\n 2. Revert unwanted changes with ${chalk.bold('git checkout <file>')}\n 3. Test that events are being captured in your PostHog project\n 4. Create insights in PostHog\n `,\n );\n}\n"]}
@@ -1,2 +0,0 @@
1
- import type { WizardOptions } from '../utils/types';
2
- export declare function runNextjsWizard(options: WizardOptions): Promise<void>;
@@ -1,190 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.runNextjsWizard = runNextjsWizard;
40
- /* eslint-disable max-lines */
41
- const clack_utils_1 = require("../utils/clack-utils");
42
- const package_json_1 = require("../utils/package-json");
43
- const utils_1 = require("./utils");
44
- const clack_1 = __importDefault(require("../utils/clack"));
45
- const constants_1 = require("../lib/constants");
46
- const docs_1 = require("./docs");
47
- const analytics_1 = require("../utils/analytics");
48
- const file_utils_1 = require("../utils/file-utils");
49
- const clack_utils_2 = require("../utils/clack-utils");
50
- const messages_1 = require("../lib/messages");
51
- const steps_1 = require("../steps");
52
- const semver = __importStar(require("semver"));
53
- async function runNextjsWizard(options) {
54
- (0, clack_utils_1.printWelcome)({
55
- wizardName: 'PostHog Next.js wizard',
56
- });
57
- const aiConsent = await (0, clack_utils_1.askForAIConsent)(options);
58
- if (!aiConsent) {
59
- await (0, clack_utils_1.abort)('The Next.js wizard requires AI to get setup right now. Please view the docs to setup Next.js manually instead: https://posthog.com/docs/libraries/next-js', 0);
60
- }
61
- const cloudRegion = options.cloudRegion ?? (await (0, clack_utils_2.askForCloudRegion)());
62
- const typeScriptDetected = (0, clack_utils_1.isUsingTypeScript)(options);
63
- await (0, clack_utils_1.confirmContinueIfNoOrDirtyGitRepo)(options);
64
- const packageJson = await (0, clack_utils_1.getPackageDotJson)(options);
65
- await (0, clack_utils_1.ensurePackageIsInstalled)(packageJson, 'next', 'Next.js');
66
- const nextVersion = (0, package_json_1.getPackageVersion)('next', packageJson);
67
- analytics_1.analytics.setTag('nextjs-version', (0, utils_1.getNextJsVersionBucket)(nextVersion));
68
- const { projectApiKey, accessToken, host, projectId } = await (0, clack_utils_1.getOrAskForProjectData)({
69
- ...options,
70
- cloudRegion,
71
- });
72
- const sdkAlreadyInstalled = (0, package_json_1.hasPackageInstalled)('posthog-js', packageJson);
73
- analytics_1.analytics.setTag('sdk-already-installed', sdkAlreadyInstalled);
74
- const { packageManager: packageManagerFromInstallStep } = await (0, clack_utils_1.installPackage)({
75
- packageName: 'posthog-js',
76
- packageNameDisplayLabel: 'posthog-js',
77
- alreadyInstalled: !!packageJson?.dependencies?.['posthog-js'],
78
- forceInstall: options.forceInstall,
79
- askBeforeUpdating: false,
80
- installDir: options.installDir,
81
- integration: constants_1.Integration.nextjs,
82
- });
83
- await (0, clack_utils_1.installPackage)({
84
- packageName: 'posthog-node',
85
- packageNameDisplayLabel: 'posthog-node',
86
- packageManager: packageManagerFromInstallStep,
87
- alreadyInstalled: !!packageJson?.dependencies?.['posthog-node'],
88
- forceInstall: options.forceInstall,
89
- askBeforeUpdating: false,
90
- installDir: options.installDir,
91
- integration: constants_1.Integration.nextjs,
92
- });
93
- const relevantFiles = await (0, file_utils_1.getRelevantFilesForIntegration)({
94
- installDir: options.installDir,
95
- integration: constants_1.Integration.nextjs,
96
- });
97
- let installationDocumentation; // Documentation for the installation of the PostHog SDK
98
- if (instrumentationFileAvailable(nextVersion)) {
99
- installationDocumentation = (0, docs_1.getModernNextjsDocs)({
100
- host,
101
- language: typeScriptDetected ? 'typescript' : 'javascript',
102
- });
103
- clack_1.default.log.info(`Reviewing PostHog documentation for Next.js`);
104
- }
105
- else {
106
- const router = await (0, utils_1.getNextJsRouter)(options);
107
- installationDocumentation = getInstallationDocumentation({
108
- router,
109
- host,
110
- language: typeScriptDetected ? 'typescript' : 'javascript',
111
- });
112
- clack_1.default.log.info(`Reviewing PostHog documentation for ${(0, utils_1.getNextJsRouterName)(router)}`);
113
- }
114
- const filesToChange = await (0, file_utils_1.getFilesToChange)({
115
- integration: constants_1.Integration.nextjs,
116
- relevantFiles,
117
- documentation: installationDocumentation,
118
- accessToken,
119
- cloudRegion,
120
- projectId,
121
- });
122
- await (0, file_utils_1.generateFileChangesForIntegration)({
123
- integration: constants_1.Integration.nextjs,
124
- filesToChange,
125
- accessToken,
126
- installDir: options.installDir,
127
- documentation: installationDocumentation,
128
- cloudRegion,
129
- projectId,
130
- });
131
- const packageManagerForOutro = packageManagerFromInstallStep ?? (await (0, clack_utils_1.getPackageManager)(options));
132
- await (0, steps_1.runPrettierStep)({
133
- installDir: options.installDir,
134
- integration: constants_1.Integration.nextjs,
135
- });
136
- const { relativeEnvFilePath, addedEnvVariables } = await (0, steps_1.addOrUpdateEnvironmentVariablesStep)({
137
- variables: {
138
- NEXT_PUBLIC_POSTHOG_KEY: projectApiKey,
139
- NEXT_PUBLIC_POSTHOG_HOST: host,
140
- },
141
- installDir: options.installDir,
142
- integration: constants_1.Integration.nextjs,
143
- });
144
- const uploadedEnvVars = await (0, steps_1.uploadEnvironmentVariablesStep)({
145
- NEXT_PUBLIC_POSTHOG_KEY: projectApiKey,
146
- NEXT_PUBLIC_POSTHOG_HOST: host,
147
- }, {
148
- integration: constants_1.Integration.nextjs,
149
- options,
150
- });
151
- const addedEditorRules = await (0, steps_1.addEditorRulesStep)({
152
- rulesName: 'next-rules.md',
153
- installDir: options.installDir,
154
- integration: constants_1.Integration.nextjs,
155
- });
156
- await (0, steps_1.addMCPServerToClientsStep)({
157
- cloudRegion,
158
- integration: constants_1.Integration.nextjs,
159
- });
160
- const outroMessage = (0, messages_1.getOutroMessage)({
161
- options,
162
- integration: constants_1.Integration.nextjs,
163
- cloudRegion,
164
- addedEditorRules,
165
- packageManager: packageManagerForOutro,
166
- envFileChanged: addedEnvVariables ? relativeEnvFilePath : undefined,
167
- uploadedEnvVars,
168
- });
169
- clack_1.default.outro(outroMessage);
170
- clack_1.default.outro('Want to try our experimental event instrumentation? Run the wizard again with this argument: npx @posthog/wizard@latest event-setup');
171
- await analytics_1.analytics.shutdown('success');
172
- }
173
- function instrumentationFileAvailable(nextVersion) {
174
- const minimumVersion = '15.3.0'; //instrumentation-client.js|ts was introduced in 15.3
175
- if (!nextVersion) {
176
- return false;
177
- }
178
- const coercedNextVersion = semver.coerce(nextVersion);
179
- if (!coercedNextVersion) {
180
- return false; // Unable to parse nextVersion
181
- }
182
- return semver.gte(coercedNextVersion, minimumVersion);
183
- }
184
- function getInstallationDocumentation({ router, host, language, }) {
185
- if (router === utils_1.NextJsRouter.PAGES_ROUTER) {
186
- return (0, docs_1.getNextjsPagesRouterDocs)({ host, language });
187
- }
188
- return (0, docs_1.getNextjsAppRouterDocs)({ host, language });
189
- }
190
- //# sourceMappingURL=nextjs-wizard.js.map