@posthog/wizard 1.14.0 → 1.15.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.
- package/dist/bin.js +17 -4
- package/dist/bin.js.map +1 -1
- package/dist/src/astro/astro-wizard.js +5 -3
- package/dist/src/astro/astro-wizard.js.map +1 -1
- package/dist/src/lib/api.d.ts +75 -0
- package/dist/src/lib/api.js +102 -0
- package/dist/src/lib/api.js.map +1 -0
- package/dist/src/lib/constants.d.ts +4 -0
- package/dist/src/lib/constants.js +5 -1
- package/dist/src/lib/constants.js.map +1 -1
- package/dist/src/mcp.d.ts +4 -1
- package/dist/src/mcp.js +6 -3
- package/dist/src/mcp.js.map +1 -1
- package/dist/src/nextjs/event-setup.js +5 -3
- package/dist/src/nextjs/event-setup.js.map +1 -1
- package/dist/src/nextjs/nextjs-wizard.js +5 -3
- package/dist/src/nextjs/nextjs-wizard.js.map +1 -1
- package/dist/src/react/react-wizard.js +5 -3
- package/dist/src/react/react-wizard.js.map +1 -1
- package/dist/src/react-native/react-native-wizard.js +5 -3
- package/dist/src/react-native/react-native-wizard.js.map +1 -1
- package/dist/src/run.js +7 -1
- package/dist/src/run.js.map +1 -1
- package/dist/src/steps/add-mcp-server-to-clients/MCPClient.d.ts +8 -8
- package/dist/src/steps/add-mcp-server-to-clients/MCPClient.js +16 -13
- package/dist/src/steps/add-mcp-server-to-clients/MCPClient.js.map +1 -1
- package/dist/src/steps/add-mcp-server-to-clients/clients/__tests__/claude.test.js +1 -1
- package/dist/src/steps/add-mcp-server-to-clients/clients/__tests__/claude.test.js.map +1 -1
- package/dist/src/steps/add-mcp-server-to-clients/clients/claude-code.d.ts +3 -3
- package/dist/src/steps/add-mcp-server-to-clients/clients/claude-code.js +12 -8
- package/dist/src/steps/add-mcp-server-to-clients/clients/claude-code.js.map +1 -1
- package/dist/src/steps/add-mcp-server-to-clients/clients/cursor.d.ts +1 -1
- package/dist/src/steps/add-mcp-server-to-clients/clients/cursor.js +2 -2
- package/dist/src/steps/add-mcp-server-to-clients/clients/cursor.js.map +1 -1
- package/dist/src/steps/add-mcp-server-to-clients/defaults.d.ts +1 -1
- package/dist/src/steps/add-mcp-server-to-clients/defaults.js +3 -2
- package/dist/src/steps/add-mcp-server-to-clients/defaults.js.map +1 -1
- package/dist/src/steps/add-mcp-server-to-clients/index.d.ts +7 -5
- package/dist/src/steps/add-mcp-server-to-clients/index.js +16 -14
- package/dist/src/steps/add-mcp-server-to-clients/index.js.map +1 -1
- package/dist/src/svelte/svelte-wizard.js +5 -3
- package/dist/src/svelte/svelte-wizard.js.map +1 -1
- package/dist/src/utils/clack-utils.d.ts +2 -1
- package/dist/src/utils/clack-utils.js +31 -60
- package/dist/src/utils/clack-utils.js.map +1 -1
- package/dist/src/utils/errors.d.ts +3 -0
- package/dist/src/utils/errors.js +11 -0
- package/dist/src/utils/errors.js.map +1 -0
- package/dist/src/utils/file-utils.d.ts +9 -6
- package/dist/src/utils/file-utils.js +9 -6
- package/dist/src/utils/file-utils.js.map +1 -1
- package/dist/src/utils/oauth.d.ts +35 -0
- package/dist/src/utils/oauth.js +212 -0
- package/dist/src/utils/oauth.js.map +1 -0
- package/dist/src/utils/query.d.ts +3 -2
- package/dist/src/utils/query.js +48 -3
- package/dist/src/utils/query.js.map +1 -1
- package/dist/src/utils/types.d.ts +1 -1
- package/dist/src/utils/types.js.map +1 -1
- package/dist/src/utils/urls.d.ts +2 -0
- package/dist/src/utils/urls.js +24 -4
- package/dist/src/utils/urls.js.map +1 -1
- package/package.json +1 -1
package/dist/bin.js
CHANGED
|
@@ -125,15 +125,28 @@ if (process.env.NODE_ENV === 'test') {
|
|
|
125
125
|
.command('mcp <command>', 'MCP server management commands', (yargs) => {
|
|
126
126
|
return yargs
|
|
127
127
|
.command('add', 'Install PostHog MCP server to supported clients', (yargs) => {
|
|
128
|
-
return yargs.options({
|
|
128
|
+
return yargs.options({
|
|
129
|
+
local: {
|
|
130
|
+
default: false,
|
|
131
|
+
describe: 'Add local development MCP server (http://localhost:8787)',
|
|
132
|
+
type: 'boolean',
|
|
133
|
+
},
|
|
134
|
+
});
|
|
129
135
|
}, (argv) => {
|
|
130
136
|
const options = { ...argv };
|
|
131
137
|
void (0, mcp_1.runMCPInstall)(options);
|
|
132
138
|
})
|
|
133
139
|
.command('remove', 'Remove PostHog MCP server from supported clients', (yargs) => {
|
|
134
|
-
return yargs.options({
|
|
135
|
-
|
|
136
|
-
|
|
140
|
+
return yargs.options({
|
|
141
|
+
local: {
|
|
142
|
+
default: false,
|
|
143
|
+
describe: 'Remove local development MCP server (http://localhost:8787)',
|
|
144
|
+
type: 'boolean',
|
|
145
|
+
},
|
|
146
|
+
});
|
|
147
|
+
}, (argv) => {
|
|
148
|
+
const options = { ...argv };
|
|
149
|
+
void (0, mcp_1.runMCPRemove)(options);
|
|
137
150
|
})
|
|
138
151
|
.demandCommand(1, 'You must specify a subcommand (add or remove)')
|
|
139
152
|
.help();
|
package/dist/bin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bin.js","sourceRoot":"","sources":["../bin.ts"],"names":[],"mappings":";;;;;;AACA,mCAAmC;AACnC,iDAA0C;AAE1C,kDAA0B;AAC1B,2CAAwC;AACxC,kDAA0B;AAE1B,MAAM,kBAAkB,GAAG,WAAW,CAAC;AAEvC,iFAAiF;AACjF,+BAA+B;AAC/B,IAAI,CAAC,IAAA,kBAAS,EAAC,OAAO,CAAC,OAAO,EAAE,kBAAkB,CAAC,EAAE,CAAC;IACpD,IAAA,aAAG,EACD,mCAAmC,kBAAkB,2BAA2B,OAAO,CAAC,OAAO,wCAAwC,CACxI,CAAC;IACF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC;AAED,mCAAwD;AAExD,mCAAsC;AACtC,0DAA+D;AAC/D,yDAGiC;AACjC,gDAAwB;AACxB,8DAAsC;AAEtC,IAAI,IAAA,yCAA2B,GAAE,EAAE,CAAC;IAClC,eAAK,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Z,CAAC,CAAC;KACD,IAAI,EAAE;KACN,KAAK,CAAC,MAAM,EAAE,GAAG,CAAC;KAClB,OAAO,EAAE;KACT,KAAK,CAAC,SAAS,EAAE,GAAG,CAAC;KACrB,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,eAAK,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { satisfies } from 'semver';\nimport { red } from './src/utils/logging';\n\nimport yargs from 'yargs';\nimport { hideBin } from 'yargs/helpers';\nimport chalk from 'chalk';\n\nconst NODE_VERSION_RANGE = '>=18.17.0';\n\n// Have to run this above the other imports because they are importing clack that\n// has the problematic imports.\nif (!satisfies(process.version, NODE_VERSION_RANGE)) {\n red(\n `PostHog wizard requires Node.js ${NODE_VERSION_RANGE}. You are using Node.js ${process.version}. Please upgrade your Node.js version.`,\n );\n process.exit(1);\n}\n\nimport { runMCPInstall, runMCPRemove } from './src/mcp';\nimport type { CloudRegion, WizardOptions } from './src/utils/types';\nimport { runWizard } from './src/run';\nimport { runEventSetupWizard } from './src/nextjs/event-setup';\nimport {\n readEnvironment,\n isNonInteractiveEnvironment,\n} from './src/utils/environment';\nimport path from 'path';\nimport clack from './src/utils/clack';\n\nif (isNonInteractiveEnvironment()) {\n clack.intro(chalk.inverse(`PostHog Wizard`));\n\n clack.log.error(\n 'This installer requires an interactive terminal (TTY) to run.\\n' +\n 'It appears you are running in a non-interactive environment.\\n' +\n 'Please run the wizard in an interactive terminal.',\n );\n process.exit(1);\n}\n\nif (process.env.NODE_ENV === 'test') {\n void (async () => {\n try {\n const { server } = await import('./e2e-tests/mocks/server.js');\n server.listen({\n onUnhandledRequest: 'bypass',\n });\n } catch (error) {\n // Mock server import failed - this can happen during non-E2E tests\n }\n })();\n}\n\nyargs(hideBin(process.argv))\n .env('POSTHOG_WIZARD')\n // global options\n .options({\n debug: {\n default: false,\n describe: 'Enable verbose logging\\nenv: POSTHOG_WIZARD_DEBUG',\n type: 'boolean',\n },\n region: {\n describe: 'PostHog cloud region\\nenv: POSTHOG_WIZARD_REGION',\n choices: ['us', 'eu'],\n type: 'string',\n },\n default: {\n default: true,\n describe:\n 'Use default options for all prompts\\nenv: POSTHOG_WIZARD_DEFAULT',\n type: 'boolean',\n },\n signup: {\n default: false,\n describe:\n 'Create a new PostHog account during setup\\nenv: POSTHOG_WIZARD_SIGNUP',\n type: 'boolean',\n },\n })\n .command(\n ['$0'],\n 'Run the PostHog setup wizard',\n (yargs) => {\n return yargs.options({\n 'force-install': {\n default: false,\n describe:\n 'Force install packages even if peer dependency checks fail\\nenv: POSTHOG_WIZARD_FORCE_INSTALL',\n type: 'boolean',\n },\n 'install-dir': {\n describe:\n 'Directory to install PostHog in\\nenv: POSTHOG_WIZARD_INSTALL_DIR',\n type: 'string',\n },\n integration: {\n describe: 'Integration to set up',\n choices: ['nextjs', 'astro', 'react', 'svelte', 'react-native'],\n type: 'string',\n },\n });\n },\n (argv) => {\n const options = { ...argv };\n void runWizard(options as unknown as WizardOptions);\n },\n )\n .command(\n 'event-setup',\n 'Run the event setup wizard',\n (yargs) => {\n return yargs.options({\n 'install-dir': {\n describe:\n 'Directory to run the wizard in\\nenv: POSTHOG_WIZARD_INSTALL_DIR',\n type: 'string',\n },\n });\n },\n (argv) => {\n const finalArgs = {\n ...argv,\n ...readEnvironment(),\n } as any;\n\n let resolvedInstallDir: string;\n if (finalArgs.installDir) {\n if (path.isAbsolute(finalArgs.installDir)) {\n resolvedInstallDir = finalArgs.installDir;\n } else {\n resolvedInstallDir = path.join(process.cwd(), finalArgs.installDir);\n }\n } else {\n resolvedInstallDir = process.cwd();\n }\n\n const wizardOptions: WizardOptions = {\n debug: finalArgs.debug ?? false,\n installDir: resolvedInstallDir,\n cloudRegion: finalArgs.region as CloudRegion | undefined,\n default: finalArgs.default ?? false,\n signup: finalArgs.signup ?? false,\n forceInstall: false,\n };\n\n void runEventSetupWizard(wizardOptions);\n },\n )\n .command('mcp <command>', 'MCP server management commands', (yargs) => {\n return yargs\n .command(\n 'add',\n 'Install PostHog MCP server to supported clients',\n (yargs) => {\n return yargs.options({\n local: {\n default: false,\n describe:\n 'Add local development MCP server (http://localhost:8787)',\n type: 'boolean',\n },\n });\n },\n (argv) => {\n const options = { ...argv };\n void runMCPInstall(\n options as unknown as {\n signup: boolean;\n region?: CloudRegion;\n local?: boolean;\n },\n );\n },\n )\n .command(\n 'remove',\n 'Remove PostHog MCP server from supported clients',\n (yargs) => {\n return yargs.options({\n local: {\n default: false,\n describe:\n 'Remove local development MCP server (http://localhost:8787)',\n type: 'boolean',\n },\n });\n },\n (argv) => {\n const options = { ...argv };\n void runMCPRemove(options as { local?: boolean });\n },\n )\n .demandCommand(1, 'You must specify a subcommand (add or remove)')\n .help();\n })\n .help()\n .alias('help', 'h')\n .version()\n .alias('version', 'v')\n .wrap(process.stdout.isTTY ? yargs.terminalWidth() : 80).argv;\n"]}
|
|
@@ -31,7 +31,7 @@ async function runAstroWizard(options) {
|
|
|
31
31
|
if (astroVersion) {
|
|
32
32
|
analytics_1.analytics.setTag('astro-version', astroVersion);
|
|
33
33
|
}
|
|
34
|
-
const { projectApiKey,
|
|
34
|
+
const { projectApiKey, accessToken, host, projectId } = await (0, clack_utils_1.getOrAskForProjectData)({
|
|
35
35
|
...options,
|
|
36
36
|
cloudRegion,
|
|
37
37
|
});
|
|
@@ -49,16 +49,18 @@ async function runAstroWizard(options) {
|
|
|
49
49
|
integration: constants_1.Integration.astro,
|
|
50
50
|
relevantFiles,
|
|
51
51
|
documentation: installationDocumentation,
|
|
52
|
-
|
|
52
|
+
accessToken,
|
|
53
53
|
cloudRegion,
|
|
54
|
+
projectId,
|
|
54
55
|
});
|
|
55
56
|
await (0, file_utils_1.generateFileChangesForIntegration)({
|
|
56
57
|
integration: constants_1.Integration.astro,
|
|
57
58
|
filesToChange,
|
|
58
|
-
|
|
59
|
+
accessToken,
|
|
59
60
|
installDir: options.installDir,
|
|
60
61
|
documentation: installationDocumentation,
|
|
61
62
|
cloudRegion,
|
|
63
|
+
projectId,
|
|
62
64
|
});
|
|
63
65
|
await (0, steps_1.runPrettierStep)({
|
|
64
66
|
installDir: options.installDir,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"astro-wizard.js","sourceRoot":"","sources":["../../../src/astro/astro-wizard.ts"],"names":[],"mappings":";AAAA,8BAA8B;;;;;AA8B9B,
|
|
1
|
+
{"version":3,"file":"astro-wizard.js","sourceRoot":"","sources":["../../../src/astro/astro-wizard.ts"],"names":[],"mappings":";AAAA,8BAA8B;;;;;AA8B9B,wCA8FC;AA1HD,sDAQ8B;AAC9B,wDAA0D;AAC1D,2DAAmC;AACnC,gDAA+C;AAC/C,iCAA+C;AAC/C,kDAA+C;AAC/C,oDAI6B;AAE7B,sDAAyD;AACzD,8CAAkD;AAClD,oCAIkB;AAEX,KAAK,UAAU,cAAc,CAAC,OAAsB;IACzD,IAAA,0BAAY,EAAC;QACX,UAAU,EAAE,sBAAsB;KACnC,CAAC,CAAC;IAEH,MAAM,SAAS,GAAG,MAAM,IAAA,6BAAe,EAAC,OAAO,CAAC,CAAC;IAEjD,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,MAAM,IAAA,mBAAK,EACT,kJAAkJ,EAClJ,CAAC,CACF,CAAC;IACJ,CAAC;IAED,MAAM,WAAW,GAAG,OAAO,CAAC,WAAW,IAAI,CAAC,MAAM,IAAA,+BAAiB,GAAE,CAAC,CAAC;IAEvE,MAAM,IAAA,+CAAiC,EAAC,OAAO,CAAC,CAAC;IAEjD,MAAM,WAAW,GAAG,MAAM,IAAA,+BAAiB,EAAC,OAAO,CAAC,CAAC;IAErD,MAAM,IAAA,sCAAwB,EAAC,WAAW,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAE9D,MAAM,YAAY,GAAG,IAAA,gCAAiB,EAAC,OAAO,EAAE,WAAW,CAAC,CAAC;IAE7D,IAAI,YAA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W,CAAC,KAAK;KAC/B,CAAC,CAAC;IAEH,MAAM,IAAA,iCAAyB,EAAC;QAC9B,WAAW;QACX,WAAW,EAAE,uBAAW,CAAC,KAAK;KAC/B,CAAC,CAAC;IAEH,MAAM,YAAY,GAAG,IAAA,0BAAe,EAAC;QACnC,OAAO;QACP,WAAW,EAAE,uBAAW,CAAC,KAAK;QAC9B,WAAW;QACX,gBAAgB;QAChB,eAAe,EAAE,EAAE;KACpB,CAAC,CAAC;IAEH,eAAK,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IAE1B,MAAM,qBAAS,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;AACtC,CAAC","sourcesContent":["/* eslint-disable max-lines */\n\nimport {\n abort,\n askForAIConsent,\n confirmContinueIfNoOrDirtyGitRepo,\n ensurePackageIsInstalled,\n getOrAskForProjectData,\n getPackageDotJson,\n printWelcome,\n} from '../utils/clack-utils';\nimport { getPackageVersion } from '../utils/package-json';\nimport clack from '../utils/clack';\nimport { Integration } from '../lib/constants';\nimport { getAstroDocumentation } from './docs';\nimport { analytics } from '../utils/analytics';\nimport {\n generateFileChangesForIntegration,\n getFilesToChange,\n getRelevantFilesForIntegration,\n} from '../utils/file-utils';\nimport type { WizardOptions } from '../utils/types';\nimport { askForCloudRegion } from '../utils/clack-utils';\nimport { getOutroMessage } from '../lib/messages';\nimport {\n addEditorRulesStep,\n addMCPServerToClientsStep,\n runPrettierStep,\n} from '../steps';\n\nexport async function runAstroWizard(options: WizardOptions): Promise<void> {\n printWelcome({\n wizardName: 'PostHog Astro wizard',\n });\n\n const aiConsent = await askForAIConsent(options);\n\n if (!aiConsent) {\n await abort(\n 'The Astro wizard requires AI to get setup right now. Please view the docs to setup Astro manually instead: https://posthog.com/docs/libraries/js',\n 0,\n );\n }\n\n const cloudRegion = options.cloudRegion ?? (await askForCloudRegion());\n\n await confirmContinueIfNoOrDirtyGitRepo(options);\n\n const packageJson = await getPackageDotJson(options);\n\n await ensurePackageIsInstalled(packageJson, 'astro', 'Astro');\n\n const astroVersion = getPackageVersion('astro', packageJson);\n\n if (astroVersion) {\n analytics.setTag('astro-version', astroVersion);\n }\n\n const { projectApiKey, accessToken, host, projectId } =\n await getOrAskForProjectData({\n ...options,\n cloudRegion,\n });\n\n clack.log.info('Heading to include the PostHogSnippet in your Astro project');\n\n const relevantFiles = await getRelevantFilesForIntegration({\n installDir: options.installDir,\n integration: Integration.astro,\n });\n\n const installationDocumentation = getAstroDocumentation({\n projectApiKey,\n host,\n });\n\n clack.log.info('Reviewing PostHog documentation for Astro');\n\n const filesToChange = await getFilesToChange({\n integration: Integration.astro,\n relevantFiles,\n documentation: installationDocumentation,\n accessToken,\n cloudRegion,\n projectId,\n });\n\n await generateFileChangesForIntegration({\n integration: Integration.astro,\n filesToChange,\n accessToken,\n installDir: options.installDir,\n documentation: installationDocumentation,\n cloudRegion,\n projectId,\n });\n\n await runPrettierStep({\n installDir: options.installDir,\n integration: Integration.astro,\n });\n\n const addedEditorRules = await addEditorRulesStep({\n installDir: options.installDir,\n rulesName: 'astro-rules.md',\n integration: Integration.astro,\n });\n\n await addMCPServerToClientsStep({\n cloudRegion,\n integration: Integration.astro,\n });\n\n const outroMessage = getOutroMessage({\n options,\n integration: Integration.astro,\n cloudRegion,\n addedEditorRules,\n uploadedEnvVars: [],\n });\n\n clack.outro(outroMessage);\n\n await analytics.shutdown('success');\n}\n"]}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export declare const ApiUserSchema: z.ZodObject<{
|
|
3
|
+
distinct_id: z.ZodString;
|
|
4
|
+
organizations: z.ZodArray<z.ZodObject<{
|
|
5
|
+
id: z.ZodString;
|
|
6
|
+
}, "strip", z.ZodTypeAny, {
|
|
7
|
+
id: string;
|
|
8
|
+
}, {
|
|
9
|
+
id: string;
|
|
10
|
+
}>, "many">;
|
|
11
|
+
team: z.ZodObject<{
|
|
12
|
+
id: z.ZodNumber;
|
|
13
|
+
organization: z.ZodString;
|
|
14
|
+
}, "strip", z.ZodTypeAny, {
|
|
15
|
+
id: number;
|
|
16
|
+
organization: string;
|
|
17
|
+
}, {
|
|
18
|
+
id: number;
|
|
19
|
+
organization: string;
|
|
20
|
+
}>;
|
|
21
|
+
organization: z.ZodObject<{
|
|
22
|
+
id: z.ZodString;
|
|
23
|
+
}, "strip", z.ZodTypeAny, {
|
|
24
|
+
id: string;
|
|
25
|
+
}, {
|
|
26
|
+
id: string;
|
|
27
|
+
}>;
|
|
28
|
+
}, "strip", z.ZodTypeAny, {
|
|
29
|
+
team: {
|
|
30
|
+
id: number;
|
|
31
|
+
organization: string;
|
|
32
|
+
};
|
|
33
|
+
distinct_id: string;
|
|
34
|
+
organizations: {
|
|
35
|
+
id: string;
|
|
36
|
+
}[];
|
|
37
|
+
organization: {
|
|
38
|
+
id: string;
|
|
39
|
+
};
|
|
40
|
+
}, {
|
|
41
|
+
team: {
|
|
42
|
+
id: number;
|
|
43
|
+
organization: string;
|
|
44
|
+
};
|
|
45
|
+
distinct_id: string;
|
|
46
|
+
organizations: {
|
|
47
|
+
id: string;
|
|
48
|
+
}[];
|
|
49
|
+
organization: {
|
|
50
|
+
id: string;
|
|
51
|
+
};
|
|
52
|
+
}>;
|
|
53
|
+
export declare const ApiProjectSchema: z.ZodObject<{
|
|
54
|
+
id: z.ZodNumber;
|
|
55
|
+
uuid: z.ZodString;
|
|
56
|
+
organization: z.ZodString;
|
|
57
|
+
api_token: z.ZodString;
|
|
58
|
+
name: z.ZodString;
|
|
59
|
+
}, "strip", z.ZodTypeAny, {
|
|
60
|
+
id: number;
|
|
61
|
+
organization: string;
|
|
62
|
+
uuid: string;
|
|
63
|
+
api_token: string;
|
|
64
|
+
name: string;
|
|
65
|
+
}, {
|
|
66
|
+
id: number;
|
|
67
|
+
organization: string;
|
|
68
|
+
uuid: string;
|
|
69
|
+
api_token: string;
|
|
70
|
+
name: string;
|
|
71
|
+
}>;
|
|
72
|
+
export type ApiUser = z.infer<typeof ApiUserSchema>;
|
|
73
|
+
export type ApiProject = z.infer<typeof ApiProjectSchema>;
|
|
74
|
+
export declare function fetchUserData(accessToken: string, baseUrl: string): Promise<ApiUser>;
|
|
75
|
+
export declare function fetchProjectData(accessToken: string, projectId: number, baseUrl: string): Promise<ApiProject>;
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.ApiProjectSchema = exports.ApiUserSchema = void 0;
|
|
7
|
+
exports.fetchUserData = fetchUserData;
|
|
8
|
+
exports.fetchProjectData = fetchProjectData;
|
|
9
|
+
const axios_1 = __importDefault(require("axios"));
|
|
10
|
+
const zod_1 = require("zod");
|
|
11
|
+
const analytics_1 = require("../utils/analytics");
|
|
12
|
+
exports.ApiUserSchema = zod_1.z.object({
|
|
13
|
+
distinct_id: zod_1.z.string(),
|
|
14
|
+
organizations: zod_1.z.array(zod_1.z.object({
|
|
15
|
+
id: zod_1.z.string().uuid(),
|
|
16
|
+
})),
|
|
17
|
+
team: zod_1.z.object({
|
|
18
|
+
id: zod_1.z.number(),
|
|
19
|
+
organization: zod_1.z.string().uuid(),
|
|
20
|
+
}),
|
|
21
|
+
organization: zod_1.z.object({
|
|
22
|
+
id: zod_1.z.string().uuid(),
|
|
23
|
+
}),
|
|
24
|
+
});
|
|
25
|
+
exports.ApiProjectSchema = zod_1.z.object({
|
|
26
|
+
id: zod_1.z.number(),
|
|
27
|
+
uuid: zod_1.z.string().uuid(),
|
|
28
|
+
organization: zod_1.z.string().uuid(),
|
|
29
|
+
api_token: zod_1.z.string(),
|
|
30
|
+
name: zod_1.z.string(),
|
|
31
|
+
});
|
|
32
|
+
class ApiError extends Error {
|
|
33
|
+
statusCode;
|
|
34
|
+
endpoint;
|
|
35
|
+
constructor(message, statusCode, endpoint) {
|
|
36
|
+
super(message);
|
|
37
|
+
this.statusCode = statusCode;
|
|
38
|
+
this.endpoint = endpoint;
|
|
39
|
+
this.name = 'ApiError';
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
async function fetchUserData(accessToken, baseUrl) {
|
|
43
|
+
try {
|
|
44
|
+
const response = await axios_1.default.get(`${baseUrl}/api/users/@me/`, {
|
|
45
|
+
headers: {
|
|
46
|
+
Authorization: `Bearer ${accessToken}`,
|
|
47
|
+
},
|
|
48
|
+
});
|
|
49
|
+
return exports.ApiUserSchema.parse(response.data);
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
const apiError = handleApiError(error, 'fetch user data');
|
|
53
|
+
analytics_1.analytics.captureException(apiError, {
|
|
54
|
+
endpoint: '/api/users/@me/',
|
|
55
|
+
baseUrl,
|
|
56
|
+
});
|
|
57
|
+
throw apiError;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
async function fetchProjectData(accessToken, projectId, baseUrl) {
|
|
61
|
+
try {
|
|
62
|
+
const response = await axios_1.default.get(`${baseUrl}/api/projects/${projectId}/`, {
|
|
63
|
+
headers: {
|
|
64
|
+
Authorization: `Bearer ${accessToken}`,
|
|
65
|
+
},
|
|
66
|
+
});
|
|
67
|
+
return exports.ApiProjectSchema.parse(response.data);
|
|
68
|
+
}
|
|
69
|
+
catch (error) {
|
|
70
|
+
const apiError = handleApiError(error, 'fetch project data');
|
|
71
|
+
analytics_1.analytics.captureException(apiError, {
|
|
72
|
+
endpoint: `/api/projects/${projectId}/`,
|
|
73
|
+
baseUrl,
|
|
74
|
+
projectId,
|
|
75
|
+
});
|
|
76
|
+
throw apiError;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
function handleApiError(error, operation) {
|
|
80
|
+
if (axios_1.default.isAxiosError(error)) {
|
|
81
|
+
const axiosError = error;
|
|
82
|
+
const status = axiosError.response?.status;
|
|
83
|
+
const detail = axiosError.response?.data?.detail;
|
|
84
|
+
const endpoint = axiosError.config?.url;
|
|
85
|
+
if (status === 401) {
|
|
86
|
+
return new ApiError(`Authentication failed while trying to ${operation}`, status, endpoint);
|
|
87
|
+
}
|
|
88
|
+
if (status === 403) {
|
|
89
|
+
return new ApiError(`Access denied while trying to ${operation}`, status, endpoint);
|
|
90
|
+
}
|
|
91
|
+
if (status === 404) {
|
|
92
|
+
return new ApiError(`Resource not found while trying to ${operation}`, status, endpoint);
|
|
93
|
+
}
|
|
94
|
+
const message = detail || `Failed to ${operation}`;
|
|
95
|
+
return new ApiError(message, status, endpoint);
|
|
96
|
+
}
|
|
97
|
+
if (error instanceof zod_1.z.ZodError) {
|
|
98
|
+
return new ApiError(`Invalid response format while trying to ${operation}`);
|
|
99
|
+
}
|
|
100
|
+
return new ApiError(`Unexpected error while trying to ${operation}: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
101
|
+
}
|
|
102
|
+
//# sourceMappingURL=api.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"api.js","sourceRoot":"","sources":["../../../src/lib/api.ts"],"names":[],"mappings":";;;;;;AA0CA,sCAoBC;AAED,4CAsBC;AAtFD,kDAA0C;AAC1C,6BAAwB;AACxB,kDAA+C;AAElC,QAAA,aAAa,GAAG,OAAC,CAAC,MAAM,CAAC;IACpC,WAAW,EAAE,OAAC,CAAC,MAAM,EAAE;IACvB,aAAa,EAAE,OAAC,CAAC,KAAK,CACpB,OAAC,CAAC,MAAM,CAAC;QACP,EAAE,EAAE,OAAC,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE;KACtB,CAAC,CACH;IACD,IAAI,EAAE,OAAC,CAAC,MAAM,CAAC;QACb,EAAE,EAAE,OAAC,CAAC,MAAM,EAAE;QACd,YAAY,EAAE,OAAC,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE;KAChC,CAAC;IACF,YAAY,EAAE,OAAC,CAAC,MAAM,CAAC;QACrB,EAAE,EAAE,OAAC,CAAC,MAAM,EA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,CACjB,sCAAsC,SAAS,EAAE,EACjD,MAAM,EACN,QAAQ,CACT,CAAC;QACJ,CAAC;QAED,MAAM,OAAO,GAAG,MAAM,IAAI,aAAa,SAAS,EAAE,CAAC;QACnD,OAAO,IAAI,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC;IACjD,CAAC;IAED,IAAI,KAAK,YAAY,OAAC,CAAC,QAAQ,EAAE,CAAC;QAChC,OAAO,IAAI,QAAQ,CAAC,2CAA2C,SAAS,EAAE,CAAC,CAAC;IAC9E,CAAC;IAED,OAAO,IAAI,QAAQ,CACjB,oCAAoC,SAAS,KAC3C,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,eAC3C,EAAE,CACH,CAAC;AACJ,CAAC","sourcesContent":["import axios, { AxiosError } from 'axios';\nimport { z } from 'zod';\nimport { analytics } from '../utils/analytics';\n\nexport const ApiUserSchema = z.object({\n distinct_id: z.string(),\n organizations: z.array(\n z.object({\n id: z.string().uuid(),\n }),\n ),\n team: z.object({\n id: z.number(),\n organization: z.string().uuid(),\n }),\n organization: z.object({\n id: z.string().uuid(),\n }),\n});\n\nexport const ApiProjectSchema = z.object({\n id: z.number(),\n uuid: z.string().uuid(),\n organization: z.string().uuid(),\n api_token: z.string(),\n name: z.string(),\n});\n\nexport type ApiUser = z.infer<typeof ApiUserSchema>;\nexport type ApiProject = z.infer<typeof ApiProjectSchema>;\n\nclass ApiError extends Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n public readonly endpoint?: string,\n ) {\n super(message);\n this.name = 'ApiError';\n }\n}\n\nexport async function fetchUserData(\n accessToken: string,\n baseUrl: string,\n): Promise<ApiUser> {\n try {\n const response = await axios.get(`${baseUrl}/api/users/@me/`, {\n headers: {\n Authorization: `Bearer ${accessToken}`,\n },\n });\n\n return ApiUserSchema.parse(response.data);\n } catch (error) {\n const apiError = handleApiError(error, 'fetch user data');\n analytics.captureException(apiError, {\n endpoint: '/api/users/@me/',\n baseUrl,\n });\n throw apiError;\n }\n}\n\nexport async function fetchProjectData(\n accessToken: string,\n projectId: number,\n baseUrl: string,\n): Promise<ApiProject> {\n try {\n const response = await axios.get(`${baseUrl}/api/projects/${projectId}/`, {\n headers: {\n Authorization: `Bearer ${accessToken}`,\n },\n });\n\n return ApiProjectSchema.parse(response.data);\n } catch (error) {\n const apiError = handleApiError(error, 'fetch project data');\n analytics.captureException(apiError, {\n endpoint: `/api/projects/${projectId}/`,\n baseUrl,\n projectId,\n });\n throw apiError;\n }\n}\n\nfunction handleApiError(error: unknown, operation: string): ApiError {\n if (axios.isAxiosError(error)) {\n const axiosError = error as AxiosError<{ detail?: string }>;\n const status = axiosError.response?.status;\n const detail = axiosError.response?.data?.detail;\n const endpoint = axiosError.config?.url;\n\n if (status === 401) {\n return new ApiError(\n `Authentication failed while trying to ${operation}`,\n status,\n endpoint,\n );\n }\n\n if (status === 403) {\n return new ApiError(\n `Access denied while trying to ${operation}`,\n status,\n endpoint,\n );\n }\n\n if (status === 404) {\n return new ApiError(\n `Resource not found while trying to ${operation}`,\n status,\n endpoint,\n );\n }\n\n const message = detail || `Failed to ${operation}`;\n return new ApiError(message, status, endpoint);\n }\n\n if (error instanceof z.ZodError) {\n return new ApiError(`Invalid response format while trying to ${operation}`);\n }\n\n return new ApiError(\n `Unexpected error while trying to ${operation}: ${\n error instanceof Error ? error.message : 'Unknown error'\n }`,\n );\n}\n"]}
|
|
@@ -23,4 +23,8 @@ export declare const DEFAULT_HOST_URL: string;
|
|
|
23
23
|
export declare const ANALYTICS_POSTHOG_PUBLIC_PROJECT_WRITE_KEY = "sTMFPsFhdP1Ssg";
|
|
24
24
|
export declare const ANALYTICS_HOST_URL = "https://internal-j.posthog.com";
|
|
25
25
|
export declare const DUMMY_PROJECT_API_KEY = "_YOUR_POSTHOG_PROJECT_API_KEY_";
|
|
26
|
+
export declare const POSTHOG_US_CLIENT_ID = "c4Rdw8DIxgtQfA80IiSnGKlNX8QN00cFWF00QQhM";
|
|
27
|
+
export declare const POSTHOG_EU_CLIENT_ID = "bx2C5sZRN03TkdjraCcetvQFPGH6N2Y9vRLkcKEy";
|
|
28
|
+
export declare const POSTHOG_DEV_CLIENT_ID = "DC5uRLVbGI02YQ82grxgnK6Qn12SXWpCqdPb60oZ";
|
|
29
|
+
export declare const OAUTH_PORT = 8239;
|
|
26
30
|
export {};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.DUMMY_PROJECT_API_KEY = exports.ANALYTICS_HOST_URL = exports.ANALYTICS_POSTHOG_PUBLIC_PROJECT_WRITE_KEY = exports.DEFAULT_HOST_URL = exports.ISSUES_URL = exports.DEFAULT_URL = exports.DEBUG = exports.IS_DEV = exports.Integration = void 0;
|
|
3
|
+
exports.OAUTH_PORT = exports.POSTHOG_DEV_CLIENT_ID = exports.POSTHOG_EU_CLIENT_ID = exports.POSTHOG_US_CLIENT_ID = exports.DUMMY_PROJECT_API_KEY = exports.ANALYTICS_HOST_URL = exports.ANALYTICS_POSTHOG_PUBLIC_PROJECT_WRITE_KEY = exports.DEFAULT_HOST_URL = exports.ISSUES_URL = exports.DEFAULT_URL = exports.DEBUG = exports.IS_DEV = exports.Integration = void 0;
|
|
4
4
|
exports.getIntegrationDescription = getIntegrationDescription;
|
|
5
5
|
exports.getIntegrationChoices = getIntegrationChoices;
|
|
6
6
|
var Integration;
|
|
@@ -45,4 +45,8 @@ exports.DEFAULT_HOST_URL = exports.IS_DEV
|
|
|
45
45
|
exports.ANALYTICS_POSTHOG_PUBLIC_PROJECT_WRITE_KEY = 'sTMFPsFhdP1Ssg';
|
|
46
46
|
exports.ANALYTICS_HOST_URL = 'https://internal-j.posthog.com';
|
|
47
47
|
exports.DUMMY_PROJECT_API_KEY = '_YOUR_POSTHOG_PROJECT_API_KEY_';
|
|
48
|
+
exports.POSTHOG_US_CLIENT_ID = 'c4Rdw8DIxgtQfA80IiSnGKlNX8QN00cFWF00QQhM';
|
|
49
|
+
exports.POSTHOG_EU_CLIENT_ID = 'bx2C5sZRN03TkdjraCcetvQFPGH6N2Y9vRLkcKEy';
|
|
50
|
+
exports.POSTHOG_DEV_CLIENT_ID = 'DC5uRLVbGI02YQ82grxgnK6Qn12SXWpCqdPb60oZ';
|
|
51
|
+
exports.OAUTH_PORT = 8239;
|
|
48
52
|
//# sourceMappingURL=constants.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":";;;AAQA,8DAeC;AAOD,sDAKC;AAnCD,IAAY,WAMX;AAND,WAAY,WAAW;IACrB,gCAAiB,CAAA;IACjB,8BAAe,CAAA;IACf,gCAAiB,CAAA;IACjB,2CAA4B,CAAA;IAC5B,8BAAe,CAAA;AACjB,CAAC,EANW,WAAW,2BAAX,WAAW,QAMtB;AAED,SAAgB,yBAAyB,CAAC,IAAY;IACpD,QAAQ,IAAI,EAAE,CAAC;QACb,KAAK,WAAW,CAAC,MAAM;YACrB,OAAO,SAAS,CAAC;QACnB,KAAK,WAAW,CAAC,KAAK;YACpB,OAAO,OAAO,CAAC;QACjB,KAAK,WAAW,CAAC,WAAW;YAC1B,OAAO,cAAc,CAAC;QACxB,KAAK,WAAW,CAAC,MAAM;YACrB,OAAO,QAAQ,CAAC;QAClB,KAAK,WAAW,CAAC,KAAK;YACpB,OAAO,OAAO,CAAC;QACjB;YACE,MAAM,IAAI,KAAK,CAAC,uBAAuB,IAAI,EAAE,CAAC,CAAC;IACnD,CAAC;AACH,CAAC;AAOD,SAAgB,qBAAqB;IACnC,OAAO,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,GAAG,CAAC,CAAC,IAAY,EAAE,EAAE,CAAC,CAAC;QACrD,IAAI,EAAE,yBAAyB,CAAC,IAAI,CAAC;QACrC,KAAK,EAAE,IAAI;KACZ,CAAC,CAAC,CAAC;AACN,CAAC;AAOY,QAAA,MAAM,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC,QAAQ,CACpD,OAAO,CAAC,GAAG,CAAC,QAAQ,IAAI,EAAE,CAC3B,CAAC;AAEW,QAAA,KAAK,GAAG,KAAK,CAAC;AAEd,QAAA,WAAW,GAAG,cAAM;IAC/B,CAAC,CAAC,uBAAuB;IACzB,CAAC,CAAC,wBAAwB,CAAC;AAChB,QAAA,UAAU,GAAG,0CAA0C,CAAC;AACxD,QAAA,gBAAgB,GAAG,cAAM;IACpC,CAAC,CAAC,uBAAuB;IACzB,CAAC,CAAC,0BAA0B,CAAC;AAClB,QAAA,0CAA0C,GAAG,gBAAgB,CAAC;AAC9D,QAAA,kBAAkB,GAAG,gCAAgC,CAAC;AACtD,QAAA,qBAAqB,GAAG,gCAAgC,CAAC","sourcesContent":["export enum Integration {\n nextjs = 'nextjs',\n react = 'react',\n svelte = 'svelte',\n reactNative = 'react-native',\n astro = 'astro',\n}\n\nexport function getIntegrationDescription(type: string): string {\n switch (type) {\n case Integration.nextjs:\n return 'Next.js';\n case Integration.react:\n return 'React';\n case Integration.reactNative:\n return 'React Native';\n case Integration.svelte:\n return 'Svelte';\n case Integration.astro:\n return 'Astro';\n default:\n throw new Error(`Unknown integration ${type}`);\n }\n}\n\ntype IntegrationChoice = {\n name: string;\n value: string;\n};\n\nexport function getIntegrationChoices(): IntegrationChoice[] {\n return Object.keys(Integration).map((type: string) => ({\n name: getIntegrationDescription(type),\n value: type,\n }));\n}\n\nexport interface Args {\n debug: boolean;\n integration: Integration;\n}\n\nexport const IS_DEV = ['test', 'development'].includes(\n process.env.NODE_ENV ?? '',\n);\n\nexport const DEBUG = false;\n\nexport const DEFAULT_URL = IS_DEV\n ? 'http://localhost:8010'\n : 'https://us.posthog.com';\nexport const ISSUES_URL = 'https://github.com/posthog/wizard/issues';\nexport const DEFAULT_HOST_URL = IS_DEV\n ? 'http://localhost:8010'\n : 'https://us.i.posthog.com';\nexport const ANALYTICS_POSTHOG_PUBLIC_PROJECT_WRITE_KEY = 'sTMFPsFhdP1Ssg';\nexport const ANALYTICS_HOST_URL = 'https://internal-j.posthog.com';\nexport const DUMMY_PROJECT_API_KEY = '_YOUR_POSTHOG_PROJECT_API_KEY_';\n"]}
|
|
1
|
+
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":";;;AAQA,8DAeC;AAOD,sDAKC;AAnCD,IAAY,WAMX;AAND,WAAY,WAAW;IACrB,gCAAiB,CAAA;IACjB,8BAAe,CAAA;IACf,gCAAiB,CAAA;IACjB,2CAA4B,CAAA;IAC5B,8BAAe,CAAA;AACjB,CAAC,EANW,WAAW,2BAAX,WAAW,QAMtB;AAED,SAAgB,yBAAyB,CAAC,IAAY;IACpD,QAAQ,IAAI,EAAE,CAAC;QACb,KAAK,WAAW,CAAC,MAAM;YACrB,OAAO,SAAS,CAAC;QACnB,KAAK,WAAW,CAAC,KAAK;YACpB,OAAO,OAAO,CAAC;QACjB,KAAK,WAAW,CAAC,WAAW;YAC1B,OAAO,cAAc,CAAC;QACxB,KAAK,WAAW,CAAC,MAAM;YACrB,OAAO,QAAQ,CAAC;QAClB,KAAK,WAAW,CAAC,KAAK;YACpB,OAAO,OAAO,CAAC;QACjB;YACE,MAAM,IAAI,KAAK,CAAC,uBAAuB,IAAI,EAAE,CAAC,CAAC;IACnD,CAAC;AACH,CAAC;AAOD,SAAgB,qBAAqB;IACnC,OAAO,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,GAAG,CAAC,CAAC,IAAY,EAAE,EAAE,CAAC,CAAC;QACrD,IAAI,EAAE,yBAAyB,CAAC,IAAI,CAAC;QACrC,KAAK,EAAE,IAAI;KACZ,CAAC,CAAC,CAAC;AACN,CAAC;AAOY,QAAA,MAAM,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC,QAAQ,CACpD,OAAO,CAAC,GAAG,CAAC,QAAQ,IAAI,EAAE,CAC3B,CAAC;AAEW,QAAA,KAAK,GAAG,KAAK,CAAC;AAEd,QAAA,WAAW,GAAG,cAAM;IAC/B,CAAC,CAAC,uBAAuB;IACzB,CAAC,CAAC,wBAAwB,CAAC;AAChB,QAAA,UAAU,GAAG,0CAA0C,CAAC;AACxD,QAAA,gBAAgB,GAAG,cAAM;IACpC,CAAC,CAAC,uBAAuB;IACzB,CAAC,CAAC,0BAA0B,CAAC;AAClB,QAAA,0CAA0C,GAAG,gBAAgB,CAAC;AAC9D,QAAA,kBAAkB,GAAG,gCAAgC,CAAC;AACtD,QAAA,qBAAqB,GAAG,gCAAgC,CAAC;AAEzD,QAAA,oBAAoB,GAAG,0CAA0C,CAAC;AAClE,QAAA,oBAAoB,GAAG,0CAA0C,CAAC;AAClE,QAAA,qBAAqB,GAAG,0CAA0C,CAAC;AACnE,QAAA,UAAU,GAAG,IAAI,CAAC","sourcesContent":["export enum Integration {\n nextjs = 'nextjs',\n react = 'react',\n svelte = 'svelte',\n reactNative = 'react-native',\n astro = 'astro',\n}\n\nexport function getIntegrationDescription(type: string): string {\n switch (type) {\n case Integration.nextjs:\n return 'Next.js';\n case Integration.react:\n return 'React';\n case Integration.reactNative:\n return 'React Native';\n case Integration.svelte:\n return 'Svelte';\n case Integration.astro:\n return 'Astro';\n default:\n throw new Error(`Unknown integration ${type}`);\n }\n}\n\ntype IntegrationChoice = {\n name: string;\n value: string;\n};\n\nexport function getIntegrationChoices(): IntegrationChoice[] {\n return Object.keys(Integration).map((type: string) => ({\n name: getIntegrationDescription(type),\n value: type,\n }));\n}\n\nexport interface Args {\n debug: boolean;\n integration: Integration;\n}\n\nexport const IS_DEV = ['test', 'development'].includes(\n process.env.NODE_ENV ?? '',\n);\n\nexport const DEBUG = false;\n\nexport const DEFAULT_URL = IS_DEV\n ? 'http://localhost:8010'\n : 'https://us.posthog.com';\nexport const ISSUES_URL = 'https://github.com/posthog/wizard/issues';\nexport const DEFAULT_HOST_URL = IS_DEV\n ? 'http://localhost:8010'\n : 'https://us.i.posthog.com';\nexport const ANALYTICS_POSTHOG_PUBLIC_PROJECT_WRITE_KEY = 'sTMFPsFhdP1Ssg';\nexport const ANALYTICS_HOST_URL = 'https://internal-j.posthog.com';\nexport const DUMMY_PROJECT_API_KEY = '_YOUR_POSTHOG_PROJECT_API_KEY_';\n\nexport const POSTHOG_US_CLIENT_ID = 'c4Rdw8DIxgtQfA80IiSnGKlNX8QN00cFWF00QQhM';\nexport const POSTHOG_EU_CLIENT_ID = 'bx2C5sZRN03TkdjraCcetvQFPGH6N2Y9vRLkcKEy';\nexport const POSTHOG_DEV_CLIENT_ID = 'DC5uRLVbGI02YQ82grxgnK6Qn12SXWpCqdPb60oZ';\nexport const OAUTH_PORT = 8239;\n"]}
|
package/dist/src/mcp.d.ts
CHANGED
|
@@ -2,8 +2,11 @@ import type { CloudRegion } from './utils/types';
|
|
|
2
2
|
export declare const runMCPInstall: (options: {
|
|
3
3
|
signup: boolean;
|
|
4
4
|
region?: CloudRegion;
|
|
5
|
+
local?: boolean;
|
|
6
|
+
}) => Promise<void>;
|
|
7
|
+
export declare const runMCPRemove: (options?: {
|
|
8
|
+
local?: boolean;
|
|
5
9
|
}) => Promise<void>;
|
|
6
|
-
export declare const runMCPRemove: () => Promise<void>;
|
|
7
10
|
export declare const getPersonalApiKey: (options: {
|
|
8
11
|
cloudRegion: CloudRegion;
|
|
9
12
|
}) => Promise<string>;
|
package/dist/src/mcp.js
CHANGED
|
@@ -12,10 +12,11 @@ const opn_1 = __importDefault(require("opn"));
|
|
|
12
12
|
const urls_1 = require("./utils/urls");
|
|
13
13
|
const helper_functions_1 = require("./lib/helper-functions");
|
|
14
14
|
const runMCPInstall = async (options) => {
|
|
15
|
-
clack_1.default.intro(chalk_1.default.bgGreenBright(
|
|
15
|
+
clack_1.default.intro(chalk_1.default.bgGreenBright(`Installing the PostHog MCP server ${options.local && '(local)'}`));
|
|
16
16
|
await (0, add_mcp_server_to_clients_1.addMCPServerToClientsStep)({
|
|
17
17
|
cloudRegion: options.region,
|
|
18
18
|
askPermission: false,
|
|
19
|
+
local: options.local,
|
|
19
20
|
});
|
|
20
21
|
clack_1.default.log.message(`${chalk_1.default.greenBright('You might need to restart your MCP clients to see the changes.')}`);
|
|
21
22
|
clack_1.default.log.message(`Get started with some prompts like:
|
|
@@ -26,9 +27,11 @@ const runMCPInstall = async (options) => {
|
|
|
26
27
|
${chalk_1.default.blueBright(`https://posthog.com/docs/model-context-protocol`)}`);
|
|
27
28
|
};
|
|
28
29
|
exports.runMCPInstall = runMCPInstall;
|
|
29
|
-
const runMCPRemove = async () => {
|
|
30
|
+
const runMCPRemove = async (options) => {
|
|
30
31
|
clack_1.default.intro(chalk_1.default.bgRed('Removing the PostHog MCP server'));
|
|
31
|
-
const results = await (0, add_mcp_server_to_clients_1.removeMCPServerFromClientsStep)({
|
|
32
|
+
const results = await (0, add_mcp_server_to_clients_1.removeMCPServerFromClientsStep)({
|
|
33
|
+
local: options?.local,
|
|
34
|
+
});
|
|
32
35
|
if (results.length === 0) {
|
|
33
36
|
clack_1.default.outro(`No PostHog MCP servers found to remove.`);
|
|
34
37
|
return;
|
package/dist/src/mcp.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp.js","sourceRoot":"","sources":["../../src/mcp.ts"],"names":[],"mappings":";;;;;;AAAA,kDAA0B;AAC1B,iFAG2C;AAC3C,0DAAkC;AAClC,qDAA4C;AAE5C,8CAAsB;AACtB,uCAAqD;AACrD,6DAA+C;AAExC,MAAM,aAAa,GAAG,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"mcp.js","sourceRoot":"","sources":["../../src/mcp.ts"],"names":[],"mappings":";;;;;;AAAA,kDAA0B;AAC1B,iFAG2C;AAC3C,0DAAkC;AAClC,qDAA4C;AAE5C,8CAAsB;AACtB,uCAAqD;AACrD,6DAA+C;AAExC,MAAM,aAAa,GAAG,KAAK,EAAE,OAInC,EAAE,EAAE;IACH,eA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,CAAC,CAAC;AAlBW,QAAA,YAAY,gBAkBvB;AAEK,MAAM,iBAAiB,GAAG,KAAK,EAAE,OAEvC,EAAmB,EAAE;IACpB,MAAM,QAAQ,GAAG,IAAA,4BAAqB,EAAC,OAAO,CAAC,WAAW,CAAC,CAAC;IAE5D,MAAM,SAAS,GAAG,GAAG,QAAQ,2CAA2C,CAAC;IAEzE,MAAM,OAAO,GAAG,eAAK,CAAC,OAAO,EAAE,CAAC;IAChC,OAAO,CAAC,KAAK,CACX,oEAAoE,CACrE,CAAC;IAEF,MAAM,IAAA,wBAAK,EAAC,IAAI,CAAC,CAAC;IAElB,OAAO,CAAC,IAAI,CACV,8IAA8I,eAAK,CAAC,IAAI,CACtJ,SAAS,CACV,EAAE,CACJ,CAAC;IAEF,IAAA,aAAG,EAAC,SAAS,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE;QACzC,iGAAiG;IACnG,CAAC,CAAC,CAAC;IAEH,MAAM,cAAc,GAAG,MAAM,eAAK,CAAC,QAAQ,CAAC;QAC1C,OAAO,EAAE,iCAAiC;QAC1C,QAAQ,CAAC,KAAK;YACZ,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;gBAAE,OAAO,oBAAoB,CAAC;YAEpD,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC;gBAC9B,OAAO,6FAA6F,CAAC;YACvG,CAAC;QACH,CAAC;KACF,CAAC,CAAC;IAEH,IAAI,CAAC,cAAc,EAAE,CAAC;QACpB,MAAM,IAAA,mBAAK,EAAC,+CAA+C,CAAC,CAAC;QAC7D,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,OAAO,cAAwB,CAAC;AAClC,CAAC,CAAC;AAzCW,QAAA,iBAAiB,qBAyC5B","sourcesContent":["import chalk from 'chalk';\nimport {\n addMCPServerToClientsStep,\n removeMCPServerFromClientsStep,\n} from './steps/add-mcp-server-to-clients';\nimport clack from './utils/clack';\nimport { abort } from './utils/clack-utils';\nimport type { CloudRegion } from './utils/types';\nimport opn from 'opn';\nimport { getCloudUrlFromRegion } from './utils/urls';\nimport { sleep } from './lib/helper-functions';\n\nexport const runMCPInstall = async (options: {\n signup: boolean;\n region?: CloudRegion;\n local?: boolean;\n}) => {\n clack.intro(\n chalk.bgGreenBright(\n `Installing the PostHog MCP server ${options.local && '(local)'}`,\n ),\n );\n\n await addMCPServerToClientsStep({\n cloudRegion: options.region,\n askPermission: false,\n local: options.local,\n });\n\n clack.log.message(\n `${chalk.greenBright(\n 'You might need to restart your MCP clients to see the changes.',\n )}`,\n );\n\n clack.log.message(`Get started with some prompts like:\n- What feature flags do I have active?\n- Add a new feature flag for our homepage redesign\n- What are my most common errors?`);\n\n clack.log.message(`Check out our MCP Server documentation:\n${chalk.blueBright(`https://posthog.com/docs/model-context-protocol`)}`);\n};\n\nexport const runMCPRemove = async (options?: { local?: boolean }) => {\n clack.intro(chalk.bgRed('Removing the PostHog MCP server'));\n const results = await removeMCPServerFromClientsStep({\n local: options?.local,\n });\n\n if (results.length === 0) {\n clack.outro(`No PostHog MCP servers found to remove.`);\n return;\n }\n\n clack.log.success(`PostHog MCP server removed from:`);\n results.map((c) => clack.log.message(`- ${c}`));\n clack.outro(\n `${chalk.green(\n 'You might need to restart your MCP clients to see the changes.\\n\\n',\n )}`,\n );\n};\n\nexport const getPersonalApiKey = async (options: {\n cloudRegion: CloudRegion;\n}): Promise<string> => {\n const cloudUrl = getCloudUrlFromRegion(options.cloudRegion);\n\n const urlToOpen = `${cloudUrl}/settings/user-api-keys?preset=mcp_server`;\n\n const spinner = clack.spinner();\n spinner.start(\n `Opening your project settings so you can get a Personal API key...`,\n );\n\n await sleep(1500);\n\n spinner.stop(\n `Opened your project settings. If the link didn't open automatically, open the following URL in your browser to get a Personal API key: \\n\\n${chalk.cyan(\n urlToOpen,\n )}`,\n );\n\n opn(urlToOpen, { wait: false }).catch(() => {\n // opn throws in environments that don't have a browser (e.g. remote shells) so we just noop here\n });\n\n const personalApiKey = await clack.password({\n message: 'Paste in your Personal API key:',\n validate(value) {\n if (value.length === 0) return `Value is required!`;\n\n if (!value.startsWith('phx_')) {\n return `That doesn't look right, are you sure you copied the right key? It should start with 'phx_'`;\n }\n },\n });\n\n if (!personalApiKey) {\n await abort('Unable to proceed without a personal API key.');\n return '';\n }\n\n return personalApiKey as string;\n};\n"]}
|
|
@@ -101,7 +101,7 @@ The event setup wizard will modify multiple files. For the best experience, comm
|
|
|
101
101
|
}
|
|
102
102
|
}
|
|
103
103
|
const cloudRegion = options.cloudRegion ?? (await (0, clack_utils_1.askForCloudRegion)());
|
|
104
|
-
const {
|
|
104
|
+
const { accessToken, projectId } = await (0, clack_utils_1.getOrAskForProjectData)({
|
|
105
105
|
...options,
|
|
106
106
|
cloudRegion,
|
|
107
107
|
});
|
|
@@ -197,7 +197,8 @@ The event setup wizard will modify multiple files. For the best experience, comm
|
|
|
197
197
|
model: 'gemini-2.5-flash',
|
|
198
198
|
region: cloudRegion,
|
|
199
199
|
schema: FileSelectionSchema,
|
|
200
|
-
|
|
200
|
+
accessToken,
|
|
201
|
+
projectId,
|
|
201
202
|
});
|
|
202
203
|
selectedFiles = response.files;
|
|
203
204
|
s.stop(`Selected ${selectedFiles.length} files for event tracking`);
|
|
@@ -292,7 +293,8 @@ The event setup wizard will modify multiple files. For the best experience, comm
|
|
|
292
293
|
model: 'gemini-2.5-pro',
|
|
293
294
|
region: cloudRegion,
|
|
294
295
|
schema: EnhancedFileSchema,
|
|
295
|
-
|
|
296
|
+
accessToken,
|
|
297
|
+
projectId,
|
|
296
298
|
});
|
|
297
299
|
// Apply changes immediately
|
|
298
300
|
if (response.content !== fileContent) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event-setup.js","sourceRoot":"","sources":["../../../src/nextjs/event-setup.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,kDAkYC;AA7a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AAC,aAAa,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;;oCAE9B,eAAK,CAAC,IAAI,CAAC,QAAQ,CAAC;;;;sCAIlB,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 { wizardHash } = 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 wizardHash,\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 wizardHash,\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
|
+
{"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,+CAAiC;AACjC,0CAAwD;AACxD,kDAA+C;AAE/C,sBAAsB;AACtB,MAAM,kBAAkB,GAAG,oBAAoB,CAAC;AAChD,MAAM,gBAAgB,GAAG,aAAa,CAAC;AAEvC,oCAAoC;AACpC,MAAM,mBAAmB,GAAG,OAAC,CAAC,MAAM,CAAC;IACnC,KAAK,EAAE,OAAC,CAAC,KAAK,CAAC,OAAC,CAAC,MAAM,EAAE,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC;CACnC,CAAC,CAAC;AAEH,uCAAuC;AACvC,MAAM,kBAAkB,GAAG,OAAC,CAAC,MAAM,CAAC;IAClC,QAAQ,EAAE,OAAC,CAAC,MAAM,EAAE;IACpB,OAAO,EAAE,OAAC,CAAC,MAAM,EAAE;IACnB,MAAM,EAAE,OAAC,CAAC,KAAK,CACb,OAAC,CAAC,MAAM,CAAC;QACP,IAAI,EAAE,OAAC,CAAC,MAAM,EAAE;QAChB,WAAW,EAAE,OAAC,C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AAG,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,EACvC,CAAC,CACF,CAAC;IAEF,qBAAS,CAAC,OAAO,CAAC,kBAAkB,EAAE;QACpC,MAAM,EAAE,uBAAuB;QAC/B,WAAW,EAAE,gBAAgB;QAC7B,WAAW;QACX,aAAa,EAAE,aAAa,CAAC,MAAM;QACnC,cAAc,EAAE,aAAa,CAAC,MAAM;KACrC,CAAC,CAAC;IAEH,qBAAS,CAAC,MAAM,CAAC,0BAA0B,EAAE,WAAW,CAAC,CAAC;IAC1D,qBAAS,CAAC,MAAM,CAAC,4BAA4B,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;IAErE,eAAK,CAAC,KAAK,CACT,kBAAkB,eAAK,CAAC,IAAI,CAC1B,WAAW,CAAC,QAAQ,EAAE,CACvB,kBAAkB,eAAK,CAAC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;;oCAE9B,eAAK,CAAC,IAAI,CAAC,QAAQ,CAAC;;;;sCAIlB,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"]}
|