@posthog/wizard 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/LICENSE +47 -0
  2. package/README.md +34 -0
  3. package/dist/bin.d.ts +2 -0
  4. package/dist/bin.js +28 -0
  5. package/dist/bin.js.map +1 -0
  6. package/dist/src/lib/constants.d.ts +20 -0
  7. package/dist/src/lib/constants.js +34 -0
  8. package/dist/src/lib/constants.js.map +1 -0
  9. package/dist/src/nextjs/docs.d.ts +8 -0
  10. package/dist/src/nextjs/docs.js +235 -0
  11. package/dist/src/nextjs/docs.js.map +1 -0
  12. package/dist/src/nextjs/nextjs-wizard.d.ts +9 -0
  13. package/dist/src/nextjs/nextjs-wizard.js +331 -0
  14. package/dist/src/nextjs/nextjs-wizard.js.map +1 -0
  15. package/dist/src/nextjs/prompts.d.ts +12 -0
  16. package/dist/src/nextjs/prompts.js +64 -0
  17. package/dist/src/nextjs/prompts.js.map +1 -0
  18. package/dist/src/nextjs/utils.d.ts +9 -0
  19. package/dist/src/nextjs/utils.js +80 -0
  20. package/dist/src/nextjs/utils.js.map +1 -0
  21. package/dist/src/run.d.ts +8 -0
  22. package/dist/src/run.js +69 -0
  23. package/dist/src/run.js.map +1 -0
  24. package/dist/src/telemetry.d.ts +2 -0
  25. package/dist/src/telemetry.js +13 -0
  26. package/dist/src/telemetry.js.map +1 -0
  27. package/dist/src/utils/analytics.d.ts +4 -0
  28. package/dist/src/utils/analytics.js +10 -0
  29. package/dist/src/utils/analytics.js.map +1 -0
  30. package/dist/src/utils/bash.d.ts +2 -0
  31. package/dist/src/utils/bash.js +54 -0
  32. package/dist/src/utils/bash.js.map +1 -0
  33. package/dist/src/utils/clack-utils.d.ts +177 -0
  34. package/dist/src/utils/clack-utils.js +628 -0
  35. package/dist/src/utils/clack-utils.js.map +1 -0
  36. package/dist/src/utils/clack.d.ts +2 -0
  37. package/dist/src/utils/clack.js +9 -0
  38. package/dist/src/utils/clack.js.map +1 -0
  39. package/dist/src/utils/debug.d.ts +2 -0
  40. package/dist/src/utils/debug.js +22 -0
  41. package/dist/src/utils/debug.js.map +1 -0
  42. package/dist/src/utils/environment.d.ts +1 -0
  43. package/dist/src/utils/environment.js +12 -0
  44. package/dist/src/utils/environment.js.map +1 -0
  45. package/dist/src/utils/file-utils.d.ts +2 -0
  46. package/dist/src/utils/file-utils.js +38 -0
  47. package/dist/src/utils/file-utils.js.map +1 -0
  48. package/dist/src/utils/logging.d.ts +9 -0
  49. package/dist/src/utils/logging.js +50 -0
  50. package/dist/src/utils/logging.js.map +1 -0
  51. package/dist/src/utils/package-json.d.ts +25 -0
  52. package/dist/src/utils/package-json.js +27 -0
  53. package/dist/src/utils/package-json.js.map +1 -0
  54. package/dist/src/utils/package-manager.d.ts +19 -0
  55. package/dist/src/utils/package-manager.js +188 -0
  56. package/dist/src/utils/package-manager.js.map +1 -0
  57. package/dist/src/utils/query.d.ts +6 -0
  58. package/dist/src/utils/query.js +27 -0
  59. package/dist/src/utils/query.js.map +1 -0
  60. package/dist/src/utils/semver.d.ts +5 -0
  61. package/dist/src/utils/semver.js +25 -0
  62. package/dist/src/utils/semver.js.map +1 -0
  63. package/dist/src/utils/string.d.ts +1 -0
  64. package/dist/src/utils/string.js +9 -0
  65. package/dist/src/utils/string.js.map +1 -0
  66. package/dist/src/utils/types.d.ts +30 -0
  67. package/dist/src/utils/types.js +3 -0
  68. package/dist/src/utils/types.js.map +1 -0
  69. package/dist/src/utils/vendor/is-unicorn-supported.d.ts +1 -0
  70. package/dist/src/utils/vendor/is-unicorn-supported.js +24 -0
  71. package/dist/src/utils/vendor/is-unicorn-supported.js.map +1 -0
  72. package/package.json +135 -0
@@ -0,0 +1,628 @@
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.abort = abort;
40
+ exports.abortIfCancelled = abortIfCancelled;
41
+ exports.printWelcome = printWelcome;
42
+ exports.confirmContinueIfNoOrDirtyGitRepo = confirmContinueIfNoOrDirtyGitRepo;
43
+ exports.isInGitRepo = isInGitRepo;
44
+ exports.getUncommittedOrUntrackedFiles = getUncommittedOrUntrackedFiles;
45
+ exports.askForItemSelection = askForItemSelection;
46
+ exports.confirmContinueIfPackageVersionNotSupported = confirmContinueIfPackageVersionNotSupported;
47
+ exports.installPackage = installPackage;
48
+ exports.runPrettierIfInstalled = runPrettierIfInstalled;
49
+ exports.ensurePackageIsInstalled = ensurePackageIsInstalled;
50
+ exports.getPackageDotJson = getPackageDotJson;
51
+ exports.updatePackageDotJson = updatePackageDotJson;
52
+ exports.getPackageManager = getPackageManager;
53
+ exports.isUsingTypeScript = isUsingTypeScript;
54
+ exports.getOrAskForProjectData = getOrAskForProjectData;
55
+ exports.askForToolConfigPath = askForToolConfigPath;
56
+ exports.showCopyPasteInstructions = showCopyPasteInstructions;
57
+ exports.makeCodeSnippet = makeCodeSnippet;
58
+ exports.createNewConfigFile = createNewConfigFile;
59
+ exports.featureSelectionPrompt = featureSelectionPrompt;
60
+ exports.askShouldInstallPackage = askShouldInstallPackage;
61
+ exports.askShouldAddPackageOverride = askShouldAddPackageOverride;
62
+ const childProcess = __importStar(require("node:child_process"));
63
+ const fs = __importStar(require("node:fs"));
64
+ const os = __importStar(require("node:os"));
65
+ const node_path_1 = require("node:path");
66
+ const node_timers_1 = require("node:timers");
67
+ const node_url_1 = require("node:url");
68
+ const axios_1 = __importDefault(require("axios"));
69
+ const chalk_1 = __importDefault(require("chalk"));
70
+ const opn_1 = __importDefault(require("opn"));
71
+ const telemetry_1 = require("../telemetry");
72
+ const debug_1 = require("./debug");
73
+ const package_json_1 = require("./package-json");
74
+ const package_manager_1 = require("./package-manager");
75
+ const semver_1 = require("./semver");
76
+ const constants_1 = require("../lib/constants");
77
+ const analytics_1 = require("./analytics");
78
+ const clack_1 = __importDefault(require("./clack"));
79
+ async function abort(message, status) {
80
+ clack_1.default.outro(message ?? 'Wizard setup cancelled.');
81
+ return process.exit(status ?? 1);
82
+ }
83
+ async function abortIfCancelled(input) {
84
+ if (clack_1.default.isCancel(await input)) {
85
+ clack_1.default.cancel('Wizard setup cancelled.');
86
+ process.exit(0);
87
+ }
88
+ else {
89
+ return input;
90
+ }
91
+ }
92
+ function printWelcome(options) {
93
+ const wizardVersion = process.env.npm_package_version;
94
+ // eslint-disable-next-line no-console
95
+ console.log('');
96
+ clack_1.default.intro(chalk_1.default.inverse(` ${options.wizardName} `));
97
+ let welcomeText = options.message ||
98
+ `The ${options.wizardName} will help you set up PostHog for your application.\nThank you for using PostHog :)`;
99
+ if (wizardVersion) {
100
+ welcomeText = `${welcomeText}\n\nVersion: ${wizardVersion}`;
101
+ }
102
+ if (options.telemetryEnabled) {
103
+ welcomeText = `${welcomeText}
104
+
105
+ This wizard sends telemetry data and crash reports to PostHog. This helps us improve the Wizard.
106
+ You can turn this off at any time by running ${chalk_1.default.cyanBright('npx @posthog/wizard --disable-telemetry')}.`;
107
+ }
108
+ clack_1.default.note(welcomeText);
109
+ }
110
+ async function confirmContinueIfNoOrDirtyGitRepo() {
111
+ return (0, telemetry_1.traceStep)('check-git-status', async () => {
112
+ if (!isInGitRepo()) {
113
+ const continueWithoutGit = await abortIfCancelled(clack_1.default.confirm({
114
+ message: 'You are not inside a git repository. The wizard will create and update files. Do you want to continue anyway?',
115
+ }));
116
+ analytics_1.Analytics.setTag('continue-without-git', continueWithoutGit);
117
+ if (!continueWithoutGit) {
118
+ await abort(undefined, 0);
119
+ }
120
+ // return early to avoid checking for uncommitted files
121
+ return;
122
+ }
123
+ const uncommittedOrUntrackedFiles = getUncommittedOrUntrackedFiles();
124
+ if (uncommittedOrUntrackedFiles.length) {
125
+ clack_1.default.log.warn(`You have uncommitted or untracked files in your repo:
126
+
127
+ ${uncommittedOrUntrackedFiles.join('\n')}
128
+
129
+ The wizard will create and update files.`);
130
+ const continueWithDirtyRepo = await abortIfCancelled(clack_1.default.confirm({
131
+ message: 'Do you want to continue anyway?',
132
+ }));
133
+ analytics_1.Analytics.setTag('continue-with-dirty-repo', continueWithDirtyRepo);
134
+ if (!continueWithDirtyRepo) {
135
+ await abort(undefined, 0);
136
+ }
137
+ }
138
+ });
139
+ }
140
+ function isInGitRepo() {
141
+ try {
142
+ childProcess.execSync('git rev-parse --is-inside-work-tree', {
143
+ stdio: 'ignore',
144
+ });
145
+ return true;
146
+ }
147
+ catch {
148
+ return false;
149
+ }
150
+ }
151
+ function getUncommittedOrUntrackedFiles() {
152
+ try {
153
+ const gitStatus = childProcess
154
+ .execSync('git status --porcelain=v1', {
155
+ // we only care about stdout
156
+ stdio: ['ignore', 'pipe', 'ignore'],
157
+ })
158
+ .toString();
159
+ const files = gitStatus
160
+ .split(os.EOL)
161
+ .map((line) => line.trim())
162
+ .filter(Boolean)
163
+ .map((f) => `- ${f.split(/\s+/)[1]}`);
164
+ return files;
165
+ }
166
+ catch {
167
+ return [];
168
+ }
169
+ }
170
+ async function askForItemSelection(items, message) {
171
+ const selection = await abortIfCancelled(clack_1.default.select({
172
+ maxItems: 12,
173
+ message: message,
174
+ options: items.map((item, index) => {
175
+ return {
176
+ value: { value: item, index: index },
177
+ label: item,
178
+ };
179
+ }),
180
+ }));
181
+ return selection;
182
+ }
183
+ async function confirmContinueIfPackageVersionNotSupported({ packageId, packageName, packageVersion, acceptableVersions, note, }) {
184
+ return (0, telemetry_1.traceStep)(`check-package-version`, async () => {
185
+ analytics_1.Analytics.setTag(`${packageName.toLowerCase()}-version`, packageVersion);
186
+ const isSupportedVersion = (0, semver_1.fulfillsVersionRange)({
187
+ acceptableVersions,
188
+ version: packageVersion,
189
+ canBeLatest: true,
190
+ });
191
+ if (isSupportedVersion) {
192
+ analytics_1.Analytics.setTag(`${packageName.toLowerCase()}-supported`, true);
193
+ return;
194
+ }
195
+ clack_1.default.log.warn(`You have an unsupported version of ${packageName} installed:
196
+
197
+ ${packageId}@${packageVersion}`);
198
+ clack_1.default.note(note ??
199
+ `Please upgrade to ${acceptableVersions} if you wish to use the PostHog Wizard.`);
200
+ const continueWithUnsupportedVersion = await abortIfCancelled(clack_1.default.confirm({
201
+ message: 'Do you want to continue anyway?',
202
+ }));
203
+ analytics_1.Analytics.setTag(`${packageName.toLowerCase()}-continue-with-unsupported-version`, continueWithUnsupportedVersion);
204
+ if (!continueWithUnsupportedVersion) {
205
+ await abort(undefined, 0);
206
+ }
207
+ });
208
+ }
209
+ /**
210
+ * Installs or updates a package with the user's package manager.
211
+ *
212
+ * IMPORTANT: This function modifies the `package.json`! Be sure to re-read
213
+ * it if you make additional modifications to it after calling this function!
214
+ */
215
+ async function installPackage({ packageName, alreadyInstalled, askBeforeUpdating = true, packageNameDisplayLabel, packageManager, forceInstall = false, }) {
216
+ return (0, telemetry_1.traceStep)('install-package', async () => {
217
+ if (alreadyInstalled && askBeforeUpdating) {
218
+ const shouldUpdatePackage = await abortIfCancelled(clack_1.default.confirm({
219
+ message: `The ${chalk_1.default.bold.cyan(packageNameDisplayLabel ?? packageName)} package is already installed. Do you want to update it to the latest version?`,
220
+ }));
221
+ if (!shouldUpdatePackage) {
222
+ return {};
223
+ }
224
+ }
225
+ const sdkInstallSpinner = clack_1.default.spinner();
226
+ const pkgManager = packageManager || (await getPackageManager());
227
+ sdkInstallSpinner.start(`${alreadyInstalled ? 'Updating' : 'Installing'} ${chalk_1.default.bold.cyan(packageNameDisplayLabel ?? packageName)} with ${chalk_1.default.bold(pkgManager.label)}.`);
228
+ try {
229
+ await new Promise((resolve, reject) => {
230
+ childProcess.exec(`${pkgManager.installCommand} ${packageName} ${pkgManager.flags} ${forceInstall ? pkgManager.forceInstallFlag : ''}`, { cwd: constants_1.INSTALL_DIR }, (err, stdout, stderr) => {
231
+ if (err) {
232
+ // Write a log file so we can better troubleshoot issues
233
+ fs.writeFileSync((0, node_path_1.join)(process.cwd(), `posthog-wizard-installation-error-${Date.now()}.log`), JSON.stringify({
234
+ stdout,
235
+ stderr,
236
+ }), { encoding: 'utf8' });
237
+ reject(err);
238
+ }
239
+ else {
240
+ resolve();
241
+ }
242
+ });
243
+ });
244
+ }
245
+ catch (e) {
246
+ sdkInstallSpinner.stop('Installation failed.');
247
+ clack_1.default.log.error(`${chalk_1.default.red('Encountered the following error during installation:')}\n\n${e}\n\n${chalk_1.default.dim(`The wizard has created a \`posthog-wizard-installation-error-*.log\` file. If you think this issue is caused by the PostHog Wizard, create an issue on GitHub and include the log file's content:\n${constants_1.ISSUES_URL}`)}`);
248
+ await abort();
249
+ }
250
+ sdkInstallSpinner.stop(`${alreadyInstalled ? 'Updated' : 'Installed'} ${chalk_1.default.bold.cyan(packageNameDisplayLabel ?? packageName)} with ${chalk_1.default.bold(pkgManager.label)}.`);
251
+ return { packageManager: pkgManager };
252
+ });
253
+ }
254
+ async function runPrettierIfInstalled() {
255
+ return (0, telemetry_1.traceStep)('run-prettier', async () => {
256
+ if (!isInGitRepo()) {
257
+ // We only run formatting on changed files. If we're not in a git repo, we can't find
258
+ // changed files. So let's early-return without showing any formatting-related messages.
259
+ return;
260
+ }
261
+ const changedOrUntrackedFiles = getUncommittedOrUntrackedFiles()
262
+ .map((filename) => {
263
+ return filename.startsWith('- ') ? filename.slice(2) : filename;
264
+ })
265
+ .join(' ');
266
+ if (!changedOrUntrackedFiles.length) {
267
+ // Likewise, if we can't find changed or untracked files, there's no point in running Prettier.
268
+ return;
269
+ }
270
+ const packageJson = await getPackageDotJson();
271
+ const prettierInstalled = (0, package_json_1.hasPackageInstalled)('prettier', packageJson);
272
+ analytics_1.Analytics.setTag('prettier-installed', prettierInstalled);
273
+ if (!prettierInstalled) {
274
+ return;
275
+ }
276
+ const prettierSpinner = clack_1.default.spinner();
277
+ prettierSpinner.start('Running Prettier on your files.');
278
+ try {
279
+ await new Promise((resolve, reject) => {
280
+ childProcess.exec(`npx prettier --ignore-unknown --write ${changedOrUntrackedFiles}`, (err) => {
281
+ if (err) {
282
+ reject(err);
283
+ }
284
+ else {
285
+ resolve();
286
+ }
287
+ });
288
+ });
289
+ }
290
+ catch (e) {
291
+ prettierSpinner.stop('Prettier failed to run.');
292
+ clack_1.default.log.warn('Prettier failed to run. There may be formatting issues in your updated files.');
293
+ return;
294
+ }
295
+ prettierSpinner.stop('Prettier has formatted your files.');
296
+ });
297
+ }
298
+ /**
299
+ * Checks if @param packageId is listed as a dependency in @param packageJson.
300
+ * If not, it will ask users if they want to continue without the package.
301
+ *
302
+ * Use this function to check if e.g. a the framework of the SDK is installed
303
+ *
304
+ * @param packageJson the package.json object
305
+ * @param packageId the npm name of the package
306
+ * @param packageName a human readable name of the package
307
+ */
308
+ async function ensurePackageIsInstalled(packageJson, packageId, packageName) {
309
+ return (0, telemetry_1.traceStep)('ensure-package-installed', async () => {
310
+ const installed = (0, package_json_1.hasPackageInstalled)(packageId, packageJson);
311
+ analytics_1.Analytics.setTag(`${packageName.toLowerCase()}-installed`, installed);
312
+ if (!installed) {
313
+ analytics_1.Analytics.setTag(`${packageName.toLowerCase()}-installed`, false);
314
+ const continueWithoutPackage = await abortIfCancelled(clack_1.default.confirm({
315
+ message: `${packageName} does not seem to be installed. Do you still want to continue?`,
316
+ initialValue: false,
317
+ }));
318
+ if (!continueWithoutPackage) {
319
+ await abort(undefined, 0);
320
+ }
321
+ }
322
+ });
323
+ }
324
+ async function getPackageDotJson() {
325
+ const packageJsonFileContents = await fs.promises
326
+ .readFile((0, node_path_1.join)(constants_1.INSTALL_DIR, 'package.json'), 'utf8')
327
+ .catch(() => {
328
+ clack_1.default.log.error('Could not find package.json. Make sure to run the wizard in the root of your app!');
329
+ return abort();
330
+ });
331
+ let packageJson = undefined;
332
+ try {
333
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
334
+ packageJson = JSON.parse(packageJsonFileContents);
335
+ }
336
+ catch {
337
+ clack_1.default.log.error(`Unable to parse your ${chalk_1.default.cyan('package.json')}. Make sure it has a valid format!`);
338
+ await abort();
339
+ }
340
+ return packageJson || {};
341
+ }
342
+ async function updatePackageDotJson(packageDotJson) {
343
+ try {
344
+ await fs.promises.writeFile((0, node_path_1.join)(constants_1.INSTALL_DIR, 'package.json'),
345
+ // TODO: maybe figure out the original indentation
346
+ JSON.stringify(packageDotJson, null, 2), {
347
+ encoding: 'utf8',
348
+ flag: 'w',
349
+ });
350
+ }
351
+ catch {
352
+ clack_1.default.log.error(`Unable to update your ${chalk_1.default.cyan('package.json')}.`);
353
+ await abort();
354
+ }
355
+ }
356
+ async function getPackageManager() {
357
+ const detectedPackageManager = (0, package_manager_1.detectPackageManger)();
358
+ if (detectedPackageManager) {
359
+ return detectedPackageManager;
360
+ }
361
+ const selectedPackageManager = await abortIfCancelled(clack_1.default.select({
362
+ message: 'Please select your package manager.',
363
+ options: package_manager_1.packageManagers.map((packageManager) => ({
364
+ value: packageManager,
365
+ label: packageManager.label,
366
+ })),
367
+ }));
368
+ analytics_1.Analytics.setTag('package-manager', selectedPackageManager.name);
369
+ return selectedPackageManager;
370
+ }
371
+ function isUsingTypeScript() {
372
+ try {
373
+ return fs.existsSync((0, node_path_1.join)(constants_1.INSTALL_DIR, 'tsconfig.json'));
374
+ }
375
+ catch {
376
+ return false;
377
+ }
378
+ }
379
+ /**
380
+ * Checks if we already got project data from a previous wizard invocation.
381
+ * If yes, this data is returned.
382
+ * Otherwise, we start the login flow and ask the user to select a project.
383
+ *
384
+ * Use this function to get project data for the wizard.
385
+ *
386
+ * @param options wizard options
387
+ * @returns project data (token, url)
388
+ */
389
+ async function getOrAskForProjectData(_options) {
390
+ const { host, projectApiKey, wizardHash } = await (0, telemetry_1.traceStep)('login', () => askForWizardLogin({
391
+ url: constants_1.CLOUD_URL,
392
+ }));
393
+ if (!projectApiKey) {
394
+ clack_1.default.log.error(`Didn't receive a project API key. This shouldn't happen :(
395
+
396
+ Please let us know if you think this is a bug in the wizard:
397
+ ${chalk_1.default.cyan(constants_1.ISSUES_URL)}`);
398
+ clack_1.default.log
399
+ .info(`In the meantime, we'll add a dummy project API key (${chalk_1.default.cyan(`"${constants_1.DUMMY_PROJECT_API_KEY}"`)}) for you to replace later.
400
+ You can find your Project API key here:
401
+ ${chalk_1.default.cyan(`${constants_1.CLOUD_URL}/settings/project#variables`)}`);
402
+ }
403
+ return {
404
+ wizardHash,
405
+ host: host || constants_1.DEFAULT_HOST_URL,
406
+ projectApiKey: projectApiKey || constants_1.DUMMY_PROJECT_API_KEY,
407
+ };
408
+ }
409
+ async function askForWizardLogin(options) {
410
+ let wizardHash;
411
+ try {
412
+ wizardHash = (await axios_1.default.post(`${options.url}/api/wizard/initialize`)).data.hash;
413
+ }
414
+ catch (e) {
415
+ clack_1.default.log.error('Loading wizard failed.');
416
+ clack_1.default.log.info(JSON.stringify(e, null, 2));
417
+ await abort(chalk_1.default.red(`Please try again in a few minutes and let us know if this issue persists: ${constants_1.ISSUES_URL}`));
418
+ }
419
+ const loginUrl = new node_url_1.URL(`${options.url}/wizard?hash=${wizardHash}`);
420
+ const urlToOpen = loginUrl.toString();
421
+ clack_1.default.log.info(`${chalk_1.default.bold(`If the browser window didn't open automatically, please open the following link to login into PostHog:`)}\n\n${chalk_1.default.cyan(urlToOpen)}`);
422
+ (0, opn_1.default)(urlToOpen, { wait: false }).catch(() => {
423
+ // opn throws in environments that don't have a browser (e.g. remote shells) so we just noop here
424
+ });
425
+ const loginSpinner = clack_1.default.spinner();
426
+ loginSpinner.start('Waiting for you to log in using the link above');
427
+ const data = await new Promise((resolve) => {
428
+ const pollingInterval = (0, node_timers_1.setInterval)(() => {
429
+ axios_1.default
430
+ .get(`${options.url}/api/wizard/data`, {
431
+ headers: {
432
+ 'Accept-Encoding': 'deflate',
433
+ 'X-PostHog-Wizard-Hash': wizardHash,
434
+ },
435
+ })
436
+ .then((result) => {
437
+ const data = {
438
+ wizardHash,
439
+ projectApiKey: result.data.project_api_key,
440
+ host: result.data.host,
441
+ };
442
+ resolve(data);
443
+ clearTimeout(timeout);
444
+ clearInterval(pollingInterval);
445
+ })
446
+ .catch(() => {
447
+ // noop - just try again
448
+ });
449
+ }, 500);
450
+ const timeout = setTimeout(() => {
451
+ clearInterval(pollingInterval);
452
+ loginSpinner.stop('Login timed out. No worries - it happens to the best of us.');
453
+ analytics_1.Analytics.setTag('opened-wizard-link', false);
454
+ void abort('Please restart the Wizard and log in to complete the setup.');
455
+ }, 180_000);
456
+ });
457
+ loginSpinner.stop('Login complete.');
458
+ analytics_1.Analytics.setTag('opened-wizard-link', true);
459
+ return data;
460
+ }
461
+ /**
462
+ * Asks users if they have a config file for @param tool (e.g. Vite).
463
+ * If yes, asks users to specify the path to their config file.
464
+ *
465
+ * Use this helper function as a fallback mechanism if the lookup for
466
+ * a config file with its most usual location/name fails.
467
+ *
468
+ * @param toolName Name of the tool for which we're looking for the config file
469
+ * @param configFileName Name of the most common config file name (e.g. vite.config.js)
470
+ *
471
+ * @returns a user path to the config file or undefined if the user doesn't have a config file
472
+ */
473
+ async function askForToolConfigPath(toolName, configFileName) {
474
+ const hasConfig = await abortIfCancelled(clack_1.default.confirm({
475
+ message: `Do you have a ${toolName} config file (e.g. ${chalk_1.default.cyan(configFileName)})?`,
476
+ initialValue: true,
477
+ }));
478
+ if (!hasConfig) {
479
+ return undefined;
480
+ }
481
+ return await abortIfCancelled(clack_1.default.text({
482
+ message: `Please enter the path to your ${toolName} config file:`,
483
+ placeholder: (0, node_path_1.join)('.', configFileName),
484
+ validate: (value) => {
485
+ if (!value) {
486
+ return 'Please enter a path.';
487
+ }
488
+ try {
489
+ fs.accessSync(value);
490
+ }
491
+ catch {
492
+ return 'Could not access the file at this path.';
493
+ }
494
+ },
495
+ }));
496
+ }
497
+ /**
498
+ * Prints copy/paste-able instructions to the console.
499
+ * Afterwards asks the user if they added the code snippet to their file.
500
+ *
501
+ * While there's no point in providing a "no" answer here, it gives users time to fulfill the
502
+ * task before the wizard continues with additional steps.
503
+ *
504
+ * Use this function if you want to show users instructions on how to add/modify
505
+ * code in their file. This is helpful if automatic insertion failed or is not possible/feasible.
506
+ *
507
+ * @param filename the name of the file to which the code snippet should be applied.
508
+ * If a path is provided, only the filename will be used.
509
+ *
510
+ * @param codeSnippet the snippet to be printed. Use {@link makeCodeSnippet} to create the
511
+ * diff-like format for visually highlighting unchanged or modified lines of code.
512
+ *
513
+ * @param hint (optional) a hint to be printed after the main instruction to add
514
+ * the code from @param codeSnippet to their @param filename.
515
+ *
516
+ * TODO: refactor copy paste instructions across different wizards to use this function.
517
+ * this might require adding a custom message parameter to the function
518
+ */
519
+ async function showCopyPasteInstructions(filename, codeSnippet, hint) {
520
+ clack_1.default.log.step(`Add the following code to your ${chalk_1.default.cyan((0, node_path_1.basename)(filename))} file:${hint ? chalk_1.default.dim(` (${chalk_1.default.dim(hint)})`) : ''}`);
521
+ // Padding the code snippet to be printed with a \n at the beginning and end
522
+ // This makes it easier to distinguish the snippet from the rest of the output
523
+ // Intentionally logging directly to console here so that the code can be copied/pasted directly
524
+ // eslint-disable-next-line no-console
525
+ console.log(`\n${codeSnippet}\n`);
526
+ await abortIfCancelled(clack_1.default.select({
527
+ message: 'Did you apply the snippet above?',
528
+ options: [{ label: 'Yes, continue!', value: true }],
529
+ initialValue: true,
530
+ }));
531
+ }
532
+ /**
533
+ * Crafts a code snippet that can be used to e.g.
534
+ * - print copy/paste instructions to the console
535
+ * - create a new config file.
536
+ *
537
+ * @param colors set this to true if you want the final snippet to be colored.
538
+ * This is useful for printing the snippet to the console as part of copy/paste instructions.
539
+ *
540
+ * @param callback the callback that returns the formatted code snippet.
541
+ * It exposes takes the helper functions for marking code as unchanged, new or removed.
542
+ * These functions no-op if no special formatting should be applied
543
+ * and otherwise apply the appropriate formatting/coloring.
544
+ * (@see {@link CodeSnippetFormatter})
545
+ *
546
+ * @see {@link showCopyPasteInstructions} for the helper with which to display the snippet in the console.
547
+ *
548
+ * @returns a string containing the final, formatted code snippet.
549
+ */
550
+ function makeCodeSnippet(colors, callback) {
551
+ const unchanged = (txt) => (colors ? chalk_1.default.grey(txt) : txt);
552
+ const plus = (txt) => (colors ? chalk_1.default.greenBright(txt) : txt);
553
+ const minus = (txt) => (colors ? chalk_1.default.redBright(txt) : txt);
554
+ return callback(unchanged, plus, minus);
555
+ }
556
+ /**
557
+ * Creates a new config file with the given @param filepath and @param codeSnippet.
558
+ *
559
+ * Use this function to create a new config file for users. This is useful
560
+ * when users answered that they don't yet have a config file for a tool.
561
+ *
562
+ * (This doesn't mean that they don't yet have some other way of configuring
563
+ * their tool but we can leave it up to them to figure out how to merge configs
564
+ * here.)
565
+ *
566
+ * @param filepath absolute path to the new config file
567
+ * @param codeSnippet the snippet to be inserted into the file
568
+ * @param moreInformation (optional) the message to be printed after the file was created
569
+ * For example, this can be a link to more information about configuring the tool.
570
+ *
571
+ * @returns true on success, false otherwise
572
+ */
573
+ async function createNewConfigFile(filepath, codeSnippet, moreInformation) {
574
+ if (!(0, node_path_1.isAbsolute)(filepath)) {
575
+ (0, debug_1.debug)(`createNewConfigFile: filepath is not absolute: ${filepath}`);
576
+ return false;
577
+ }
578
+ const prettyFilename = chalk_1.default.cyan((0, node_path_1.relative)(constants_1.INSTALL_DIR, filepath));
579
+ try {
580
+ await fs.promises.writeFile(filepath, codeSnippet);
581
+ clack_1.default.log.success(`Added new ${prettyFilename} file.`);
582
+ if (moreInformation) {
583
+ clack_1.default.log.info(chalk_1.default.gray(moreInformation));
584
+ }
585
+ return true;
586
+ }
587
+ catch (e) {
588
+ (0, debug_1.debug)(e);
589
+ clack_1.default.log.warn(`Could not create a new ${prettyFilename} file. Please create one manually and follow the instructions below.`);
590
+ }
591
+ return false;
592
+ }
593
+ async function featureSelectionPrompt(features) {
594
+ return (0, telemetry_1.traceStep)('feature-selection', async () => {
595
+ const selectedFeatures = {};
596
+ for (const feature of features) {
597
+ const selected = await abortIfCancelled(clack_1.default.select({
598
+ message: feature.prompt,
599
+ initialValue: true,
600
+ options: [
601
+ {
602
+ value: true,
603
+ label: 'Yes',
604
+ hint: feature.enabledHint,
605
+ },
606
+ {
607
+ value: false,
608
+ label: 'No',
609
+ hint: feature.disabledHint,
610
+ },
611
+ ],
612
+ }));
613
+ selectedFeatures[feature.id] = selected;
614
+ }
615
+ return selectedFeatures;
616
+ });
617
+ }
618
+ async function askShouldInstallPackage(pkgName) {
619
+ return (0, telemetry_1.traceStep)(`ask-install-package`, () => abortIfCancelled(clack_1.default.confirm({
620
+ message: `Do you want to install ${chalk_1.default.cyan(pkgName)}?`,
621
+ })));
622
+ }
623
+ async function askShouldAddPackageOverride(pkgName, pkgVersion) {
624
+ return (0, telemetry_1.traceStep)(`ask-add-package-override`, () => abortIfCancelled(clack_1.default.confirm({
625
+ message: `Do you want to add an override for ${chalk_1.default.cyan(pkgName)} version ${chalk_1.default.cyan(pkgVersion)}?`,
626
+ })));
627
+ }
628
+ //# sourceMappingURL=clack-utils.js.map