diff --git a/apps/cli-docs/src/fragments/commands/wizard.md b/apps/cli-docs/src/fragments/commands/wizard.md index 5412b86ff..b396ea280 100644 --- a/apps/cli-docs/src/fragments/commands/wizard.md +++ b/apps/cli-docs/src/fragments/commands/wizard.md @@ -57,3 +57,12 @@ but not most of its flags or its `SENTRY_WIZARD_*` environment variables: The Cordova and Electron wizards were retired. Follow their setup guides in the Sentry docs instead. + +Flows that uploaded source maps with `@sentry/cli`, such as Angular, now +install the `sentry` package instead. The `sentry:sourcemaps` script they add +to `package.json` runs `sentry sourcemap upload` on your build output, which +injects debug IDs before it uploads. The wizard writes your org, project and, +on self-hosted Sentry, URL to the `[defaults]` section of the project's +`.sentryclirc`, next to the auth token, and adds the file to `.gitignore`. In +CI, set `SENTRY_AUTH_TOKEN`. On self-hosted Sentry, also set `SENTRY_ORG`, +`SENTRY_PROJECT` and `SENTRY_URL`. diff --git a/packages/cli/src/lib/wizard/angular/angular-wizard.ts b/packages/cli/src/lib/wizard/angular/angular-wizard.ts new file mode 100644 index 000000000..f2844f7e6 --- /dev/null +++ b/packages/cli/src/lib/wizard/angular/angular-wizard.ts @@ -0,0 +1,311 @@ +/** + * The Angular setup wizard: installs `@sentry/angular`, initializes it in + * `src/main.ts`, adds the Sentry providers to the app config, turns on + * source maps in `angular.json`, sets up their upload with `sentry + * sourcemap` commands, and optionally creates an example component. + */ + +import path from "node:path"; +import chalk from "chalk"; +import { gte } from "semver"; +import { setupCI } from "../sourcemaps/ci.js"; +import { configureAngularSourcemapGenerationFlow } from "../sourcemaps/tools/angular.js"; +import { configureSentryCLI } from "../sourcemaps/tools/sentry-cli.js"; +import { Sentry, traceStep, withTelemetry } from "../telemetry.js"; +import { abortIfSpotlightNotSupported } from "../utils/abort-if-sportlight-not-supported.js"; +import { + abort, + abortIfCancelled, + askShouldCreateExampleComponent, + confirmContinueIfNoOrDirtyGitRepo, + ensurePackageIsInstalled, + featureSelectionPrompt, + getOrAskForProjectData, + getPackageDotJson, + installPackage, + printSdkV11MigrationGuideIfOutdated, + printWelcome, + runPrettierIfInstalled, +} from "../utils/clack/index.js"; +import { offerProjectScopedMcpConfig } from "../utils/clack/mcp-config.js"; +import { clack } from "../utils/clack/prompts.js"; +import { + askShouldReduceDataCollection, + sdkSupportsDataCollection, +} from "../utils/data-collection.js"; +import { warnIfNodeVersionUnsupportedBySdkV11 } from "../utils/node-version.js"; +import { + getPackageVersion, + hasPackageInstalled, +} from "../utils/package-json.js"; +import { safeMinVersion } from "../utils/semver.js"; +import type { WizardOptions } from "../utils/types.js"; +import { addSourcemapEntryToAngularJSON } from "./codemods/sourcemaps.js"; +import { createExampleComponent } from "./example-component.js"; +import { + initializeSentryOnApplicationEntry, + updateAppConfig, +} from "./sdk-setup.js"; + +const MIN_SUPPORTED_ANGULAR_VERSION = "14.0.0"; +const MIN_SUPPORTED_WIZARD_ANGULAR_VERSION = "17.0.0"; + +/** Run the Angular wizard (`sentry wizard angular`). */ +export async function runAngularWizard(options: WizardOptions): Promise { + return await withTelemetry( + { + enabled: options.telemetryEnabled, + integration: "angular", + wizardOptions: options, + }, + () => runAngularWizardWithTelemetry(options), + ); +} + +async function runAngularWizardWithTelemetry( + options: WizardOptions, +): Promise { + printWelcome({ + wizardName: "Sentry Angular Wizard", + telemetryEnabled: options.telemetryEnabled, + }); + + warnIfNodeVersionUnsupportedBySdkV11(); + + await confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: options.ignoreGitChanges, + cwd: undefined, + }); + + const packageJson = await getPackageDotJson(); + + await ensurePackageIsInstalled(packageJson, "@angular/core", "Angular"); + + let installedAngularVersion = getPackageVersion("@angular/core", packageJson); + + if (!installedAngularVersion) { + clack.log.warn("Could not determine installed Angular version."); + + installedAngularVersion = await abortIfCancelled( + clack.text({ + message: `Please enter your installed Angular major version (e.g. ${chalk.cyan( + "18", + )} for Angular 18)`, + validate(value) { + if (!value) { + return "Angular version is required"; + } + + if (!safeMinVersion(value)) { + return `Invalid Angular version provided: ${value}`; + } + return undefined; + }, + }), + ); + } + + Sentry.setTag("angular-version", installedAngularVersion); + + const installedMinVersion = safeMinVersion(installedAngularVersion); + if (!installedMinVersion) { + clack.log.warn( + `Could not parse the Angular version ${chalk.cyan(installedAngularVersion)}.`, + ); + return await abort("Exiting the wizard."); + } + + const sdkSupportsAngularVersion = gte( + installedMinVersion, + MIN_SUPPORTED_ANGULAR_VERSION, + ); + + const wizardSupportsAngularVersion = gte( + installedMinVersion, + MIN_SUPPORTED_WIZARD_ANGULAR_VERSION, + ); + + if (!sdkSupportsAngularVersion) { + Sentry.setTag("angular-version-compatible", false); + + clack.log.warn( + `Angular version ${chalk.cyan( + MIN_SUPPORTED_ANGULAR_VERSION, + )} or higher is required for the Sentry SDK.`, + ); + clack.log.warn( + `Please refer to Sentry's version compatibility table for more information: + +${chalk.underline( + "https://docs.sentry.io/platforms/javascript/guides/angular/#angular-version-compatibility", +)} +`, + ); + + return await abort("Exiting the wizard.", 0); + } + + if (!wizardSupportsAngularVersion) { + Sentry.setTag("angular-wizard-version-compatible", false); + + clack.log.warn( + `The Sentry Angular Wizard requires Angular version ${chalk.cyan( + MIN_SUPPORTED_WIZARD_ANGULAR_VERSION, + )} or higher.`, + ); + clack.log.warn( + `Your Angular version (${installedAngularVersion}) is compatible with the Sentry SDK but you need to set it up manually by following our documentation: + +${chalk.underline("https://docs.sentry.io/platforms/javascript/guides/angular")} + +Apologies for the inconvenience!`, + ); + + return await abort("Exiting the wizard.", 0); + } + + const projectData = await getOrAskForProjectData( + options, + "javascript-angular", + ); + + if (projectData.spotlight) { + return await abortIfSpotlightNotSupported("Angular"); + } + + const { selectedProject, authToken, sentryUrl, selfHosted } = projectData; + + const dsn = selectedProject.keys[0].dsn.public; + + const sdkAlreadyInstalled = hasPackageInstalled( + "@sentry/angular", + packageJson, + ); + + Sentry.setTag("sdk-already-installed", sdkAlreadyInstalled); + + printSdkV11MigrationGuideIfOutdated("@sentry/angular", packageJson); + + await installPackage({ + packageName: "@sentry/angular@^11", + packageNameDisplayLabel: "@sentry/angular", + alreadyInstalled: sdkAlreadyInstalled, + forceInstall: options.forceInstall, + }); + + // The install may have been skipped (user declined the update prompt), so + // re-read package.json to learn which SDK major is actually installed. + const installedSdkVersion = getPackageVersion( + "@sentry/angular", + await getPackageDotJson(), + ); + + // From v11 on, the SDK collects rich context by default, so offer to + // reduce collection of data that can identify users. + const reduceDataCollection = + sdkSupportsDataCollection(installedSdkVersion, "^11") && + (await askShouldReduceDataCollection()); + + const selectedFeatures = await featureSelectionPrompt([ + { + id: "performance", + prompt: `Do you want to enable ${chalk.bold( + "Tracing", + )} to track the performance of your application?`, + enabledHint: "recommended", + }, + { + id: "replay", + prompt: `Do you want to enable ${chalk.bold( + "Session Replay", + )} to get a video-like reproduction of errors during a user session?`, + enabledHint: "recommended, but increases bundle size", + }, + ] as const); + + await traceStep( + "Initialize Sentry on Angular application entry point", + async () => { + await initializeSentryOnApplicationEntry( + dsn, + selectedFeatures, + reduceDataCollection, + ); + }, + ); + + await traceStep("Update Angular project configuration", async () => { + await updateAppConfig(installedMinVersion, selectedFeatures.performance); + }); + + await traceStep("Setup for sourcemap uploads", async () => { + await addSourcemapEntryToAngularJSON(); + + // sentry-wizard ran its source maps wizard with the Angular tool + // preselected here. Its other steps (redirect to a framework wizard, SDK + // version check, project selection) are already done by this point, so + // run the Angular tool setup and the CI step directly. + await configureSentryCLI( + { + orgSlug: selectedProject.organization.slug, + projectSlug: selectedProject.slug, + selfHosted, + url: sentryUrl, + authToken, + defaultArtifactPath: `.${path.sep}dist`, + forceInstall: options.forceInstall, + }, + configureAngularSourcemapGenerationFlow, + true, + ); + + await setupCI("angular", authToken, { + org: selectedProject.organization.slug, + project: selectedProject.slug, + url: selfHosted ? sentryUrl : undefined, + }); + }); + + const shouldCreateExampleComponent = await askShouldCreateExampleComponent(); + + Sentry.setTag("create-example-component", shouldCreateExampleComponent); + + if (shouldCreateExampleComponent) { + await traceStep( + "create-example-component", + async () => + await createExampleComponent({ + orgSlug: selectedProject.organization.slug, + projectId: selectedProject.id, + }), + ); + } + + await traceStep("Run Prettier", async () => { + await runPrettierIfInstalled({ cwd: undefined }); + }); + + // Offer optional project-scoped MCP config for Sentry with org and project scope + await offerProjectScopedMcpConfig( + selectedProject.organization.slug, + selectedProject.slug, + ); + + clack.outro(buildOutroMessage(shouldCreateExampleComponent)); +} + +/** The closing message, with how to test the example component if one was created. */ +export function buildOutroMessage(createdExampleComponent: boolean): string { + let msg = chalk.green("Successfully installed the Sentry Angular SDK!"); + + if (createdExampleComponent) { + msg += `\n\nYou can validate your setup by starting your dev environment (${chalk.cyan( + "ng serve", + )}) and throwing an error in the example component.`; + } + + msg += `\n\nCheck out the SDK documentation for further configuration: +https://docs.sentry.io/platforms/javascript/guides/angular/`; + + return msg; +} diff --git a/packages/cli/src/lib/wizard/angular/codemods/app-config.ts b/packages/cli/src/lib/wizard/angular/codemods/app-config.ts new file mode 100644 index 000000000..18f8ae768 --- /dev/null +++ b/packages/cli/src/lib/wizard/angular/codemods/app-config.ts @@ -0,0 +1,281 @@ +/** + * Codemod for the Angular app config (`src/app/app.config.ts`): adds the + * Sentry `ErrorHandler` provider and, with tracing, the `TraceService` and + * its app initializer (`provideAppInitializer` from Angular 19 on, + * `APP_INITIALIZER` before). + */ + +import type { namedTypes as t } from "ast-types"; +import chalk from "chalk"; +import type { ProxifiedModule } from "magicast"; +import recast from "recast"; +import { gte, type SemVer } from "semver"; +import { clack } from "../../utils/clack/prompts.js"; + +/** Add the Sentry imports and providers to the app config module. */ +export function updateAppConfigMod( + originalAppConfigMod: ProxifiedModule, + angularVersion: SemVer, + isTracingEnabled: boolean, +): ProxifiedModule { + const isAboveAngularV19 = gte(angularVersion, "19.0.0"); + + addImports(originalAppConfigMod, isAboveAngularV19, isTracingEnabled); + if ( + !addProviders(originalAppConfigMod, isAboveAngularV19, isTracingEnabled) + ) { + throw new Error( + "Could not find a `providers` array in `export const appConfig`.", + ); + } + + return originalAppConfigMod; +} +function addSentryImport(originalAppConfigMod: ProxifiedModule): void { + const imports = originalAppConfigMod.imports; + const hasSentryImport = imports.$items.some( + (item) => item.from === "@sentry/angular", + ); + + if (!hasSentryImport) { + imports.$add({ + from: "@sentry/angular", + imported: "*", + local: "Sentry", + }); + } +} + +function addErrorHandlerImport(originalAppConfigMod: ProxifiedModule): void { + const imports = originalAppConfigMod.imports; + const hasErrorHandler = imports.$items.some( + (item) => item.local === "ErrorHandler" && item.from === "@angular/core", + ); + + if (!hasErrorHandler) { + imports.$add({ + from: "@angular/core", + imported: "ErrorHandler", + local: "ErrorHandler", + }); + } +} +function addRouterImport(originalAppConfigMod: ProxifiedModule): void { + const imports = originalAppConfigMod.imports; + const hasRouter = imports.$items.some( + (item) => item.local === "Router" && item.from === "@angular/router", + ); + + if (!hasRouter) { + imports.$add({ + from: "@angular/router", + imported: "Router", + local: "Router", + }); + } +} + +function addMissingImportsV19(originalAppConfigMod: ProxifiedModule): void { + const imports = originalAppConfigMod.imports; + + const hasProvideAppInitializer = imports.$items.some( + (item) => + item.local === "provideAppInitializer" && item.from === "@angular/core", + ); + + if (!hasProvideAppInitializer) { + imports.$add({ + from: "@angular/core", + imported: "provideAppInitializer", + local: "provideAppInitializer", + }); + } + + const hasInject = imports.$items.some( + (item) => item.local === "inject" && item.from === "@angular/core", + ); + + if (!hasInject) { + imports.$add({ + from: "@angular/core", + imported: "inject", + local: "inject", + }); + } +} +function addAppInitializer(originalAppConfigMod: ProxifiedModule): void { + const imports = originalAppConfigMod.imports; + + const hasAppInitializer = imports.$items.some( + (item) => item.local === "APP_INITIALIZER" && item.from === "@angular/core", + ); + + if (!hasAppInitializer) { + imports.$add({ + from: "@angular/core", + imported: "APP_INITIALIZER", + local: "APP_INITIALIZER", + }); + } +} + +function addImports( + originalAppConfigMod: ProxifiedModule, + isAboveAngularV19: boolean, + isTracingEnabled: boolean, +): void { + addSentryImport(originalAppConfigMod); + addErrorHandlerImport(originalAppConfigMod); + + if (isTracingEnabled) { + addRouterImport(originalAppConfigMod); + } + + // Both helpers import only what the tracing providers use. + if (isTracingEnabled) { + if (isAboveAngularV19) { + addMissingImportsV19(originalAppConfigMod); + } else { + addAppInitializer(originalAppConfigMod); + } + } +} + +function addProviders( + originalAppConfigMod: ProxifiedModule, + isAboveAngularV19: boolean, + isTracingEnabled: boolean, +): boolean { + const b = recast.types.builders; + let foundProviders = false; + + recast.visit(originalAppConfigMod.exports.$ast, { + visitExportNamedDeclaration(path) { + if ( + path.node.declaration?.type !== "VariableDeclaration" || + path.node.declaration.declarations[0]?.type !== "VariableDeclarator" || + path.node.declaration.declarations[0].id.type !== "Identifier" || + path.node.declaration.declarations[0].id.name !== "appConfig" || + path.node.declaration.declarations[0].init?.type !== "ObjectExpression" + ) { + return false; + } + + const appConfigProps = + path.node.declaration.declarations[0].init.properties; + + const providersProperty = appConfigProps.find( + (prop) => + prop.type === "ObjectProperty" && + prop.key.type === "Identifier" && + prop.key.name === "providers", + // type cast is safe because we already check the type in the find condition + ) as t.ObjectProperty | undefined; + + const validProviders = + providersProperty?.value.type === "ArrayExpression" + ? providersProperty.value + : undefined; + + if (!validProviders) { + return false; + } + foundProviders = true; + + // Check if there is already an ErrorHandler provider + const hasErrorHandlerProvider = validProviders.elements.some( + (element) => + element?.type === "ObjectExpression" && + element.properties.some( + (prop) => + prop.type === "ObjectProperty" && + prop.key.type === "Identifier" && + prop.key.name === "provide" && + prop.value.type === "Identifier" && + prop.value.name === "ErrorHandler", + ), + ); + + // If there is already an ErrorHandler provider, we skip adding it and log a message + if (hasErrorHandlerProvider) { + clack.log.warn(`ErrorHandler provider already exists in your app config. +Please refer to the Sentry Angular SDK documentation to combine it manually with Sentry's ErrorHandler. +${chalk.underline( + "https://docs.sentry.io/platforms/javascript/guides/angular/features/error-handler/", +)} +`); + } else { + const errorHandlerObject = b.objectExpression([ + b.objectProperty( + b.identifier("provide"), + b.identifier("ErrorHandler"), + ), + b.objectProperty( + b.identifier("useValue"), + b.identifier("Sentry.createErrorHandler()"), + ), + ]); + + validProviders.elements.push(errorHandlerObject); + } + + if (isTracingEnabled) { + const traceServiceObject = b.objectExpression([ + b.objectProperty( + b.identifier("provide"), + b.identifier("Sentry.TraceService"), + ), + b.objectProperty( + b.identifier("deps"), + b.arrayExpression([b.identifier("Router")]), + ), + ]); + validProviders.elements.push(traceServiceObject); + + if (isAboveAngularV19) { + const provideAppInitializerCall = b.callExpression( + b.identifier("provideAppInitializer"), + [ + b.arrowFunctionExpression( + [], + b.blockStatement([ + b.expressionStatement( + b.callExpression(b.identifier("inject"), [ + b.identifier("Sentry.TraceService"), + ]), + ), + ]), + ), + ], + ); + validProviders.elements.push(provideAppInitializerCall); + } else { + const provideAppInitializerObject = b.objectExpression([ + b.objectProperty( + b.identifier("provide"), + b.identifier("APP_INITIALIZER"), + ), + b.objectProperty( + b.identifier("useFactory"), + b.arrowFunctionExpression( + [], + b.arrowFunctionExpression([], b.blockStatement([])), + ), + ), + b.objectProperty( + b.identifier("deps"), + b.arrayExpression([b.identifier("Sentry.TraceService")]), + ), + b.objectProperty(b.identifier("multi"), b.booleanLiteral(true)), + ]); + validProviders.elements.push(provideAppInitializerObject); + } + } + + this.traverse(path); + return false; + }, + }); + + return foundProviders; +} diff --git a/packages/cli/src/lib/wizard/angular/codemods/main.ts b/packages/cli/src/lib/wizard/angular/codemods/main.ts new file mode 100644 index 000000000..637f9ba3b --- /dev/null +++ b/packages/cli/src/lib/wizard/angular/codemods/main.ts @@ -0,0 +1,129 @@ +/** + * Codemod for the Angular application entry (`src/main.ts`): imports + * `@sentry/angular` and inserts `Sentry.init()` after the imports. + */ + +import type { namedTypes as t } from "ast-types"; +import { + builders, + generateCode, + type Proxified, + type ProxifiedModule, +} from "magicast"; +import { getDataCollectionSnippet } from "../../utils/data-collection.js"; + +/** Add the Sentry import and `Sentry.init()` call to the entry module. */ +export function updateAppEntryMod( + originalAppModuleMod: ProxifiedModule, + dsn: string, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + reduceDataCollection: boolean, +): ProxifiedModule { + originalAppModuleMod.imports.$add({ + from: "@sentry/angular", + imported: "*", + local: "Sentry", + }); + + insertInitCall( + originalAppModuleMod, + dsn, + selectedFeatures, + reduceDataCollection, + ); + + return originalAppModuleMod; +} + +/** Insert `Sentry.init()` with the selected features after the last import. */ +function insertInitCall( + originalAppModuleMod: ProxifiedModule, + dsn: string, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + reduceDataCollection: boolean, +): void { + const initCallArgs = getInitCallArgs(dsn, selectedFeatures); + const initCall = builders.functionCall("Sentry.init", initCallArgs); + const originalAppModuleModAst = originalAppModuleMod.$ast as t.Program; + + const initCallInsertionIndex = getAfterImportsInsertionIndex( + originalAppModuleModAst, + ); + const generatedInitCode = generateCode(initCall).code; + // Magicast can't express comments inside an options object, so splice the + // commented `dataCollection` preset into the generated code before the + // closing `})`. + const initCode = reduceDataCollection + ? generatedInitCode.replace( + /\n\}\)$/, + `,\n${getDataCollectionSnippet(" ")}\n})`, + ) + : generatedInitCode; + + // magicast's proxied AST turns a code string into its statement node. + originalAppModuleModAst.body.splice( + initCallInsertionIndex, + 0, + initCode as unknown as (typeof originalAppModuleModAst.body)[number], + ); +} + +type InitCallArgs = Record< + string, + string | number | boolean | Array | Record +>; + +/** The options object of `Sentry.init()` for the selected features. */ +export function getInitCallArgs( + dsn: string, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, +): InitCallArgs { + const initCallArgs: InitCallArgs = { + dsn, + }; + + if (selectedFeatures.replay || selectedFeatures.performance) { + const integrations: Proxified[] = []; + initCallArgs["integrations"] = integrations; + + if (selectedFeatures.performance) { + integrations.push( + builders.functionCall("Sentry.browserTracingIntegration"), + ); + initCallArgs["tracesSampleRate"] = 1.0; + } + + if (selectedFeatures.replay) { + integrations.push(builders.functionCall("Sentry.replayIntegration")); + + initCallArgs["replaysSessionSampleRate"] = 0.1; + initCallArgs["replaysOnErrorSampleRate"] = 1.0; + } + } + + return initCallArgs; +} + +/** + * We want to insert the handleError function just after all imports + */ +function getAfterImportsInsertionIndex( + originalEntryServerModAST: t.Program, +): number { + for (let x = originalEntryServerModAST.body.length - 1; x >= 0; x--) { + if (originalEntryServerModAST.body[x]?.type === "ImportDeclaration") { + return x + 1; + } + } + + return 0; +} diff --git a/packages/cli/src/lib/wizard/angular/codemods/sourcemaps.ts b/packages/cli/src/lib/wizard/angular/codemods/sourcemaps.ts new file mode 100644 index 000000000..2c7768696 --- /dev/null +++ b/packages/cli/src/lib/wizard/angular/codemods/sourcemaps.ts @@ -0,0 +1,110 @@ +/** + * Turn on source maps for the production build of every project in + * `angular.json`, or show the manual steps when that file can't be edited. + */ + +import { readFileSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { reportCliError } from "../../../error-reporting.js"; +import { configureAngularSourcemapGenerationFlow } from "../../sourcemaps/tools/angular.js"; +import { clack } from "../../utils/clack/prompts.js"; +import { debug } from "../../utils/debug.js"; + +interface PartialAngularJson { + projects?: Record< + string, + { + architect?: { + build?: { + configurations?: { + production?: { + sourceMap?: boolean; + } & Record; + }; + }; + }; + } + >; +} + +/** Set `sourceMap: true` on the production build of each `angular.json` project. */ +export async function addSourcemapEntryToAngularJSON(): Promise { + const angularJsonPath = path.join(process.cwd(), "angular.json"); + const angularJson = getParsedAngularJson(angularJsonPath); + + if (!angularJson || typeof angularJson !== "object") { + await configureAngularSourcemapGenerationFlow(); + return; + } + + const updatedAngularJson = addSourceMapsSetting(angularJson); + + if (!updatedAngularJson) { + await configureAngularSourcemapGenerationFlow(); + return; + } + + try { + writeFileSync(angularJsonPath, JSON.stringify(updatedAngularJson, null, 2)); + } catch (error) { + clack.log.error(`Failed to write sourcemap configuration to angular.json`); + reportCliError(error); + await configureAngularSourcemapGenerationFlow(); + } +} + +/** + * Extracted from `addSourcemapEntryToAngularJSON` and exported to allow for easier testing. + */ +export function addSourceMapsSetting( + angularJson: PartialAngularJson, +): PartialAngularJson | undefined { + const newAngularJson = { ...angularJson }; + + const projectKeys = Object.keys(newAngularJson.projects || {}); + + if (!projectKeys.length || !newAngularJson.projects) { + return undefined; + } + + // Emit sourcemaps from all projects in angular.json + for (const projectKey of projectKeys) { + const projectConfig = newAngularJson.projects[projectKey]; + if (!projectConfig) { + continue; + } + + if (!projectConfig.architect) { + projectConfig.architect = {}; + } + + if (!projectConfig.architect.build) { + projectConfig.architect.build = {}; + } + + if (!projectConfig.architect.build.configurations) { + projectConfig.architect.build.configurations = {}; + } + + projectConfig.architect.build.configurations.production = { + ...projectConfig.architect.build.configurations.production, + sourceMap: true, + }; + } + + return newAngularJson; +} + +function getParsedAngularJson( + angularJsonPath: string, +): PartialAngularJson | undefined { + try { + const angularJSONFile = readFileSync(angularJsonPath, "utf-8"); + return JSON.parse(angularJSONFile) as PartialAngularJson | undefined; + } catch (error) { + // Not fatal: without a readable angular.json, the caller shows the + // manual steps instead. A missing or hand-broken file is not a bug. + debug(error); + return undefined; + } +} diff --git a/packages/cli/src/lib/wizard/angular/example-component.ts b/packages/cli/src/lib/wizard/angular/example-component.ts new file mode 100644 index 000000000..ba578d155 --- /dev/null +++ b/packages/cli/src/lib/wizard/angular/example-component.ts @@ -0,0 +1,302 @@ +/** + * Create an example Angular component that throws a test error, and show + * how to add it to a page. + */ + +import { existsSync, mkdirSync, writeFileSync } from "node:fs"; +import chalk from "chalk"; +import { + abortIfCancelled, + makeCodeSnippet, + showCopyPasteInstructions, +} from "../utils/clack/index.js"; +import { clack } from "../utils/clack/prompts.js"; +import { buildProjectIssuesUrl } from "../../sentry-web-urls.js"; + +interface ExampleComponentOptions { + orgSlug: string; + projectId: string; +} + +/** Write `sentry-example.component.ts` and show how to use it. */ +export async function createExampleComponent( + options: ExampleComponentOptions, +): Promise { + const componentName = "sentry-example"; + const appRootPath = "./src/app"; + + let componentDirPath = appRootPath; + const hasAppRoot = existsSync(appRootPath); + if (!hasAppRoot) { + componentDirPath = await abortIfCancelled( + clack.text({ + message: "Where should we create the example component?", + placeholder: appRootPath, + validate(value) { + if (!value) { + return "Please enter a path."; + } + return undefined; + }, + }), + ); + } + + if (!existsSync(componentDirPath)) { + mkdirSync(componentDirPath, { recursive: true }); + } + + const componentCode = getSentryExampleComponentCode(options); + + const componentFilePath = `${componentDirPath}/${componentName}.component.ts`; + + writeFileSync(componentFilePath, componentCode); + + clack.log.success( + `Created example component at ${chalk.cyan(componentFilePath)}`, + ); + + const addComponentCodeSnippet = makeCodeSnippet(true, (unchanged, plus) => + unchanged(`${plus( + "import { SentryExample } from './sentry-example.component'", + )} + +@Component({ + selector: 'app-root', + standalone: true, + imports: [RouterOutlet, ${plus("SentryExample")}], + template: \` +
+

Your Application

+ ${plus("")} +
+ \`, +}) +`), + ); + + await showCopyPasteInstructions({ + instructions: `Add the example component one of your pages or components (for example, in ${chalk.cyan( + "app.component.ts", + )}).`, + codeSnippet: addComponentCodeSnippet, + }); +} + +/** The source of the example component. */ +export function getSentryExampleComponentCode( + options: ExampleComponentOptions, +): string { + const issueStreamUrl = buildProjectIssuesUrl( + options.orgSlug, + options.projectId, + ); + + return `import { NgIf } from '@angular/common'; +import { Component, OnInit } from '@angular/core'; +import * as Sentry from '@sentry/angular'; + +/** + * This is just a very simple component that throws an example error. + * Feel free to delete this file once you verify that Sentry is working. + */ + +@Component({ + selector: 'app-sentry-example', + standalone: true, + imports: [NgIf], + template: \` + + + + +

app-sentry-example

+ +

+ Click the button below, and view the sample error on the Sentry + Issues Page. For more details about setting up Sentry, + read our docs. +

+ + + +
+ Sample error was sent to Sentry. +
+
+ +
+

+ The Sentry SDK is not able to reach Sentry right now - this may be due + to an adblocker. For more information, see + the troubleshooting guide. +

+
+ +

+ Adblockers will prevent errors from being sent to Sentry. +

+ \`, + styles: \` + :host { + display: flex; + flex-direction: column; + justify-content: space-between; + align-items: center; + border: 2px solid #553DB8; + border-radius: 8px; + padding: 1em; + margin: 0.5em; + width: 500px; + height: 495px; + gap: 1em; + } + + h1 { + padding: 0px 4px; + border-radius: 4px; + background-color: rgba(24, 20, 35, 0.03); + font-family: monospace; + font-size: 20px; + line-height: 1.2; + } + + p { + margin: 0; + font-size: 20px; + } + + a { + color: #6341F0; + text-decoration: underline; + cursor: pointer; + + @media (prefers-color-scheme: dark) { + color: #B3A1FF; + } + } + + button { + border-radius: 8px; + color: white; + cursor: pointer; + background-color: #553DB8; + border: none; + padding: 0; + margin-top: 4px; + + & > span { + display: inline-block; + padding: 12px 16px; + border-radius: inherit; + font-size: 20px; + font-weight: bold; + line-height: 1; + background-color: #7553FF; + border: 1px solid #553DB8; + transform: translateY(-4px); + } + + &:hover > span { + transform: translateY(-8px); + } + + &:active > span { + transform: translateY(0); + } + } + + .success { + padding: 12px 16px; + border-radius: 8px; + font-size: 20px; + line-height: 1; + background-color: #00F261; + border: 1px solid #00BF4D; + color: #181423; + } + + .success_placeholder { + height: 46px; + } + + .description { + text-align: center; + color: #6E6C75; + max-width: 500px; + line-height: 1.5; + font-size: 20px; + + @media (prefers-color-scheme: dark) { + color: #A49FB5; + } + } + + .connectivity-error { + padding: 12px 16px; + background-color: #E50045; + border-radius: 8px; + width: 500px; + color: #FFFFFF; + border: 1px solid #A80033; + text-align: center; + margin: 0; + max-width: 400px; + } + + .connectivity-error a { + color: #FFFFFF; + text-decoration: underline; + } + \`, +}) +export class SentryExample implements OnInit { + sentError = false; + isConnected = true; + + async ngOnInit(): Promise { + const res = await Sentry.diagnoseSdkConnectivity(); + this.isConnected = res !== 'sentry-unreachable'; + } + + throwError() { + Sentry.startSpan( + { + name: 'Example Frontend Span', + op: 'test', + }, + () => { + this.sentError = true; + throw new SentryExampleError( + 'This error was thrown by the Sentry example component.' + ); + } + ); + } +} + +class SentryExampleError extends Error { + constructor(message: string | undefined) { + super(message); + this.name = 'SentryExampleError'; + } +} +`; +} diff --git a/packages/cli/src/lib/wizard/angular/sdk-setup.ts b/packages/cli/src/lib/wizard/angular/sdk-setup.ts new file mode 100644 index 000000000..e5e12dae9 --- /dev/null +++ b/packages/cli/src/lib/wizard/angular/sdk-setup.ts @@ -0,0 +1,180 @@ +/** + * Add Sentry to an Angular app: `Sentry.init()` in `src/main.ts` and the + * Sentry providers in `src/app/app.config.ts`. + */ + +import { existsSync } from "node:fs"; +import path from "node:path"; +import type { namedTypes as t } from "ast-types"; +import chalk from "chalk"; +import { loadFile, writeFile } from "magicast"; +import type { SemVer } from "semver"; +import { Sentry } from "../telemetry.js"; +import { hasSentryContent } from "../utils/ast-utils.js"; +import { clack } from "../utils/clack/prompts.js"; +import { debug } from "../utils/debug.js"; +import { updateAppConfigMod } from "./codemods/app-config.js"; +import { updateAppEntryMod } from "./codemods/main.js"; + +/** Import Sentry and call `Sentry.init()` in `src/main.ts`. */ +export async function initializeSentryOnApplicationEntry( + dsn: string, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + reduceDataCollection: boolean, +): Promise { + const appEntryFilename = "main.ts"; + const appEntryPath = path.join(process.cwd(), "src", appEntryFilename); + + let originalAppEntry: Awaited>; + try { + originalAppEntry = await loadFile(appEntryPath); + } catch (error: unknown) { + // Not fatal: the user gets the manual setup steps instead. + debug(error); + clack.log.error( + `Could not read ${chalk.cyan(path.join("src", appEntryFilename))}.`, + ); + clack.log.warn( + `Please refer to the documentation for manual setup: +${chalk.underline( + "https://docs.sentry.io/platforms/javascript/guides/angular/#configure", +)}`, + ); + return; + } + + if (hasSentryContent(originalAppEntry.$ast as t.Program)) { + clack.log.warn( + `File ${chalk.cyan(appEntryFilename)} already contains Sentry. +Skipping adding Sentry functionality to ${chalk.cyan(appEntryFilename)}.`, + ); + + return; + } + + const updatedAppEntryMod = updateAppEntryMod( + originalAppEntry, + dsn, + selectedFeatures, + reduceDataCollection, + ); + + try { + await writeFile(updatedAppEntryMod.$ast, appEntryPath); + } catch (error: unknown) { + // Not fatal: the user gets the manual setup steps instead. + debug(error); + clack.log.error( + `Error while adding Sentry to ${chalk.cyan(appEntryFilename)}`, + ); + + clack.log.warn( + `Please refer to the documentation for manual setup: +${chalk.underline( + "https://docs.sentry.io/platforms/javascript/guides/angular/#configure", +)}`, + ); + + return; + } + + clack.log.success( + `Successfully initialized Sentry in ${chalk.cyan(appEntryFilename)}`, + ); +} + +/** Add the Sentry providers to `src/app/app.config.ts`. */ +export async function updateAppConfig( + angularVersion: SemVer, + isTracingEnabled: boolean, +): Promise { + const appConfigFilename = "app.config.ts"; + const appConfigPath = path.join( + process.cwd(), + "src", + "app", + appConfigFilename, + ); + + if (!existsSync(appConfigPath)) { + Sentry.setTag("angular-app-config-found", false); + + clack.log.warn( + `File ${chalk.cyan( + appConfigFilename, + )} not found. Skipping adding Sentry functionality.`, + ); + + clack.log.warn(`Please refer to the documentation for manual setup: +${chalk.underline( + "https://docs.sentry.io/platforms/javascript/guides/angular/#configure", +)}`); + + return; + } + + Sentry.setTag("angular-app-config-found", true); + + let appConfig: Awaited>; + try { + appConfig = await loadFile(appConfigPath); + } catch (error: unknown) { + // Not fatal: the user gets the manual setup steps instead. + debug(error); + clack.log.error(`Could not read ${chalk.cyan(appConfigFilename)}.`); + clack.log.warn( + `Please refer to the documentation for manual setup: +${chalk.underline( + "https://docs.sentry.io/platforms/javascript/guides/angular/#configure", +)}`, + ); + return; + } + + if (hasSentryContent(appConfig.$ast as t.Program)) { + clack.log.warn( + `File ${chalk.cyan(appConfigFilename)} already contains Sentry. + Skipping adding Sentry functionality to ${chalk.cyan(appConfigFilename)}.`, + ); + + return; + } + + try { + const updatedAppConfigMod = updateAppConfigMod( + appConfig, + angularVersion, + isTracingEnabled, + ); + + await writeFile(updatedAppConfigMod.$ast, appConfigPath); + } catch (error: unknown) { + clack.log.error( + `Error while updating your app config ${chalk.cyan(appConfigFilename)}.`, + ); + + clack.log.info( + chalk.dim( + error instanceof Error + ? error.toString() + : typeof error === "string" + ? error + : "", + ), + ); + + clack.log.warn(`Please refer to the documentation for manual setup: +${chalk.underline( + "https://docs.sentry.io/platforms/javascript/guides/angular/#configure", +)}`); + + return; + } + + clack.log.success( + `Successfully updated your app config ${chalk.cyan(appConfigFilename)}`, + ); +} diff --git a/packages/cli/src/lib/wizard/nuxt/nuxt-wizard.ts b/packages/cli/src/lib/wizard/nuxt/nuxt-wizard.ts new file mode 100644 index 000000000..48f3e33df --- /dev/null +++ b/packages/cli/src/lib/wizard/nuxt/nuxt-wizard.ts @@ -0,0 +1,238 @@ +/** + * The Nuxt setup wizard: installs `@sentry/nuxt`, adds the Sentry Nuxt + * module to the Nuxt config, writes the client and server SDK configs and + * the auth token for source map uploads, and optionally creates an example + * page or component. + */ + +import chalk from "chalk"; +import { lt } from "semver"; +import { Sentry, traceStep, withTelemetry } from "../telemetry.js"; +import { abortIfSpotlightNotSupported } from "../utils/abort-if-sportlight-not-supported.js"; +import { + abort, + abortIfCancelled, + addDotEnvSentryBuildPluginFile, + askShouldCreateExampleComponent, + askShouldCreateExamplePage, + confirmContinueIfNoOrDirtyGitRepo, + ensurePackageIsInstalled, + getOrAskForProjectData, + getPackageDotJson, + getPackageManager, + installPackage, + printSdkV11MigrationGuideIfOutdated, + printWelcome, + runPrettierIfInstalled, +} from "../utils/clack/index.js"; +import { offerProjectScopedMcpConfig } from "../utils/clack/mcp-config.js"; +import { clack } from "../utils/clack/prompts.js"; +import { + askShouldReduceDataCollection, + sdkSupportsDataCollection, +} from "../utils/data-collection.js"; +import { warnIfNodeVersionUnsupportedBySdkV11 } from "../utils/node-version.js"; +import { + getPackageVersion, + hasPackageInstalled, +} from "../utils/package-json.js"; +import { safeMinVersion } from "../utils/semver.js"; +import type { WizardOptions } from "../utils/types.js"; +import { + createExampleComponent, + createExamplePage, + supportsExamplePage, +} from "./sdk-example.js"; +import { + addNuxtOverrides, + addSDKModule, + createConfigFiles, + getNuxtConfig, +} from "./sdk-setup.js"; +import { isNuxtV4 } from "./utils.js"; + +/** Run the Nuxt wizard (`sentry wizard nuxt`). */ +export async function runNuxtWizard(options: WizardOptions): Promise { + return await withTelemetry( + { + enabled: options.telemetryEnabled, + integration: "nuxt", + wizardOptions: options, + }, + () => runNuxtWizardWithTelemetry(options), + ); +} + +async function runNuxtWizardWithTelemetry( + options: WizardOptions, +): Promise { + const { telemetryEnabled, forceInstall } = options; + + printWelcome({ + wizardName: "Sentry Nuxt Wizard", + telemetryEnabled, + }); + + warnIfNodeVersionUnsupportedBySdkV11(); + + await confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: options.ignoreGitChanges, + cwd: undefined, + }); + + const packageJson = await getPackageDotJson(); + + await ensurePackageIsInstalled(packageJson, "nuxt", "Nuxt"); + + const nuxtVersion = getPackageVersion("nuxt", packageJson); + Sentry.setTag("nuxt-version", nuxtVersion); + + const minVer = safeMinVersion(nuxtVersion || "0.0.0"); + + if (!nuxtVersion || !minVer || lt(minVer, "3.7.0")) { + clack.log.warn( + "It seems you're using a Nuxt version <3.7.0 which is not supported by Sentry.\nWe recommend upgrading to the latest version before you continue.", + ); + const shouldContinue = await abortIfCancelled( + clack.select({ + message: "Do you want to continue anyway?", + options: [ + { + label: "Yes, continue", + hint: "The SDK might not work correctly", + value: true, + }, + { label: "No, I'll upgrade first", value: false }, + ], + }), + ); + if (!shouldContinue) { + await abort("Exiting Wizard", 0); + return; + } + } + + const projectDataResult = await getOrAskForProjectData( + options, + "javascript-nuxt", + ); + + if (projectDataResult.spotlight) { + return await abortIfSpotlightNotSupported("Nuxt"); + } + + const { authToken, selectedProject, selfHosted, sentryUrl } = + projectDataResult; + + const packageManager = await getPackageManager(); + + await addNuxtOverrides(packageManager, minVer); + + const sdkAlreadyInstalled = hasPackageInstalled("@sentry/nuxt", packageJson); + Sentry.setTag("sdk-already-installed", sdkAlreadyInstalled); + + printSdkV11MigrationGuideIfOutdated("@sentry/nuxt", packageJson); + + await installPackage({ + packageName: "@sentry/nuxt@^11", + alreadyInstalled: sdkAlreadyInstalled, + packageManager, + forceInstall, + }); + + // The install may have been skipped (user declined the update prompt), so + // re-read package.json to learn which SDK major is actually installed. + const installedSdkVersion = getPackageVersion( + "@sentry/nuxt", + await getPackageDotJson(), + ); + + // From v11 on, the SDK collects rich context by default, so offer to + // reduce collection of data that can identify users. + const reduceDataCollection = + sdkSupportsDataCollection(installedSdkVersion, "^11") && + (await askShouldReduceDataCollection()); + + await addDotEnvSentryBuildPluginFile(authToken); + + const nuxtConfig = await traceStep("load-nuxt-config", getNuxtConfig); + + const projectData = { + org: selectedProject.organization.slug, + project: selectedProject.slug, + projectId: selectedProject.id, + url: sentryUrl, + selfHosted, + }; + + await traceStep("configure-sdk", async () => { + await addSDKModule(nuxtConfig, projectData); + await createConfigFiles( + selectedProject.keys[0].dsn.public, + reduceDataCollection, + ); + }); + + let shouldCreateExamplePage = false; + let shouldCreateExampleButton = false; + + const isV4 = await isNuxtV4(nuxtConfig, nuxtVersion); + const canCreateExamplePage = await supportsExamplePage(isV4); + Sentry.setTag("supports-example-page-creation", canCreateExamplePage); + + if (canCreateExamplePage) { + shouldCreateExamplePage = await askShouldCreateExamplePage(); + + if (shouldCreateExamplePage) { + await traceStep( + "create-example-page", + async () => await createExamplePage(isV4, projectData), + ); + } + } else { + shouldCreateExampleButton = await askShouldCreateExampleComponent(); + + if (shouldCreateExampleButton) { + await traceStep( + "create-example-component", + async () => await createExampleComponent(isV4), + ); + } + } + + await runPrettierIfInstalled({ cwd: undefined }); + + // Offer optional project-scoped MCP config for Sentry with org and project scope + await offerProjectScopedMcpConfig( + selectedProject.organization.slug, + selectedProject.slug, + ); + + clack.outro( + buildOutroMessage(shouldCreateExamplePage, shouldCreateExampleButton), + ); +} + +export function buildOutroMessage( + shouldCreateExamplePage: boolean, + shouldCreateExampleButton: boolean, +): string { + let msg = chalk.green("Successfully installed the Sentry Nuxt SDK!"); + + if (shouldCreateExamplePage) { + msg += `\n\nYou can validate your setup by visiting ${chalk.cyan( + '"/sentry-example-page"', + )}.`; + } + if (shouldCreateExampleButton) { + msg += `\n\nYou can validate your setup by adding the ${chalk.cyan( + "`SentryErrorButton`", + )} component to a page and triggering it.`; + } + + msg += `\n\nCheck out the SDK documentation for further configuration: ${chalk.underline( + "https://docs.sentry.io/platforms/javascript/guides/nuxt/", + )}`; + + return msg; +} diff --git a/packages/cli/src/lib/wizard/nuxt/sdk-example.ts b/packages/cli/src/lib/wizard/nuxt/sdk-example.ts new file mode 100644 index 000000000..5e71c72a0 --- /dev/null +++ b/packages/cli/src/lib/wizard/nuxt/sdk-example.ts @@ -0,0 +1,169 @@ +/** + * Create the Nuxt example page (with its API route) or the example error + * button component that the user can trigger to test Sentry. + */ + +import { existsSync, mkdirSync, promises } from "node:fs"; +import path from "node:path"; +import chalk from "chalk"; +import { reportCliError } from "../../error-reporting.js"; +import { abort, isUsingTypeScript } from "../utils/clack/index.js"; +import { clack } from "../utils/clack/prompts.js"; +import { + getIndexRouteTemplate, + getSentryErrorButtonTemplate, + getSentryExampleApiTemplate, + getSentryExamplePageTemplate, +} from "./templates.js"; + +function getSrcDirectory(isNuxtV4: boolean): string { + if (!isNuxtV4 || existsSync(path.resolve("pages"))) { + return "."; + } + // Nuxt 4 defaults the src directory to `app/`. A root `app.vue` with no + // `app/` directory means the project keeps a root `srcDir`. + if (!existsSync(path.resolve("app")) && existsSync(path.resolve("app.vue"))) { + return "."; + } + return "app"; +} + +/** Whether the app renders pages, so an example page would be reachable. */ +export async function supportsExamplePage(isNuxtV4: boolean): Promise { + // We currently only support creating an example page + // if users can reliably access it without having to + // add code changes themselves. + // + // If users have an `app.vue` layout without the + // needed component to render routes (), + // we bail out of creating an example page altogether. + const src = getSrcDirectory(isNuxtV4); + const app = path.join(src, "app.vue"); + + // If there's no `app.vue` layout, nuxt automatically renders + // the routes. + if (!existsSync(path.resolve(app))) { + return true; + } + + const content = await promises.readFile(path.resolve(app), "utf8"); + return /<(?:NuxtPage|nuxt-page)[\s/>]/.test(content); +} + +/** Write the example page and its API route. */ +export async function createExamplePage( + isNuxtV4: boolean, + options: { + org: string; + project: string; + projectId: string; + url: string; + }, +): Promise { + try { + const src = getSrcDirectory(isNuxtV4); + const pages = path.join(src, "pages"); + + if (!existsSync(path.resolve(pages))) { + mkdirSync(path.resolve(pages), { recursive: true }); + + const indexPage = path.join(pages, "index.vue"); + + await promises.writeFile( + path.resolve(indexPage), + getIndexRouteTemplate(), + ); + + clack.log.success(`Created ${chalk.cyan(indexPage)}.`); + } + + const examplePage = path.join(pages, "sentry-example-page.vue"); + + if (existsSync(path.resolve(examplePage))) { + clack.log.warn( + `It seems like a sentry example page already exists. Skipping creation of example page.`, + ); + } else { + await promises.writeFile( + path.resolve(examplePage), + getSentryExamplePageTemplate(options), + ); + + clack.log.success(`Created ${chalk.cyan(examplePage)}.`); + } + + const api = path.join("server", "api"); + + if (!existsSync(path.resolve(api))) { + mkdirSync(path.resolve(api), { recursive: true }); + } + + const exampleApi = path.join( + api, + isUsingTypeScript() ? "sentry-example-api.ts" : "sentry-example-api.js", + ); + + if (existsSync(path.resolve(exampleApi))) { + clack.log.warn( + `It seems like a sentry example API route already exists. Skipping creation of example API route.`, + ); + return; + } + + await promises.writeFile( + path.resolve(exampleApi), + getSentryExampleApiTemplate(), + ); + + clack.log.success(`Created ${chalk.cyan(exampleApi)}.`); + } catch (e: unknown) { + clack.log.error("Error while creating an example page to test Sentry:"); + clack.log.info( + chalk.dim( + e instanceof Error + ? e.toString() + : typeof e === "string" + ? e + : "Unknown error", + ), + ); + reportCliError(e); + await abort("Exiting Wizard"); + } +} + +/** Write the `SentryErrorButton` example component. */ +export async function createExampleComponent(isNuxtV4: boolean): Promise { + try { + const src = getSrcDirectory(isNuxtV4); + const components = path.join(src, "components"); + + if (!existsSync(path.resolve(components))) { + mkdirSync(path.resolve(components), { recursive: true }); + } + + const exampleComponent = path.join(components, "SentryErrorButton.vue"); + + await promises.writeFile( + path.resolve(exampleComponent), + getSentryErrorButtonTemplate(), + ); + + clack.log.success(`Created ${chalk.cyan(exampleComponent)}.`); + } catch (e: unknown) { + clack.log.error( + "Error while creating an example component to test Sentry:", + ); + clack.log.info( + chalk.dim( + e instanceof Error + ? e.toString() + : typeof e === "string" + ? e + : "Unknown error", + ), + ); + reportCliError(e); + await abort("Exiting Wizard"); + } +} diff --git a/packages/cli/src/lib/wizard/nuxt/sdk-setup.ts b/packages/cli/src/lib/wizard/nuxt/sdk-setup.ts new file mode 100644 index 000000000..3d8b8a978 --- /dev/null +++ b/packages/cli/src/lib/wizard/nuxt/sdk-setup.ts @@ -0,0 +1,324 @@ +/** + * Set up `@sentry/nuxt` in a Nuxt project: the Sentry Nuxt module in the + * Nuxt config, the client and server SDK configs, and the `ofetch` override + * that Nuxt before 3.14 needs. + */ + +import { existsSync, promises, unlinkSync } from "node:fs"; +import path from "node:path"; +import chalk from "chalk"; +import { generateCode, loadFile, type ProxifiedModule } from "magicast"; +import { addNuxtModule } from "magicast/helpers"; +import { lt, type SemVer } from "semver"; +import { Sentry, traceStep } from "../telemetry.js"; +import { + abort, + abortIfCancelled, + askShouldAddPackageOverride, + featureSelectionPrompt, + isUsingTypeScript, +} from "../utils/clack/index.js"; +import { clack } from "../utils/clack/prompts.js"; +import type { PackageManager } from "../utils/package-manager.js"; +import { + getConfigBody, + getDataCollectionBlock, + getDefaultNuxtConfig, + getNuxtModuleFallbackTemplate, + getSentryConfigContents, +} from "./templates.js"; + +const possibleNuxtConfig = [ + "nuxt.config.js", + "nuxt.config.mjs", + "nuxt.config.cjs", + "nuxt.config.ts", + "nuxt.config.mts", + "nuxt.config.cts", +]; + +/** + * The path of the Nuxt config file, after creating `nuxt.config.ts` when + * there is none. + */ +export async function getNuxtConfig(): Promise { + let configFile = possibleNuxtConfig.find((fileName) => + existsSync(path.join(process.cwd(), fileName)), + ); + + if (!configFile) { + clack.log.info("No Nuxt config file found, creating a new one."); + Sentry.setTag("nuxt-config-strategy", "create"); + // nuxt recommends its config to be .ts by default + configFile = "nuxt.config.ts"; + + await promises.writeFile( + path.join(process.cwd(), configFile), + getDefaultNuxtConfig(), + { encoding: "utf-8", flag: "w" }, + ); + + clack.log.success(`Created ${chalk.cyan("nuxt.config.ts")}.`); + } + + return path.join(process.cwd(), configFile); +} + +/** Add `@sentry/nuxt/module` and its options to the Nuxt config. */ +export async function addSDKModule( + config: string, + options: { org: string; project: string; url: string; selfHosted: boolean }, +): Promise { + const failureTagKey = "modify-nuxt-config-error"; + + let module: ProxifiedModule; + + try { + module = await loadFile(config); + } catch (e) { + if (e instanceof Error) { + if (e instanceof SyntaxError || e.message.includes("Unexpected token")) { + Sentry.setTag(failureTagKey, "loadFile-failed-syntax-error"); + } else if ( + e.message.includes("ENOENT") || + e.message.includes("no such file") + ) { + Sentry.setTag(failureTagKey, "loadFile-failed-file-not-found"); + } + } else { + Sentry.setTag(failureTagKey, "loadFile-failed"); + } + + clack.log.error( + `Error while loading Nuxt config file: ${ + e instanceof Error ? e.message : "Unknown" + }`, + ); + + showFallbackInstructions(config, options); + return await abort(); + } + + try { + addNuxtModule(module, "@sentry/nuxt/module", "sentry", { + org: options.org, + project: options.project, + ...(options.selfHosted && { sentryUrl: options.url }), + }); + } catch (e) { + Sentry.setTag(failureTagKey, "adding-sentry-options-failed"); + + clack.log.error( + `Error while modifying 'sentry' in Nuxt config: ${ + e instanceof Error ? e.message : "Unknown" + }`, + ); + + showFallbackInstructions(config, options); + return await abort(); + } + + try { + addNuxtModule(module, "@sentry/nuxt/module", "sourcemap", { + client: "hidden", + }); + } catch (e) { + Sentry.setTag(failureTagKey, "adding-sourcemap-options-failed"); + + clack.log.error( + `Error while modifying 'sourcemap' in Nuxt config: ${ + e instanceof Error ? e.message : "Unknown" + }`, + ); + + showFallbackInstructions(config, options); + return await abort(); + } + + let code: string; + + try { + ({ code } = generateCode(module)); + } catch (e) { + Sentry.setTag(failureTagKey, "generateCode-failed"); + + clack.log.error( + `Error while generating module code: ${ + e instanceof Error ? e.message : "Unknown" + }`, + ); + + showFallbackInstructions(config, options); + return await abort(); + } + + try { + await promises.writeFile(config, code, { encoding: "utf-8", flag: "w" }); + + clack.log.success( + `Added Sentry Nuxt Module to ${chalk.cyan(path.basename(config))}.`, + ); + } catch (e: unknown) { + Sentry.setTag(failureTagKey, "writeFile-failed"); + + clack.log.error( + `Error while writing Nuxt config: ${ + e instanceof Error ? e.message : "Unknown" + }`, + ); + + showFallbackInstructions(config, options); + return await abort(); + } +} + +function showFallbackInstructions( + config: string, + options: { org: string; project: string; url: string; selfHosted: boolean }, +): void { + clack.log.warn( + `Please add the following settings to ${chalk.cyan( + path.basename(config), + )}:`, + ); + // Printed outside clack's gutter so that it can be copied/pasted directly + clack.rawOutput(`\n\n${getNuxtModuleFallbackTemplate(options)}\n\n`); +} + +/** Ask for the features to enable, then write `sentry.{client,server}.config.{ts,js}`. */ +export async function createConfigFiles( + dsn: string, + reduceDataCollection: boolean, +): Promise { + const selectedFeatures = await featureSelectionPrompt([ + { + id: "performance", + prompt: `Do you want to enable ${chalk.bold( + "Tracing", + )} to track the performance of your application?`, + enabledHint: "recommended", + }, + { + id: "replay", + prompt: `Do you want to enable ${chalk.bold( + "Session Replay", + )} to get a video-like reproduction of errors during a user session?`, + enabledHint: "recommended, but increases bundle size", + }, + ] as const); + + const typeScriptDetected = isUsingTypeScript(); + + const configVariants = ["server", "client"] as const; + + for (const configVariant of configVariants) { + await traceStep(`create-sentry-${configVariant}-config`, async () => { + const jsConfig = `sentry.${configVariant}.config.js`; + const tsConfig = `sentry.${configVariant}.config.ts`; + + const jsConfigExists = existsSync(path.join(process.cwd(), jsConfig)); + const tsConfigExists = existsSync(path.join(process.cwd(), tsConfig)); + + let shouldWriteFile = true; + + if (jsConfigExists || tsConfigExists) { + const existingConfigs: string[] = []; + + if (jsConfigExists) { + existingConfigs.push(jsConfig); + } + + if (tsConfigExists) { + existingConfigs.push(tsConfig); + } + + const overwriteExistingConfigs = await abortIfCancelled( + clack.confirm({ + message: `Found existing Sentry ${configVariant} config (${existingConfigs.join( + ", ", + )}). Overwrite ${existingConfigs.length > 1 ? "them" : "it"}?`, + }), + ); + Sentry.setTag( + `overwrite-${configVariant}-config`, + overwriteExistingConfigs, + ); + + shouldWriteFile = overwriteExistingConfigs; + + if (overwriteExistingConfigs) { + if (jsConfigExists) { + unlinkSync(path.join(process.cwd(), jsConfig)); + clack.log.warn(`Removed existing ${chalk.cyan(jsConfig)}.`); + } + if (tsConfigExists) { + unlinkSync(path.join(process.cwd(), tsConfig)); + clack.log.warn(`Removed existing ${chalk.cyan(tsConfig)}.`); + } + } + } + + if (shouldWriteFile) { + await promises.writeFile( + path.join(process.cwd(), typeScriptDetected ? tsConfig : jsConfig), + getSentryConfigContents( + dsn, + configVariant, + selectedFeatures, + reduceDataCollection, + ), + { encoding: "utf8", flag: "w" }, + ); + clack.log.success( + `Created new ${chalk.cyan( + typeScriptDetected ? tsConfig : jsConfig, + )}.`, + ); + Sentry.setTag(`created-${configVariant}-config`, true); + } else { + clack.log.info( + `Okay, here are the changes your ${chalk.cyan( + typeScriptDetected ? tsConfig : jsConfig, + )} should contain:`, + ); + // Printed outside clack's gutter so that it can be copied/pasted directly + clack.rawOutput( + `\n\n ${getConfigBody(dsn, configVariant, selectedFeatures)}\n\n${getDataCollectionBlock(reduceDataCollection)}\n\n`, + ); + } + }); + } +} + +/** + * On Nuxt before 3.14, offer to override `ofetch` to `^1.4.0`, which Sentry + * needs to instrument the app. + */ +export async function addNuxtOverrides( + packageManager: PackageManager, + nuxtMinVer: SemVer | undefined, +): Promise { + if (!nuxtMinVer || !lt(nuxtMinVer, "3.14.0")) { + return; + } + + const pkgName = "ofetch"; + const pkgVersion = "^1.4.0"; + + clack.log.warn( + `To ensure Sentry can properly instrument your code it needs to add a version override for ${chalk.cyan( + pkgName, + )}.\n\nFor more info see: ${chalk.underline( + "https://github.com/getsentry/sentry-javascript/issues/14514", + )}`, + ); + + const shouldAddOverride = await askShouldAddPackageOverride( + pkgName, + pkgVersion, + ); + + if (shouldAddOverride) { + await packageManager.addOverride(pkgName, pkgVersion); + } +} diff --git a/packages/cli/src/lib/wizard/nuxt/templates.ts b/packages/cli/src/lib/wizard/nuxt/templates.ts new file mode 100644 index 000000000..ab207d798 --- /dev/null +++ b/packages/cli/src/lib/wizard/nuxt/templates.ts @@ -0,0 +1,503 @@ +/** + * Code templates of the Nuxt wizard: the Nuxt config, the Sentry SDK + * configs, and the example page, API route, and component. + */ + +import { getDataCollectionSnippet } from "../utils/data-collection.js"; +import { buildProjectIssuesUrl } from "../../sentry-web-urls.js"; + +type SelectedSentryFeatures = { + performance: boolean; + replay: boolean; +}; + +const DATA_COLLECTION_HINT = ` dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nuxt/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + },`; + +/** + * The active PII-reducing preset when the user opted in, the commented-out + * hint otherwise. + */ +/** The `dataCollection` preset, or a hint about it when not reduced. */ +export function getDataCollectionBlock(reduceDataCollection: boolean): string { + return reduceDataCollection + ? getDataCollectionSnippet(" ") + : DATA_COLLECTION_HINT; +} + +export function getDefaultNuxtConfig(): string { + return `// https://nuxt.com/docs/api/configuration/nuxt-config +export default defineNuxtConfig({ + compatibilityDate: '2024-04-03', + devtools: { enabled: true } +}) +`; +} + +export function getNuxtModuleFallbackTemplate(options: { + org: string; + project: string; + url: string; + selfHosted: boolean; +}): string { + return ` modules: ["@sentry/nuxt/module"], + sentry: { + org: "${options.org}", + project: "${options.project}",${ + options.selfHosted ? `\n sentryUrl: "${options.url}",` : "" + } + sourcemaps: { + // This will delete all .map files in the build output after uploading them to Sentry. Modify as needed. + // For more information, see: https://docs.sentry.io/platforms/javascript/guides/nuxt/sourcemaps/ + filesToDeleteAfterUpload: ['.*/**/*.map'] + }, + }, + sourcemap: { client: "hidden" },`; +} + +export function getSentryConfigContents( + dsn: string, + config: "client" | "server", + selectedFeatures: SelectedSentryFeatures, + reduceDataCollection: boolean, +): string { + if (config === "client") { + return getSentryClientConfigContents( + dsn, + selectedFeatures, + reduceDataCollection, + ); + } + + return getSentryServerConfigContents( + dsn, + selectedFeatures, + reduceDataCollection, + ); +} + +const featuresConfigMap: Record = { + performance: [ + " // We recommend adjusting this value in production, or using tracesSampler", + " // for finer control", + " tracesSampleRate: 1.0,", + ].join("\n"), + replay: [ + " // This sets the sample rate to be 10%. You may want this to be 100% while", + " // in development and sample at a lower rate in production", + " replaysSessionSampleRate: 0.1,", + " ", + " // If the entire session is not sampled, use the below sample rate to sample", + " // sessions when an error occurs.", + " replaysOnErrorSampleRate: 1.0,", + " ", + " // If you don't want to use Session Replay, just remove the line below:", + " integrations: [Sentry.replayIntegration()],", + ].join("\n"), +}; + +const featuresMap: Record< + "client" | "server", + Array +> = { + client: ["performance", "replay"], + server: ["performance"], +}; + +export function getConfigBody( + dsn: string, + variant: "client" | "server", + selectedFeatures: SelectedSentryFeatures, +): string { + const features = Object.keys(selectedFeatures) as Array< + keyof SelectedSentryFeatures + >; + return [ + `dsn: "${dsn}",`, + features + .map((feature) => { + return featuresMap[variant].includes(feature) && + selectedFeatures[feature] + ? featuresConfigMap[feature] + : null; + }) + .filter(Boolean) + .join("\n\n"), + ] + .filter(Boolean) + .join("\n\n"); +} + +function getSentryClientConfigContents( + dsn: string, + selectedFeatures: SelectedSentryFeatures, + reduceDataCollection: boolean, +): string { + return `import * as Sentry from "@sentry/nuxt"; + +Sentry.init({ + // If set up, you can use your runtime config here + // dsn: useRuntimeConfig().public.sentry.dsn, + ${getConfigBody(dsn, "client", selectedFeatures)} + +${getDataCollectionBlock(reduceDataCollection)} + + // Setting this option to true will print useful information to the console while you're setting up Sentry. + debug: false, +}); +`; +} + +function getSentryServerConfigContents( + dsn: string, + selectedFeatures: SelectedSentryFeatures, + reduceDataCollection: boolean, +): string { + return `import * as Sentry from "@sentry/nuxt"; + +Sentry.init({ + ${getConfigBody(dsn, "server", selectedFeatures)} + +${getDataCollectionBlock(reduceDataCollection)} + + // Setting this option to true will print useful information to the console while you're setting up Sentry. + debug: false, +}); +`; +} + +export function getIndexRouteTemplate(): string { + return ` + +`; +} + +export function getSentryExamplePageTemplate(options: { + org: string; + projectId: string; +}): string { + const { org, projectId } = options; + const issuesPageLink = buildProjectIssuesUrl(org, projectId); + + return ` + + + + + + + +`; +} + +export function getSentryExampleApiTemplate(): string { + return `// This is just a very simple API route that throws an example error. +// Feel free to delete this file. +import { defineEventHandler } from '#imports'; + +export default defineEventHandler(() => { + throw new Error("Sentry Example API Route Error"); +}); +`; +} + +export function getSentryErrorButtonTemplate(): string { + return ` + + + + + + +`; +} diff --git a/packages/cli/src/lib/wizard/nuxt/utils.ts b/packages/cli/src/lib/wizard/nuxt/utils.ts new file mode 100644 index 000000000..331ddce8d --- /dev/null +++ b/packages/cli/src/lib/wizard/nuxt/utils.ts @@ -0,0 +1,50 @@ +/** + * Detect whether a Nuxt project runs Nuxt 4, either by its installed + * version or by `future.compatibilityVersion: 4` in its config. + */ + +import { loadFile } from "magicast"; +import { abortIfCancelled } from "../utils/clack/index.js"; +import { clack } from "../utils/clack/prompts.js"; +import { debug } from "../utils/debug.js"; +import { getMajorVersion } from "../utils/semver.js"; + +/** + * Whether the project uses Nuxt 4. + * + * @param nuxtConfig - Path of the Nuxt config file + * @param packageVersion - The `nuxt` version range from `package.json` + */ +export async function isNuxtV4( + nuxtConfig: string, + packageVersion: string | undefined, +): Promise { + // Compare majors so prereleases such as 4.0.0-rc.1 count as Nuxt 4. + if ((getMajorVersion(packageVersion) ?? 0) >= 4) { + return true; + } + + // At the time of writing, nuxt 4 is not on its own + // major yet. We must read the `compatibilityVersion` + // from the nuxt config. + try { + const mod = await loadFile(nuxtConfig); + const defaultExport = mod.exports["default"]; + const config = + defaultExport.$type === "function-call" + ? defaultExport.$args[0] + : defaultExport; + + if (config?.future?.compatibilityVersion === 4) { + return true; + } + } catch (error) { + // Not fatal: when the config can't be parsed, ask instead. + debug(error); + return await abortIfCancelled( + clack.confirm({ message: "Are you using Nuxt version 4?" }), + ); + } + + return false; +} diff --git a/packages/cli/src/lib/wizard/run.ts b/packages/cli/src/lib/wizard/run.ts index 0e2f411ec..e236129a4 100644 --- a/packages/cli/src/lib/wizard/run.ts +++ b/packages/cli/src/lib/wizard/run.ts @@ -62,10 +62,18 @@ type WizardRunner = ( * moved over from sentry-wizard. */ const WIZARD_RUNNERS: Partial> = { + angular: async (options) => { + const { runAngularWizard } = await import("./angular/angular-wizard.js"); + await runAngularWizard(options); + }, nextjs: async (options) => { const { runNextjsWizard } = await import("./nextjs/nextjs-wizard.js"); await runNextjsWizard(options); }, + nuxt: async (options) => { + const { runNuxtWizard } = await import("./nuxt/nuxt-wizard.js"); + await runNuxtWizard(options); + }, remix: async (options) => { const { runRemixWizard } = await import("./remix/remix-wizard.js"); await runRemixWizard(options); diff --git a/packages/cli/src/lib/wizard/sourcemaps/ci.ts b/packages/cli/src/lib/wizard/sourcemaps/ci.ts index ed73aa32c..cf666f259 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/ci.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/ci.ts @@ -13,6 +13,7 @@ import { SENTRY_DOT_ENV_FILE, } from "../utils/clack/index.js"; import { clack } from "../utils/clack/prompts.js"; +import { setupNpmScriptInCI } from "./tools/sentry-cli.js"; /** Tools that upload with `sentry` commands and read `.sentryclirc`. */ const CLI_BASED_FLOW_TOOLS: readonly string[] = [ @@ -23,23 +24,41 @@ const CLI_BASED_FLOW_TOOLS: readonly string[] = [ ]; /** - * Ask whether the user builds in CI and, if so, show the auth token to set - * there. + * Where `sentry sourcemap upload` sends source maps. On sentry.io v4 + * resolves the org and project from the DSN, so CI needs only the token. + * Self-hosted CI also needs `SENTRY_ORG`, `SENTRY_PROJECT` and `SENTRY_URL`. + */ +export type SentryCliUploadTarget = { + org: string; + project: string; + /** The self-hosted Sentry URL. Unset for sentry.io. */ + url?: string | undefined; +}; + +/** + * Ask whether the user builds in CI and, if so, show the environment + * variables to set there. * * @param selectedTool - The build tool the wizard configured, such as `nextjs` * @param authToken - The token written to the local config file + * @param uploadTarget - For tools that upload with `sentry` commands, the + * org, project, and self-hosted URL to upload to */ export async function setupCI( selectedTool: string, authToken: string, + uploadTarget?: SentryCliUploadTarget, ): Promise { - await traceStep("configure-ci", () => configureCI(selectedTool, authToken)); + await traceStep("configure-ci", () => + configureCI(selectedTool, authToken, uploadTarget), + ); } -/** Ask about CI and show the auth token to set there. */ +/** Ask about CI and show the environment variables to set there. */ async function configureCI( selectedTool: string, authToken: string, + uploadTarget: SentryCliUploadTarget | undefined, ): Promise { const isUsingCI = await abortIfCancelled( clack.select({ @@ -62,7 +81,9 @@ async function configureCI( Sentry.setTag("using-ci", isUsingCI); - const authTokenFile = CLI_BASED_FLOW_TOOLS.includes(selectedTool) + const isCliBasedFlowTool = CLI_BASED_FLOW_TOOLS.includes(selectedTool); + + const authTokenFile = isCliBasedFlowTool ? SENTRY_CLI_RC_FILE : SENTRY_DOT_ENV_FILE; @@ -75,19 +96,52 @@ async function configureCI( return; } - await traceStep("ci-auth-token-setup", () => setupAuthTokenInCI(authToken)); + if (isCliBasedFlowTool) { + await traceStep("ci-npm-script-setup", setupNpmScriptInCI); + } + + await traceStep("ci-auth-token-setup", () => + setupAuthTokenInCI( + authToken, + isCliBasedFlowTool ? uploadTarget : undefined, + ), + ); } -/** Show the auth token to add to the CI environment. */ -async function setupAuthTokenInCI(authToken: string): Promise { +/** + * The `NAME=value` lines to add to the CI environment: the auth token, plus + * the org, project, and URL for a self-hosted upload target. + */ +export function getCIEnvVars( + authToken: string, + uploadTarget: SentryCliUploadTarget | undefined, +): string[] { + const lines = [`SENTRY_AUTH_TOKEN=${authToken}`]; + if (uploadTarget?.url) { + lines.push( + `SENTRY_ORG=${uploadTarget.org}`, + `SENTRY_PROJECT=${uploadTarget.project}`, + `SENTRY_URL=${uploadTarget.url}`, + ); + } + return lines; +} + +/** Show the auth token, and the upload target if any, to add to CI. */ +async function setupAuthTokenInCI( + authToken: string, + uploadTarget: SentryCliUploadTarget | undefined, +): Promise { clack.log.step( - "Add the Sentry authentication token as an environment variable to your CI setup:", + uploadTarget?.url + ? "Add these environment variables to your CI setup:" + : "Add the Sentry authentication token as an environment variable to your CI setup:", ); // Printed outside clack's gutter so that it can be copied/pasted directly clack.rawOutput( chalk.greenBright(` -SENTRY_AUTH_TOKEN=${authToken} +${getCIEnvVars(authToken, uploadTarget).join("\n")} `), ); diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/angular.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/angular.ts new file mode 100644 index 000000000..594928170 --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/angular.ts @@ -0,0 +1,56 @@ +/** + * The source map generation step for Angular: shows the `angular.json` + * setting that turns on source maps and asks the user to check it. + */ + +import { clack } from "../../utils/clack/prompts.js"; +import chalk from "chalk"; +import { abortIfCancelled, makeCodeSnippet } from "../../utils/clack/index.js"; + +/** + * The `angular.json` change that turns on source maps. It goes in the + * production configuration, like the automatic `angular.json` edit, because + * Angular's default production configuration sets `sourceMap: false`, which + * overrides `options`. + */ +const angularJsonTemplate = makeCodeSnippet(true, (unchanged, plus) => + unchanged(`{ + "projects": { + "your-project": { + "architect": { + "build": { + "configurations": { + "production": { + ${plus(`"sourceMap": true`)} + } + } + } + } + } + } +}`), +); + +/** Show the `angular.json` change and wait until the user confirms it. */ +export async function configureAngularSourcemapGenerationFlow(): Promise { + clack.log.info( + `Enable generating source maps in your ${chalk.bold("angular.json")} file:`, + ); + + // Printed outside clack's gutter so that it can be copied/pasted directly + clack.rawOutput(angularJsonTemplate); + + await abortIfCancelled( + clack.select({ + message: `Verify that you are generating source maps when building your Angular app.`, + options: [ + { + label: "I checked!", + hint: "My build output folder contains .js.map files after a build.", + value: true, + }, + ], + initialValue: true, + }), + ); +} diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts new file mode 100644 index 000000000..30c589fd6 --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts @@ -0,0 +1,501 @@ +/** + * Source map upload with `sentry` commands, for build tools that have no + * Sentry bundler plugin (Angular, tsc, Create React App, …). + * + * Installs the `sentry` CLI package, adds a `sentry:sourcemaps` npm script + * that runs `sentry sourcemap upload` on the build output, optionally + * appends it to the production build script, and + * writes the org, project, self-hosted URL, and auth token to `.sentryclirc`. + * v4 reads that file: `[defaults]` feeds org/project/url resolution and + * `[auth] token` becomes `SENTRY_AUTH_TOKEN`. + * + * Ported from sentry-wizard's `src/sourcemaps/tools/sentry-cli.ts`, which + * installed `@sentry/cli`, ran `sentry-cli sourcemaps …`, and also wrote the + * token to `.sentryclirc`. + */ + +import { existsSync, promises, readFileSync } from "node:fs"; +import path from "node:path"; +import chalk from "chalk"; +import { CLI_VERSION } from "../../../constants.js"; +import { Sentry, traceStep } from "../../telemetry.js"; +import { + abortIfCancelled, + addSentryCliConfig, + artifactsExist, + askToRunBuildOrEnterPathOrProceed, + getPackageDotJson, + getPackageManager, + installPackage, + SENTRY_CLI_RC_FILE, +} from "../../utils/clack/index.js"; +import { clack } from "../../utils/clack/prompts.js"; +import { debug } from "../../utils/debug.js"; +import { hasPackageInstalled } from "../../utils/package-json.js"; +import { NPM } from "../../utils/package-manager.js"; +import type { SourceMapUploadToolConfigurationOptions } from "./types.js"; + +const SENTRY_NPM_SCRIPT_NAME = "sentry:sourcemaps"; + +/** + * The `sentry` package to install: the major this wizard runs on. The + * package manager runs through a shell, so the spec must not hold shell + * metacharacters such as `>`, `<`, `|` or `^`. + */ +export const SENTRY_CLI_PACKAGE_SPEC = `sentry@${CLI_VERSION.split(".")[0]}.x`; + +let addedToBuildCommand = false; + +type configureSentryCLIOptions = SourceMapUploadToolConfigurationOptions & { + defaultArtifactPath?: string | undefined; + /** Passed to the package manager when installing the `sentry` CLI. */ + forceInstall?: boolean | undefined; +}; + +/** + * Set up source map upload with `sentry sourcemap` commands. + * + * @param options - The Sentry project to upload to, and the build output + * path to suggest + * @param configureSourcemapGenerationFlow - Asks the user to turn on source + * map generation in their build tool + * @param skipValidation - Skip `configureSourcemapGenerationFlow`, for flows + * that already turned source maps on + */ +export async function configureSentryCLI( + options: configureSentryCLIOptions, + configureSourcemapGenerationFlow: () => Promise = defaultConfigureSourcemapGenerationFlow, + skipValidation = false, +): Promise { + const packageDotJson = await getPackageDotJson(); + + await installPackage({ + packageName: SENTRY_CLI_PACKAGE_SPEC, + alreadyInstalled: hasPackageInstalled("sentry", packageDotJson), + devDependency: true, + forceInstall: options.forceInstall, + }); + + let validPath = false; + let relativeArtifactPath: string | undefined; + do { + const rawArtifactPath = await abortIfCancelled( + clack.text({ + message: "Where are your build artifacts located?", + placeholder: + relativeArtifactPath ?? + options.defaultArtifactPath ?? + `.${path.sep}out`, + initialValue: + relativeArtifactPath ?? + options.defaultArtifactPath ?? + `.${path.sep}out`, + validate(value) { + if (!value) { + return "Please enter a path."; + } + return undefined; + }, + }), + ); + + if (path.isAbsolute(rawArtifactPath)) { + // The project root itself is "" relative to cwd; the CLI needs ".". + relativeArtifactPath = + path.relative(process.cwd(), rawArtifactPath) || "."; + } else { + relativeArtifactPath = rawArtifactPath; + } + + if (artifactsExist(relativeArtifactPath)) { + validPath = true; + continue; + } + + const runBuildOrEnterPathOrProceed = + await askToRunBuildOrEnterPathOrProceed({ + relativeArtifactPath, + }); + + validPath = runBuildOrEnterPathOrProceed.validPath; + relativeArtifactPath = + runBuildOrEnterPathOrProceed.relativeArtifactPath ?? relativeArtifactPath; + } while (!validPath); + + const relativePosixArtifactPath = relativeArtifactPath + .split(path.sep) + .join(path.posix.sep); + + if (!skipValidation) { + await configureSourcemapGenerationFlow(); + } + + await createAndAddNpmScript(relativePosixArtifactPath); + + if (await askShouldAddToBuildCommand()) { + await traceStep("sentry-cli-add-to-build-cmd", () => + addSentryCommandToBuildCommand(), + ); + } else { + clack.log.info( + `No problem, just make sure to run this script ${chalk.bold( + "after", + )} building your application but ${chalk.bold("before")} deploying!`, + ); + } + + await addUploadTargetToSentryCliRc(options); + await addSentryCliConfig({ authToken: options.authToken }); + + if (options.selfHosted) { + clack.log.info( + `Set ${chalk.cyan(`SENTRY_URL=${options.url}`)} wherever ${chalk.cyan( + SENTRY_NPM_SCRIPT_NAME, + )} runs, such as in CI, so that it uploads to your Sentry instance.`, + ); + } +} + +/** + * Ask the user to run the `sentry:sourcemaps` script in CI, unless the + * wizard already appended it to the build script. + */ +export async function setupNpmScriptInCI(): Promise { + if (addedToBuildCommand) { + // No need to tell users to add it manually to their CI + // if the script is already added to the build command + return; + } + + const addedToCI = await abortIfCancelled( + clack.select({ + message: `Add a step to your CI pipeline that runs the ${chalk.cyan( + SENTRY_NPM_SCRIPT_NAME, + )} script ${chalk.bold("right after")} building your application.`, + options: [ + { label: "I did, continue!", value: true }, + { + label: "I'll do it later...", + value: false, + hint: chalk.yellow( + `You need to run ${chalk.cyan( + SENTRY_NPM_SCRIPT_NAME, + )} after each build for source maps to work properly.`, + ), + }, + ], + initialValue: true, + }), + ); + + Sentry.setTag("added-ci-script", addedToCI); + + if (!addedToCI) { + clack.log.info("Don't forget! :)"); + } +} + +/** + * The `sentry:sourcemaps` script: upload the build output. `sentry sourcemap + * upload` injects missing debug IDs into the files first, so the deployed + * build carries them. It reads the org and project from + * `.sentryclirc` locally. In CI it resolves them from the DSN on sentry.io, + * and from `SENTRY_ORG`, `SENTRY_PROJECT` and `SENTRY_URL` for self-hosted. + */ +export function getSentryCliNpmScript( + relativePosixArtifactPath: string, +): string { + const artifactPath = quoteShellArg(relativePosixArtifactPath); + // The script runs the `sentry` binary of the package installed above, so + // it names `sentry` itself, not the program running the wizard. + // oxlint-disable-next-line sentry-cli/no-hardcoded-sentry-command -- a package.json script, not a hint. + return `sentry sourcemap upload ${artifactPath}`; +} + +/** Characters that make a shell split or expand an unquoted argument. */ +const SHELL_SPECIAL_RE = /[\s"'`$&|;<>()*?[\]{}!#~\\]/; + +/** + * Double-quote `value` for the npm script shell when it has whitespace or + * shell metacharacters, escaping the characters that stay special inside + * double quotes. Plain paths such as `dist` stay as they are. + */ +function quoteShellArg(value: string): string { + if (!SHELL_SPECIAL_RE.test(value)) { + return value; + } + return `"${value.replace(/["\\$`]/g, "\\$&")}"`; +} + +/** An INI section header line, such as `[defaults]`. */ +const INI_SECTION_RE = /^\s*\[([^\]]*)\]\s*$/; + +/** The key of an INI `key = value` line. */ +const INI_KEY_RE = /^\s*([^=;#\s][^=]*?)\s*=/; + +/** + * Set `values` in the `[defaults]` section of `.sentryclirc` contents and + * keep every other line as it is. + * + * Existing keys are updated in every `[defaults]` section, since the last + * one wins when the file is read. Missing keys go into the first + * `[defaults]` section, which is appended when there is none. + * + * @param contents - The current file contents, empty for a new file + * @param values - Lowercase keys and their values, such as `{ org, project }` + */ +export function setSentryCliRcDefaults( + contents: string, + values: Record, +): string { + const lines = contents === "" ? [] : contents.split("\n"); + const missing = new Map(Object.entries(values)); + let firstDefaultsHeader = -1; + let inDefaults = false; + + for (const [index, line] of lines.entries()) { + const section = INI_SECTION_RE.exec(line); + if (section) { + inDefaults = section[1]?.trim().toLowerCase() === "defaults"; + if (inDefaults && firstDefaultsHeader === -1) { + firstDefaultsHeader = index; + } + continue; + } + const key = inDefaults + ? INI_KEY_RE.exec(line)?.[1]?.toLowerCase() + : undefined; + const value = key === undefined ? undefined : values[key]; + if (key !== undefined && value !== undefined) { + lines[index] = `${key}=${value}${line.endsWith("\r") ? "\r" : ""}`; + missing.delete(key); + } + } + + const newLines = [...missing].map(([key, value]) => `${key}=${value}`); + if (newLines.length === 0) { + return lines.join("\n"); + } + if (firstDefaultsHeader !== -1) { + lines.splice(firstDefaultsHeader + 1, 0, ...newLines); + return lines.join("\n"); + } + + const prefix = lines.join("\n"); + let separator = "\n\n"; + if (prefix === "") { + separator = ""; + } else if (prefix.endsWith("\n")) { + separator = "\n"; + } + return `${prefix}${separator}[defaults]\n${newLines.join("\n")}\n`; +} + +/** + * Write the org, project and, for self-hosted Sentry, the URL to the + * project's `.sentryclirc`, so that `sentry sourcemap upload` finds them + * when the script runs locally. + * + * v4 reads a self-hosted `[defaults] url` only once the CLI trusts an + * `[auth] token` from the same file for it. Until that same-file trust fix + * lands, `assertRcUrlTrusted` refuses it and users set `SENTRY_URL`. + */ +export async function addUploadTargetToSentryCliRc( + options: SourceMapUploadToolConfigurationOptions, +): Promise { + const configPath = path.join(process.cwd(), SENTRY_CLI_RC_FILE); + const contents = existsSync(configPath) + ? readFileSync(configPath, "utf8") + : ""; + + try { + await promises.writeFile( + configPath, + setSentryCliRcDefaults(contents, { + org: options.orgSlug, + project: options.projectSlug, + ...(options.selfHosted ? { url: options.url } : {}), + }), + ); + } catch (error) { + // Not fatal, like the auth token write: CI sets SENTRY_ORG and + // SENTRY_PROJECT anyway, and the warning says what to do locally. + debug(error); + clack.log.warning( + `Failed to add the org and project to ${chalk.cyan( + SENTRY_CLI_RC_FILE, + )}. Set ${chalk.cyan("SENTRY_ORG")} and ${chalk.cyan( + "SENTRY_PROJECT", + )} wherever ${chalk.cyan(SENTRY_NPM_SCRIPT_NAME)} runs.`, + ); + return; + } + + clack.log.success( + `Added the org and project to ${chalk.cyan(SENTRY_CLI_RC_FILE)}.`, + ); +} + +async function createAndAddNpmScript( + relativePosixArtifactPath: string, +): Promise { + const sentryCliNpmScript = getSentryCliNpmScript(relativePosixArtifactPath); + + const packageDotJson = await getPackageDotJson(); + + packageDotJson.scripts = packageDotJson.scripts || {}; + packageDotJson.scripts[SENTRY_NPM_SCRIPT_NAME] = sentryCliNpmScript; + + await promises.writeFile( + path.join(process.cwd(), "package.json"), + JSON.stringify(packageDotJson, null, 2), + ); + + clack.log.info( + `Added a ${chalk.cyan(SENTRY_NPM_SCRIPT_NAME)} script to your ${chalk.cyan( + "package.json", + )}.`, + ); +} + +async function askShouldAddToBuildCommand(): Promise { + const shouldAddToBuildCommand = await abortIfCancelled( + clack.select({ + message: `Do you want to automatically run the ${chalk.cyan( + SENTRY_NPM_SCRIPT_NAME, + )} script after each production build?`, + options: [ + { + label: "Yes", + value: true, + hint: "This will modify your prod build command", + }, + { label: "No", value: false }, + ], + initialValue: true, + }), + ); + + Sentry.setTag("modify-build-command", shouldAddToBuildCommand); + + return shouldAddToBuildCommand; +} + +/** + * Add the sentry:sourcemaps command to the prod build command in the package.json + * - Detect the user's build command + * - Append the sentry:sourcemaps command to it + * + * @param packageDotJson The package.json which will be modified. + */ +export async function addSentryCommandToBuildCommand(): Promise { + const packageDotJson = await getPackageDotJson(); + // This usually shouldn't happen because earlier we added the + // SENTRY_NPM_SCRIPT_NAME script but just to be sure + packageDotJson.scripts = packageDotJson.scripts || {}; + + const allNpmScripts = Object.keys(packageDotJson.scripts).filter( + (s) => s !== SENTRY_NPM_SCRIPT_NAME, + ); + + const packageManager = await getPackageManager(NPM); + + // Heuristic to pre-select the build command: + // Often, 'build' is the prod build command, so we favour it. + // If it's not there, commands that include 'build' might be the prod build command. + let buildCommand = + typeof packageDotJson.scripts["build"] === "string" + ? "build" + : allNpmScripts.find((s) => s.toLocaleLowerCase().includes("build")); + + const isProdBuildCommand = + !!buildCommand && + (await abortIfCancelled( + clack.confirm({ + message: `Is ${chalk.cyan( + `${packageManager.runScriptCommand} ${buildCommand}`, + )} your production build command?`, + }), + )); + + if (allNpmScripts.length && (!buildCommand || !isProdBuildCommand)) { + buildCommand = await abortIfCancelled( + clack.select({ + message: `Which ${packageManager.name} command in your ${chalk.cyan( + "package.json", + )} builds your application for production?`, + options: [ + ...allNpmScripts.map((script) => ({ + label: script, + value: script, + })), + { label: "None of the above", value: "none" }, + ], + }), + ); + } + + if (!buildCommand || buildCommand === "none") { + clack.log.warn( + `We can only add the ${chalk.cyan( + SENTRY_NPM_SCRIPT_NAME, + )} script to another \`script\` in your ${chalk.cyan("package.json")}. +Please add it manually to your prod build command.`, + ); + return; + } + + const oldCommand = packageDotJson.scripts[buildCommand]; + if (!oldCommand) { + // very unlikely to happen but nevertheless + clack.log.warn( + `\`${buildCommand}\` doesn't seem to be part of your package.json scripts`, + ); + return; + } + + const newCommand = `${oldCommand} && ${packageManager.runScriptCommand} ${SENTRY_NPM_SCRIPT_NAME}`; + + if (oldCommand.endsWith(SENTRY_NPM_SCRIPT_NAME)) { + clack.log.info( + `It seems like ${chalk.cyan( + SENTRY_NPM_SCRIPT_NAME, + )} is already part of your ${chalk.cyan( + buildCommand, + )} command. Will not add it again. +Current command: ${chalk.dim(oldCommand)} +Would have injected: ${chalk.dim(newCommand)}`, + ); + + // The build already runs the script, so CI needs no separate step. + addedToBuildCommand = true; + return; + } + + packageDotJson.scripts[buildCommand] = newCommand; + + await promises.writeFile( + path.join(process.cwd(), "package.json"), + JSON.stringify(packageDotJson, null, 2), + ); + + addedToBuildCommand = true; + + clack.log.info( + `Added ${chalk.cyan(SENTRY_NPM_SCRIPT_NAME)} script to your ${chalk.cyan( + buildCommand, + )} command.`, + ); +} + +async function defaultConfigureSourcemapGenerationFlow(): Promise { + await abortIfCancelled( + clack.select({ + message: `Verify that your build tool is generating source maps. ${chalk.dim( + "(Your build output folder should contain .js.map files after a build)", + )}`, + options: [{ label: "I checked. Continue!", value: true }], + initialValue: true, + }), + ); +} diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/types.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/types.ts new file mode 100644 index 000000000..b1f26ce05 --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/types.ts @@ -0,0 +1,11 @@ +/** + * Options the source map upload tool setups take. + */ + +export type SourceMapUploadToolConfigurationOptions = { + selfHosted: boolean; + url: string; + authToken: string; + orgSlug: string; + projectSlug: string; +}; diff --git a/packages/cli/src/lib/wizard/utils/semver.ts b/packages/cli/src/lib/wizard/utils/semver.ts index da0fe4142..f303be4a9 100644 --- a/packages/cli/src/lib/wizard/utils/semver.ts +++ b/packages/cli/src/lib/wizard/utils/semver.ts @@ -5,6 +5,7 @@ import { major, minVersion, + type SemVer, satisfies, subset, valid, @@ -23,9 +24,18 @@ export function getMajorVersion( if (!version) { return undefined; } + const minVer = safeMinVersion(version); + return minVer ? major(minVer) : undefined; +} + +/** + * The lowest version that `range` permits, like semver's `minVersion`, but + * `undefined` instead of a throw for specifiers that are not ranges, such as + * `latest` or `workspace:*`. + */ +export function safeMinVersion(range: string): SemVer | undefined { try { - const minVer = minVersion(version); - return minVer ? major(minVer) : undefined; + return minVersion(range) ?? undefined; } catch (error) { debug(error); return undefined; diff --git a/packages/cli/test/lib/wizard/angular/angular-wizard-install.test.ts b/packages/cli/test/lib/wizard/angular/angular-wizard-install.test.ts new file mode 100644 index 000000000..b0914b043 --- /dev/null +++ b/packages/cli/test/lib/wizard/angular/angular-wizard-install.test.ts @@ -0,0 +1,102 @@ +import { describe, expect, it, vi } from "vitest"; + +import { runAngularWizard } from "../../../../src/lib/wizard/angular/angular-wizard.js"; +import { WizardExitError } from "../../../../src/lib/errors.js"; +import { + getPackageDotJson, + installPackage, +} from "../../../../src/lib/wizard/utils/clack/index.js"; +import { askShouldReduceDataCollection } from "../../../../src/lib/wizard/utils/data-collection.js"; + +/** Thrown by the mocked install to stop the flow right after it. */ +const { STOP } = vi.hoisted(() => ({ STOP: new Error("stop after install") })); + +vi.mock("../../../../src/lib/wizard/telemetry.js", async (importOriginal) => ({ + ...(await importOriginal()), + withTelemetry: (_options: unknown, fn: () => Promise) => fn(), +})); + +vi.mock( + "../../../../src/lib/wizard/utils/data-collection.js", + async (importOriginal) => ({ + ...(await importOriginal()), + askShouldReduceDataCollection: vi.fn().mockRejectedValue(STOP), + }), +); + +vi.mock("../../../../src/lib/wizard/utils/node-version.js", () => ({ + warnIfNodeVersionUnsupportedBySdkV11: vi.fn(), +})); + +vi.mock( + "../../../../src/lib/wizard/utils/clack/index.js", + async (importOriginal) => ({ + ...(await importOriginal()), + printWelcome: vi.fn(), + confirmContinueIfNoOrDirtyGitRepo: vi.fn().mockResolvedValue(undefined), + ensurePackageIsInstalled: vi.fn().mockResolvedValue(undefined), + printSdkV11MigrationGuideIfOutdated: vi.fn(), + getPackageDotJson: vi.fn().mockResolvedValue({ + dependencies: { "@angular/core": "^19.0.0" }, + }), + getOrAskForProjectData: vi.fn().mockResolvedValue({ + spotlight: false, + selfHosted: false, + sentryUrl: "https://sentry.io/", + authToken: "sntrys_token", + selectedProject: { + id: "2", + slug: "my-project", + organization: { slug: "my-org" }, + keys: [{ dsn: { public: "https://key@o1.ingest.sentry.io/2" } }], + }, + }), + installPackage: vi.fn().mockRejectedValue(STOP), + featureSelectionPrompt: vi.fn().mockRejectedValue(STOP), + }), +); + +describe("runAngularWizard", () => { + it.each([true, false])( + "passes forceInstall=%s to installPackage", + async (forceInstall) => { + await expect( + runAngularWizard({ + telemetryEnabled: false, + ignoreGitChanges: true, + forceInstall, + }), + ).rejects.toBe(STOP); + + expect(installPackage).toHaveBeenLastCalledWith( + expect.objectContaining({ + packageName: "@sentry/angular@^11", + forceInstall, + }), + ); + }, + ); + + it("asks about data collection when the installed SDK version is unknown", async () => { + vi.mocked(installPackage).mockResolvedValueOnce({}); + + await expect( + runAngularWizard({ telemetryEnabled: false, ignoreGitChanges: true }), + ).rejects.toBe(STOP); + + expect(askShouldReduceDataCollection).toHaveBeenCalled(); + }); + + it("exits cleanly, without a raw semver error, when the installed Angular version does not parse", async () => { + vi.mocked(getPackageDotJson).mockResolvedValueOnce({ + dependencies: { "@angular/core": "latest" }, + }); + + await expect( + runAngularWizard({ telemetryEnabled: false, ignoreGitChanges: true }), + ).rejects.toBeInstanceOf(WizardExitError); + expect(installPackage).not.toHaveBeenCalledWith( + expect.objectContaining({ packageName: "@sentry/angular@^11" }), + ); + }); +}); diff --git a/packages/cli/test/lib/wizard/angular/angular-wizard.test.ts b/packages/cli/test/lib/wizard/angular/angular-wizard.test.ts new file mode 100644 index 000000000..dcde4e85a --- /dev/null +++ b/packages/cli/test/lib/wizard/angular/angular-wizard.test.ts @@ -0,0 +1,100 @@ +import { describe, expect, it, vi } from "vitest"; + +import { buildOutroMessage } from "../../../../src/lib/wizard/angular/angular-wizard.js"; +import { getInitCallArgs } from "../../../../src/lib/wizard/angular/codemods/main.js"; + +vi.mock("../../../../src/lib/wizard/utils/clack/mcp-config.js", () => ({ + offerProjectScopedMcpConfig: vi.fn().mockResolvedValue(undefined), +})); + +describe("angular-wizard", () => { + describe("buildOutroMessage", () => { + it("returns the correct outro message if example component was created", () => { + expect(buildOutroMessage(true)).toMatchInlineSnapshot(` + "Successfully installed the Sentry Angular SDK! + + You can validate your setup by starting your dev environment (ng serve) and throwing an error in the example component. + + Check out the SDK documentation for further configuration: + https://docs.sentry.io/platforms/javascript/guides/angular/" + `); + }); + it("returns the correct outro message if example component creation was skipped", () => { + expect(buildOutroMessage(false)).toMatchInlineSnapshot(` + "Successfully installed the Sentry Angular SDK! + + Check out the SDK documentation for further configuration: + https://docs.sentry.io/platforms/javascript/guides/angular/" + `); + }); + }); + + describe("getInitCallArgs", () => { + it("returns the correct init call arguments when all features are enabled", () => { + const args = getInitCallArgs("https://example.com", { + performance: true, + replay: true, + }); + expect(args).toMatchInlineSnapshot(` + { + "dsn": "https://example.com", + "integrations": [ + {}, + {}, + ], + "replaysOnErrorSampleRate": 1, + "replaysSessionSampleRate": 0.1, + "tracesSampleRate": 1, + } + `); + }); + + it("returns the correct init call arguments when performance is disabled", () => { + const args = getInitCallArgs("https://example.com", { + performance: false, + replay: true, + }); + + expect(args).toMatchInlineSnapshot(` + { + "dsn": "https://example.com", + "integrations": [ + {}, + ], + "replaysOnErrorSampleRate": 1, + "replaysSessionSampleRate": 0.1, + } + `); + }); + + it("returns the correct init call arguments when replay is disabled", () => { + const args = getInitCallArgs("https://example.com", { + performance: true, + replay: false, + }); + + expect(args).toMatchInlineSnapshot(` + { + "dsn": "https://example.com", + "integrations": [ + {}, + ], + "tracesSampleRate": 1, + } + `); + }); + + it("returns the correct init call arguments when all features are disabled", () => { + const args = getInitCallArgs("https://example.com", { + performance: false, + replay: false, + }); + + expect(args).toMatchInlineSnapshot(` + { + "dsn": "https://example.com", + } + `); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/angular/codemods/app-config.test.ts b/packages/cli/test/lib/wizard/angular/codemods/app-config.test.ts new file mode 100644 index 000000000..5fbcbc9e4 --- /dev/null +++ b/packages/cli/test/lib/wizard/angular/codemods/app-config.test.ts @@ -0,0 +1,99 @@ +import { generateCode, parseModule } from "magicast"; +import { SemVer } from "semver"; +import { describe, expect, it, vi } from "vitest"; +import { updateAppConfigMod } from "../../../../../src/lib/wizard/angular/codemods/app-config.js"; + +vi.mock("@clack/prompts", () => ({ + log: { warn: vi.fn() }, +})); + +const APP_CONFIG = `import { ApplicationConfig } from '@angular/core'; +import { provideRouter } from '@angular/router'; + +export const appConfig: ApplicationConfig = { + providers: [provideRouter(routes)], +}; +`; + +describe("updateAppConfigMod", () => { + it("adds the ErrorHandler, TraceService, and provideAppInitializer on Angular 19+", () => { + const mod = parseModule(APP_CONFIG); + const { code } = generateCode( + updateAppConfigMod(mod, new SemVer("19.0.0"), true), + ); + + expect(code).toContain("import * as Sentry from '@sentry/angular';"); + expect(code).toContain("provide: ErrorHandler"); + expect(code).toContain("useValue: Sentry.createErrorHandler()"); + expect(code).toContain("provide: Sentry.TraceService"); + expect(code).toContain("provideAppInitializer(() => {"); + expect(code).not.toContain("APP_INITIALIZER"); + }); + + it("uses APP_INITIALIZER before Angular 19", () => { + const mod = parseModule(APP_CONFIG); + const { code } = generateCode( + updateAppConfigMod(mod, new SemVer("18.2.0"), true), + ); + + expect(code).toContain("provide: APP_INITIALIZER"); + expect(code).not.toContain("provideAppInitializer"); + }); + + it("only adds the ErrorHandler without tracing", () => { + const mod = parseModule(APP_CONFIG); + const { code } = generateCode( + updateAppConfigMod(mod, new SemVer("19.0.0"), false), + ); + + expect(code).toContain("provide: ErrorHandler"); + expect(code).not.toContain("TraceService"); + }); + + it.each(["19.0.0", "18.2.0"])( + "does not import the tracing helpers without tracing on Angular %s", + (version) => { + const mod = parseModule(APP_CONFIG); + const { code } = generateCode( + updateAppConfigMod(mod, new SemVer(version), false), + ); + + expect(code).not.toContain("provideAppInitializer"); + expect(code).not.toContain("inject"); + expect(code).not.toContain("APP_INITIALIZER"); + }, + ); + + it("throws instead of reporting success when appConfig has no providers array", () => { + const mod = parseModule(`import { ApplicationConfig } from '@angular/core'; + +export const appConfig: ApplicationConfig = { + providers: someVar, +}; +`); + + expect(() => updateAppConfigMod(mod, new SemVer("19.0.0"), true)).toThrow( + "Could not find a `providers` array", + ); + }); + + it("ignores other named exports in the file", () => { + const mod = parseModule(`export const API_URL = '/api'; +${APP_CONFIG}`); + const { code } = generateCode( + updateAppConfigMod(mod, new SemVer("19.0.0"), false), + ); + + expect(code).toContain("provide: ErrorHandler"); + }); + + it("throws when the file has no exported appConfig object", () => { + const mod = parseModule(`const appConfig = { providers: [] }; +export default appConfig; +`); + + expect(() => updateAppConfigMod(mod, new SemVer("19.0.0"), true)).toThrow( + "Could not find a `providers` array", + ); + }); +}); diff --git a/packages/cli/test/lib/wizard/angular/codemods/main.test.ts b/packages/cli/test/lib/wizard/angular/codemods/main.test.ts new file mode 100644 index 000000000..279e7d2ea --- /dev/null +++ b/packages/cli/test/lib/wizard/angular/codemods/main.test.ts @@ -0,0 +1,127 @@ +import { describe, expect, it } from "vitest"; +import { parseModule } from "magicast"; + +import { updateAppEntryMod } from "../../../../../src/lib/wizard/angular/codemods/main.js"; + +function getOriginalAppEntryMod() { + return parseModule(` + import { bootstrapApplication } from '@angular/platform-browser'; + import { appConfig } from './app/app.config'; + import { AppComponent } from './app/app.component'; + + bootstrapApplication(AppComponent, appConfig).catch((err) => console.error(err)); + `); +} + +describe("updateAppEntryMod", () => { + it("generates the init call without dataCollection when reduceDataCollection is false", () => { + const mod = updateAppEntryMod( + getOriginalAppEntryMod(), + "https://sentry.io/123", + { performance: true, replay: true }, + false, + ); + + const result = mod.generate().code; + + expect(result).not.toContain("dataCollection"); + expect(result).toMatchInlineSnapshot(` + "import * as Sentry from '@sentry/angular'; + import { bootstrapApplication } from '@angular/platform-browser'; + import { appConfig } from './app/app.config'; + import { AppComponent } from './app/app.component'; + + Sentry.init({ + dsn: "https://sentry.io/123", + integrations: [Sentry.browserTracingIntegration(), Sentry.replayIntegration()], + tracesSampleRate: 1, + replaysSessionSampleRate: 0.1, + replaysOnErrorSampleRate: 1 + }) + + bootstrapApplication(AppComponent, appConfig).catch((err) => console.error(err));" + `); + }); + + it("generates the init call with the dataCollection preset when reduceDataCollection is true", () => { + const mod = updateAppEntryMod( + getOriginalAppEntryMod(), + "https://sentry.io/123", + { performance: true, replay: true }, + true, + ); + + const result = mod.generate().code; + + expect(result).toContain("userInfo: false"); + expect(result).toContain( + 'httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }', + ); + expect(result).toMatchInlineSnapshot(` + "import * as Sentry from '@sentry/angular'; + import { bootstrapApplication } from '@angular/platform-browser'; + import { appConfig } from './app/app.config'; + import { AppComponent } from './app/app.component'; + + Sentry.init({ + dsn: "https://sentry.io/123", + integrations: [Sentry.browserTracingIntegration(), Sentry.replayIntegration()], + tracesSampleRate: 1, + replaysSessionSampleRate: 0.1, + replaysOnErrorSampleRate: 1, + // Turns off collection of data that could identify users. Adjust per category: + // https://docs.sentry.io/platforms/javascript/configuration/options/#dataCollection + dataCollection: { + userInfo: false, + graphQL: { document: false, variables: false }, + genAI: { inputs: false, outputs: false }, + databaseQueryData: false, + queues: false, + httpBodies: [], + httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + cookies: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + urlQueryParams: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + }, + }) + + bootstrapApplication(AppComponent, appConfig).catch((err) => console.error(err));" + `); + }); + + it("includes the dataCollection preset when all features are disabled", () => { + const mod = updateAppEntryMod( + getOriginalAppEntryMod(), + "https://sentry.io/123", + { performance: false, replay: false }, + true, + ); + + const result = mod.generate().code; + + expect(result).toMatchInlineSnapshot(` + "import * as Sentry from '@sentry/angular'; + import { bootstrapApplication } from '@angular/platform-browser'; + import { appConfig } from './app/app.config'; + import { AppComponent } from './app/app.component'; + + Sentry.init({ + dsn: "https://sentry.io/123", + // Turns off collection of data that could identify users. Adjust per category: + // https://docs.sentry.io/platforms/javascript/configuration/options/#dataCollection + dataCollection: { + userInfo: false, + graphQL: { document: false, variables: false }, + genAI: { inputs: false, outputs: false }, + databaseQueryData: false, + queues: false, + httpBodies: [], + httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + cookies: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + urlQueryParams: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + }, + }) + + bootstrapApplication(AppComponent, appConfig).catch((err) => console.error(err));" + `); + }); +}); diff --git a/packages/cli/test/lib/wizard/angular/codemods/sourcemaps.test.ts b/packages/cli/test/lib/wizard/angular/codemods/sourcemaps.test.ts new file mode 100644 index 000000000..288bdcffa --- /dev/null +++ b/packages/cli/test/lib/wizard/angular/codemods/sourcemaps.test.ts @@ -0,0 +1,256 @@ +import { describe, it, vi, expect, beforeEach } from "vitest"; +import { + addSourcemapEntryToAngularJSON, + addSourceMapsSetting, +} from "../../../../../src/lib/wizard/angular/codemods/sourcemaps.js"; + +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as AngularSourceMapsWizard from "../../../../../src/lib/wizard/sourcemaps/tools/angular.js"; + +const { readFileSyncMock, writeFileSyncMock } = vi.hoisted(() => { + return { + readFileSyncMock: vi.fn(), + writeFileSyncMock: vi.fn(), + }; +}); + +vi.mock("node:fs", async () => { + return { + ...(await vi.importActual("node:fs")), + readFileSync: readFileSyncMock, + writeFileSync: writeFileSyncMock, + }; +}); + +describe("addSourcemapEntryToAngularJSON", () => { + const configureAngularSourcemapGenerationFlowSpy = vi + .spyOn(AngularSourceMapsWizard, "configureAngularSourcemapGenerationFlow") + .mockImplementation(() => Promise.resolve()); + + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("reads and writes the `angular.json` file correctly", async () => { + const angularJsonPath = "angular.json"; + const angularJsonContent = JSON.stringify({ + projects: { + project1: { + architect: { + build: { + configurations: { + production: { + someKey: "someValue", + }, + }, + }, + }, + }, + }, + }); + + readFileSyncMock.mockReturnValue(angularJsonContent); + + await addSourcemapEntryToAngularJSON(); + + expect(readFileSyncMock).toHaveBeenCalledWith( + expect.stringContaining(angularJsonPath), + "utf-8", + ); + expect(writeFileSyncMock).toHaveBeenCalledWith( + expect.stringContaining(angularJsonPath), + JSON.stringify( + { + projects: { + project1: { + architect: { + build: { + configurations: { + production: { + someKey: "someValue", + sourceMap: true, + }, + }, + }, + }, + }, + }, + }, + null, + 2, + ), + ); + }); + + it("falls back to printing copy/paste instructions when reading fails", async () => { + readFileSyncMock.mockImplementation(() => { + throw new Error("File not found"); + }); + + await addSourcemapEntryToAngularJSON(); + + expect(configureAngularSourcemapGenerationFlowSpy).toHaveBeenCalledOnce(); + expect(writeFileSyncMock).not.toHaveBeenCalled(); + }); + + it("falls back to printing copy/paste instructions when writing fails", async () => { + const angularJsonContent = JSON.stringify({ + projects: { + project1: {}, + }, + }); + + readFileSyncMock.mockReturnValue(angularJsonContent); + writeFileSyncMock.mockImplementation(() => { + throw new Error("Write failed"); + }); + + await addSourcemapEntryToAngularJSON(); + + expect(configureAngularSourcemapGenerationFlowSpy).toHaveBeenCalledOnce(); + expect(writeFileSyncMock).toHaveBeenCalled(); + }); + + it("falls back to printing copy/paste instructions when angular.json` has no projects", async () => { + const angularJsonContent = JSON.stringify({ + projects: {}, + }); + + readFileSyncMock.mockReturnValue(angularJsonContent); + + await addSourcemapEntryToAngularJSON(); + + expect(configureAngularSourcemapGenerationFlowSpy).toHaveBeenCalledOnce(); + expect(writeFileSyncMock).not.toHaveBeenCalled(); + }); +}); + +describe("addSourceMapsSetting", () => { + it("adds sourceMap setting to angular.json", () => { + const angularJson = { + projects: { + project1: { + architect: { + build: { + configurations: { + production: {}, + }, + }, + }, + }, + project2: { + architect: {}, + }, + }, + }; + + const updatedAngularJson = addSourceMapsSetting(angularJson); + + expect(updatedAngularJson).toEqual({ + projects: { + project1: { + architect: { + build: { + configurations: { + production: { sourceMap: true }, + }, + }, + }, + }, + project2: { + architect: { + build: { + configurations: { + production: { + sourceMap: true, + }, + }, + }, + }, + }, + }, + }); + }); + + it("returns `undefined` if no projects are found", () => { + const angularJson = {}; + + const updatedAngularJson = addSourceMapsSetting(angularJson); + + expect(updatedAngularJson).toBeUndefined(); + }); + + it("returns `undefined` if projects have no architect", () => { + const angularJson = { + projects: {}, + }; + + const updatedAngularJson = addSourceMapsSetting(angularJson); + + expect(updatedAngularJson).toBeUndefined(); + }); + + it.each([ + { + projects: { + project1: { + architect: { + build: { + configurations: { + production: {}, + }, + }, + }, + }, + }, + }, + { + projects: { + project1: { + architect: { + build: { + configurations: {}, + }, + }, + }, + }, + }, + { + projects: { + project1: { + architect: { + build: {}, + }, + }, + }, + }, + { + projects: { + project1: { + architect: {}, + }, + }, + }, + { + projects: { + project1: {}, + }, + }, + ])("handles incomplete project declarations (%s)", (angularJson) => { + const updatedAngularJson = addSourceMapsSetting(angularJson); + + expect(updatedAngularJson).toEqual({ + projects: { + project1: { + architect: { + build: { + configurations: { + production: { sourceMap: true }, + }, + }, + }, + }, + }, + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/angular/example-component.test.ts b/packages/cli/test/lib/wizard/angular/example-component.test.ts new file mode 100644 index 000000000..2e8d96192 --- /dev/null +++ b/packages/cli/test/lib/wizard/angular/example-component.test.ts @@ -0,0 +1,130 @@ +import { text } from "@clack/prompts"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { + createExampleComponent, + getSentryExampleComponentCode, +} from "../../../../src/lib/wizard/angular/example-component.js"; + +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as clackUtils from "../../../../src/lib/wizard/utils/clack/index.js"; + +const fsMocks = vi.hoisted(() => ({ + existsSyncMock: vi.fn(() => true), + writeFileSyncMock: vi.fn(), + mkdirSyncMock: vi.fn(), +})); + +vi.mock("node:fs", async (importOriginal) => ({ + ...(await importOriginal()), + existsSync: fsMocks.existsSyncMock, + writeFileSync: fsMocks.writeFileSyncMock, + mkdirSync: fsMocks.mkdirSyncMock, +})); + +vi.mock("@clack/prompts", () => ({ + log: { + info: vi.fn(), + success: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + step: vi.fn(), + }, + outro: vi.fn(), + text: vi.fn(), + confirm: vi.fn(), + cancel: vi.fn(), + // passthrough for abortIfCancelled + isCancel: vi.fn().mockReturnValue(false), + spinner: vi + .fn() + .mockImplementation(() => ({ start: vi.fn(), stop: vi.fn() })), + select: vi.fn(), +})); + +describe("createExampleComponent", () => { + const showCopyPasteSnippetSpy = vi.spyOn( + clackUtils, + "showCopyPasteInstructions", + ); + + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("rejects an empty path when ./src/app is missing", async () => { + fsMocks.existsSyncMock.mockReturnValue(false); + vi.mocked(text).mockResolvedValueOnce("custom/app"); + + await createExampleComponent({ + orgSlug: "myOrg", + projectId: "123456789", + }); + fsMocks.existsSyncMock.mockReturnValue(true); + + const validate = vi.mocked(text).mock.calls[0]?.[0].validate; + expect(validate?.("")).toBe("Please enter a path."); + expect(validate?.("custom/app")).toBeUndefined(); + expect(fsMocks.mkdirSyncMock).toHaveBeenCalledWith("custom/app", { + recursive: true, + }); + }); + + it("creates an example component file", async () => { + const options = { + orgSlug: "myOrg", + projectId: "123456789", + }; + + // Mock the abortIfCancelled function to return the appRootPath + vi.spyOn(clackUtils, "abortIfCancelled").mockResolvedValue("src/app"); + + // Mock the getSentryExampleComponentCode function + const exampleComponentCode = getSentryExampleComponentCode(options); + + // Call the function to create the example component + await createExampleComponent(options); + + expect(fsMocks.writeFileSyncMock).toHaveBeenCalledWith( + "./src/app/sentry-example.component.ts", + exampleComponentCode, + ); + expect(showCopyPasteSnippetSpy).toHaveBeenCalledWith({ + codeSnippet: `import { SentryExample } from './sentry-example.component' + +@Component({ + selector: 'app-root', + standalone: true, + imports: [RouterOutlet, SentryExample], + template: \` +
+

Your Application

+ +
+ \`, +}) +`, + instructions: + "Add the example component one of your pages or components (for example, in app.component.ts).", + }); + }); +}); + +describe("getSentryExampleComponentCode", () => { + it("includes the correct issue stream URL", () => { + const exampleComponentCode = getSentryExampleComponentCode({ + orgSlug: "myOrg", + projectId: "123456789", + }); + expect(exampleComponentCode).toContain( + "https://myorg.sentry.io/issues/?project=123456789", + ); + }); + + it("does not log to the browser console", () => { + const exampleComponentCode = getSentryExampleComponentCode({ + orgSlug: "myOrg", + projectId: "123456789", + }); + expect(exampleComponentCode).not.toContain("console.log"); + }); +}); diff --git a/packages/cli/test/lib/wizard/angular/sdk-setup.test.ts b/packages/cli/test/lib/wizard/angular/sdk-setup.test.ts new file mode 100644 index 000000000..5b3e83a90 --- /dev/null +++ b/packages/cli/test/lib/wizard/angular/sdk-setup.test.ts @@ -0,0 +1,97 @@ +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { SemVer } from "semver"; +import { + initializeSentryOnApplicationEntry, + updateAppConfig, +} from "../../../../src/lib/wizard/angular/sdk-setup.js"; +import { clack } from "../../../../src/lib/wizard/utils/clack/prompts.js"; + +describe("initializeSentryOnApplicationEntry", () => { + let dir: string; + let cwd: string; + + beforeEach(() => { + cwd = process.cwd(); + dir = mkdtempSync(path.join(tmpdir(), "angular-entry-")); + process.chdir(dir); + }); + + afterEach(() => { + process.chdir(cwd); + rmSync(dir, { recursive: true, force: true }); + vi.restoreAllMocks(); + }); + + it("shows the manual setup steps and returns when src/main.ts is missing", async () => { + const error = vi.spyOn(clack.log, "error").mockImplementation(() => {}); + const warn = vi.spyOn(clack.log, "warn").mockImplementation(() => {}); + + await expect( + initializeSentryOnApplicationEntry( + "https://public@o0.ingest.sentry.io/0", + { performance: true, replay: false }, + false, + ), + ).resolves.toBeUndefined(); + + expect(error).toHaveBeenCalledWith(expect.stringContaining("main.ts")); + expect(warn).toHaveBeenCalledWith( + expect.stringContaining("guides/angular/#configure"), + ); + }); + + it("shows the manual setup steps and returns when src/app/app.config.ts does not parse", async () => { + mkdirSync(path.join(dir, "src", "app"), { recursive: true }); + writeFileSync( + path.join(dir, "src", "app", "app.config.ts"), + "export const appConfig = { providers: [ ", + ); + const error = vi.spyOn(clack.log, "error").mockImplementation(() => {}); + const warn = vi.spyOn(clack.log, "warn").mockImplementation(() => {}); + + await expect( + updateAppConfig(new SemVer("19.0.0"), true), + ).resolves.toBeUndefined(); + + expect(error).toHaveBeenCalledWith( + expect.stringContaining("app.config.ts"), + ); + expect(warn).toHaveBeenCalledWith( + expect.stringContaining("guides/angular/#configure"), + ); + }); + + it("leaves src/app/app.config.ts unchanged and reports no success when it has no providers array", async () => { + const appConfigPath = path.join(dir, "src", "app", "app.config.ts"); + const original = `import { ApplicationConfig } from '@angular/core'; + +export const appConfig: ApplicationConfig = { + providers: someVar, +}; +`; + mkdirSync(path.dirname(appConfigPath), { recursive: true }); + writeFileSync(appConfigPath, original); + vi.spyOn(clack.log, "error").mockImplementation(() => {}); + vi.spyOn(clack.log, "info").mockImplementation(() => {}); + const warn = vi.spyOn(clack.log, "warn").mockImplementation(() => {}); + const success = vi.spyOn(clack.log, "success").mockImplementation(() => {}); + + await updateAppConfig(new SemVer("19.0.0"), true); + + expect(readFileSync(appConfigPath, "utf8")).toBe(original); + expect(success).not.toHaveBeenCalled(); + expect(warn).toHaveBeenCalledWith( + expect.stringContaining("guides/angular/#configure"), + ); + }); +}); diff --git a/packages/cli/test/lib/wizard/nuxt/nuxt-wizard-version.test.ts b/packages/cli/test/lib/wizard/nuxt/nuxt-wizard-version.test.ts new file mode 100644 index 000000000..117b67031 --- /dev/null +++ b/packages/cli/test/lib/wizard/nuxt/nuxt-wizard-version.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it, vi } from "vitest"; + +import { WizardExitError } from "../../../../src/lib/errors.js"; +import { runNuxtWizard } from "../../../../src/lib/wizard/nuxt/nuxt-wizard.js"; +import { getOrAskForProjectData } from "../../../../src/lib/wizard/utils/clack/index.js"; +import { clack } from "../../../../src/lib/wizard/utils/clack/prompts.js"; + +vi.mock("../../../../src/lib/wizard/telemetry.js", async (importOriginal) => ({ + ...(await importOriginal()), + withTelemetry: (_options: unknown, fn: () => Promise) => fn(), +})); + +vi.mock("../../../../src/lib/wizard/utils/node-version.js", () => ({ + warnIfNodeVersionUnsupportedBySdkV11: vi.fn(), +})); + +vi.mock( + "../../../../src/lib/wizard/utils/clack/index.js", + async (importOriginal) => ({ + ...(await importOriginal()), + printWelcome: vi.fn(), + confirmContinueIfNoOrDirtyGitRepo: vi.fn().mockResolvedValue(undefined), + ensurePackageIsInstalled: vi.fn().mockResolvedValue(undefined), + getPackageDotJson: vi.fn().mockResolvedValue({ + dependencies: { nuxt: "latest" }, + }), + getOrAskForProjectData: vi.fn(), + }), +); + +describe("runNuxtWizard", () => { + it("treats a nuxt: latest specifier as an unsupported version instead of crashing", async () => { + const warn = vi.spyOn(clack.log, "warn").mockImplementation(() => {}); + // "No, I'll upgrade first" + vi.spyOn(clack, "select").mockResolvedValue(false); + vi.spyOn(clack, "outro").mockImplementation(() => {}); + + await expect( + runNuxtWizard({ telemetryEnabled: false, ignoreGitChanges: true }), + ).rejects.toBeInstanceOf(WizardExitError); + + expect(warn).toHaveBeenCalledWith( + expect.stringContaining("Nuxt version <3.7.0"), + ); + expect(getOrAskForProjectData).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/cli/test/lib/wizard/nuxt/nuxt-wizard.test.ts b/packages/cli/test/lib/wizard/nuxt/nuxt-wizard.test.ts new file mode 100644 index 000000000..0d24318ec --- /dev/null +++ b/packages/cli/test/lib/wizard/nuxt/nuxt-wizard.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it, vi } from "vitest"; + +import { buildOutroMessage } from "../../../../src/lib/wizard/nuxt/nuxt-wizard.js"; + +vi.mock("../../../../src/lib/wizard/utils/clack/mcp-config.js", () => ({ + offerProjectScopedMcpConfig: vi.fn().mockResolvedValue(undefined), +})); + +describe("buildOutroMessage", () => { + it("names the SentryErrorButton component the wizard creates", () => { + const message = buildOutroMessage(false, true); + expect(message).toContain("`SentryErrorButton`"); + expect(message).not.toContain("SentryExampleButton"); + }); + + it("points to the example page when one was created", () => { + const message = buildOutroMessage(true, false); + expect(message).toContain('"/sentry-example-page"'); + expect(message).not.toContain("SentryErrorButton"); + }); +}); diff --git a/packages/cli/test/lib/wizard/nuxt/sdk-example.test.ts b/packages/cli/test/lib/wizard/nuxt/sdk-example.test.ts new file mode 100644 index 000000000..ba5d917c8 --- /dev/null +++ b/packages/cli/test/lib/wizard/nuxt/sdk-example.test.ts @@ -0,0 +1,145 @@ +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { WizardExitError } from "../../../../src/lib/errors.js"; +import { reportCliError } from "../../../../src/lib/error-reporting.js"; +import { + createExampleComponent, + createExamplePage, + supportsExamplePage, +} from "../../../../src/lib/wizard/nuxt/sdk-example.js"; + +vi.mock("@clack/prompts", () => ({ + log: { + info: vi.fn(), + success: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + }, + outro: vi.fn(), +})); + +vi.mock("../../../../src/lib/error-reporting.js", () => ({ + reportCliError: vi.fn(), +})); + +const options = { + org: "my-org", + project: "my-project", + projectId: "1", + url: "https://sentry.io/", +}; + +let projectDir: string; +let originalCwd: string; + +beforeEach(() => { + originalCwd = process.cwd(); + projectDir = mkdtempSync(path.join(tmpdir(), "wizard-nuxt-example-")); + process.chdir(projectDir); +}); + +afterEach(() => { + process.chdir(originalCwd); + rmSync(projectDir, { recursive: true, force: true }); +}); + +describe("createExamplePage", () => { + it("creates the API route when the example page already exists", async () => { + mkdirSync("pages"); + writeFileSync("pages/sentry-example-page.vue", ""); + + await createExamplePage(false, options); + + expect(readFileSync("pages/sentry-example-page.vue", "utf8")).toBe( + "", + ); + expect(existsSync("server/api/sentry-example-api.js")).toBe(true); + }); + + it("keeps an existing API route", async () => { + mkdirSync("server/api", { recursive: true }); + writeFileSync("tsconfig.json", "{}"); + writeFileSync("server/api/sentry-example-api.ts", "// user's route"); + + await createExamplePage(false, options); + + expect(existsSync("pages/sentry-example-page.vue")).toBe(true); + expect(readFileSync("server/api/sentry-example-api.ts", "utf8")).toBe( + "// user's route", + ); + }); +}); + +describe("createExampleComponent", () => { + it("reports the error and exits cleanly when the component can't be written", async () => { + // A file where the components directory should be makes the write fail. + writeFileSync("components", ""); + + await expect(createExampleComponent(false)).rejects.toBeInstanceOf( + WizardExitError, + ); + expect(reportCliError).toHaveBeenCalled(); + }); +}); + +describe("supportsExamplePage", () => { + it.each([ + ["", true], + ["", true], + ["", true], + ["", true], + ["", false], + ["", false], + ])("returns %s => %s for app.vue", async (tag, expected) => { + writeFileSync("app.vue", ``); + + await expect(supportsExamplePage(false)).resolves.toBe(expected); + }); +}); + +describe("Nuxt 4 src directory", () => { + it("uses the root app.vue when there is no app/ directory", async () => { + writeFileSync("app.vue", ""); + + await expect(supportsExamplePage(true)).resolves.toBe(false); + + await createExampleComponent(true); + expect(existsSync("components/SentryErrorButton.vue")).toBe(true); + expect(existsSync("app")).toBe(false); + }); + + it("uses app/ when it exists, even with a root app.vue", async () => { + mkdirSync("app"); + writeFileSync("app.vue", ""); + + await expect(supportsExamplePage(true)).resolves.toBe(true); + + await createExampleComponent(true); + expect(existsSync("app/components/SentryErrorButton.vue")).toBe(true); + }); + + it("defaults to app/ in a project with neither", async () => { + await createExamplePage(true, options); + + expect(existsSync("app/pages/sentry-example-page.vue")).toBe(true); + }); + + it("keeps the root for Nuxt 3", async () => { + mkdirSync("app"); + + await createExampleComponent(false); + + expect(existsSync("components/SentryErrorButton.vue")).toBe(true); + }); +}); diff --git a/packages/cli/test/lib/wizard/nuxt/sdk-setup.test.ts b/packages/cli/test/lib/wizard/nuxt/sdk-setup.test.ts new file mode 100644 index 000000000..a271204af --- /dev/null +++ b/packages/cli/test/lib/wizard/nuxt/sdk-setup.test.ts @@ -0,0 +1,143 @@ +import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { SemVer } from "semver"; +import { + addNuxtOverrides, + addSDKModule, + createConfigFiles, +} from "../../../../src/lib/wizard/nuxt/sdk-setup.js"; +import { WizardExitError } from "../../../../src/lib/errors.js"; +import type { PackageManager } from "../../../../src/lib/wizard/utils/package-manager.js"; + +const { askShouldAddPackageOverrideMock } = vi.hoisted(() => ({ + askShouldAddPackageOverrideMock: vi.fn(), +})); + +vi.mock("@clack/prompts", () => ({ + log: { warn: vi.fn(), info: vi.fn(), error: vi.fn() }, + outro: vi.fn(), + confirm: vi.fn().mockResolvedValue(false), + isCancel: vi.fn().mockReturnValue(false), +})); + +vi.mock("../../../../src/lib/wizard/utils/clack/index.js", async () => ({ + ...(await vi.importActual("../../../../src/lib/wizard/utils/clack/index.js")), + askShouldAddPackageOverride: askShouldAddPackageOverrideMock, + featureSelectionPrompt: vi.fn().mockResolvedValue({ + performance: true, + replay: false, + }), +})); + +describe("addNuxtOverrides", () => { + const addOverride = vi.fn(); + const packageManager = { addOverride } as unknown as PackageManager; + + beforeEach(() => { + vi.clearAllMocks(); + askShouldAddPackageOverrideMock.mockResolvedValue(true); + }); + + it("adds an ofetch override for Nuxt < 3.14.0", async () => { + await addNuxtOverrides(packageManager, new SemVer("3.13.2")); + + expect(askShouldAddPackageOverrideMock).toHaveBeenCalledWith( + "ofetch", + "^1.4.0", + ); + expect(addOverride).toHaveBeenCalledWith("ofetch", "^1.4.0"); + }); + + it("does not add the override if the user declines", async () => { + askShouldAddPackageOverrideMock.mockResolvedValue(false); + + await addNuxtOverrides(packageManager, new SemVer("3.13.2")); + + expect(addOverride).not.toHaveBeenCalled(); + }); + + it.each(["3.14.0", "4.0.0"])( + "does not prompt for Nuxt %s", + async (version) => { + await addNuxtOverrides(packageManager, new SemVer(version)); + + expect(askShouldAddPackageOverrideMock).not.toHaveBeenCalled(); + expect(addOverride).not.toHaveBeenCalled(); + }, + ); + + it("does not prompt if the Nuxt version is unknown", async () => { + await addNuxtOverrides(packageManager, undefined); + + expect(askShouldAddPackageOverrideMock).not.toHaveBeenCalled(); + }); +}); + +describe("createConfigFiles", () => { + it("prints the dataCollection preset when the user keeps existing configs", async () => { + const dir = mkdtempSync(path.join(tmpdir(), "wizard-nuxt-config-")); + const originalCwd = process.cwd(); + const write = vi + .spyOn(process.stdout, "write") + .mockImplementation(() => true); + try { + writeFileSync(path.join(dir, "sentry.client.config.js"), ""); + writeFileSync(path.join(dir, "sentry.server.config.js"), ""); + process.chdir(dir); + + await createConfigFiles("https://key@o1.ingest.sentry.io/2", true); + + const printed = write.mock.calls.map(([chunk]) => String(chunk)); + expect(printed).toHaveLength(2); + for (const snippet of printed) { + expect(snippet).toContain("dataCollection: {"); + } + } finally { + process.chdir(originalCwd); + write.mockRestore(); + rmSync(dir, { recursive: true, force: true }); + } + }); +}); + +describe("addSDKModule", () => { + it("prints the manual steps and aborts cleanly before the config files when the config does not parse", async () => { + const dir = mkdtempSync(path.join(tmpdir(), "nuxt-module-")); + const originalCwd = process.cwd(); + const write = vi + .spyOn(process.stdout, "write") + .mockImplementation(() => true); + const config = path.join(dir, "nuxt.config.ts"); + writeFileSync(config, "export default defineNuxtConfig({ modules: [ "); + try { + process.chdir(dir); + + // The same two steps, in order, as `runNuxtWizard`'s configure-sdk step. + const configureSdk = async () => { + await addSDKModule(config, { + org: "my-org", + project: "my-project", + url: "https://sentry.io/", + selfHosted: false, + }); + await createConfigFiles("https://key@o1.ingest.sentry.io/2", false); + }; + + await expect(configureSdk()).rejects.toBeInstanceOf(WizardExitError); + expect( + write.mock.calls.some(([chunk]) => + String(chunk).includes("@sentry/nuxt/module"), + ), + ).toBe(true); + expect(existsSync(path.join(dir, "sentry.client.config.ts"))).toBe(false); + expect(existsSync(path.join(dir, "sentry.server.config.ts"))).toBe(false); + } finally { + process.chdir(originalCwd); + write.mockRestore(); + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/cli/test/lib/wizard/nuxt/templates.test.ts b/packages/cli/test/lib/wizard/nuxt/templates.test.ts new file mode 100644 index 000000000..65c89298a --- /dev/null +++ b/packages/cli/test/lib/wizard/nuxt/templates.test.ts @@ -0,0 +1,495 @@ +import { describe, expect, it, vi } from "vitest"; +import { + getDefaultNuxtConfig, + getNuxtModuleFallbackTemplate, + getSentryConfigContents, + getSentryExamplePageTemplate, +} from "../../../../src/lib/wizard/nuxt/templates.js"; + +vi.mock("../../../../src/lib/wizard/utils/clack/mcp-config.js", () => ({ + offerProjectScopedMcpConfig: vi.fn().mockResolvedValue(undefined), +})); + +describe("Nuxt code templates", () => { + describe("getDefaultNuxtConfig", () => { + it("returns a default nuxt config", () => { + expect(getDefaultNuxtConfig()).toMatchInlineSnapshot(` + "// https://nuxt.com/docs/api/configuration/nuxt-config + export default defineNuxtConfig({ + compatibilityDate: '2024-04-03', + devtools: { enabled: true } + }) + " +`); + }); + }); + + describe("getSentryConfigContents", () => { + describe("client config", () => { + it("generates Sentry config with all features enabled", () => { + const template = getSentryConfigContents( + "https://sentry.io/123", + "client", + { + performance: true, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "import * as Sentry from "@sentry/nuxt"; + + Sentry.init({ + // If set up, you can use your runtime config here + // dsn: useRuntimeConfig().public.sentry.dsn, + dsn: "https://sentry.io/123", + + // We recommend adjusting this value in production, or using tracesSampler + // for finer control + tracesSampleRate: 1.0, + + // This sets the sample rate to be 10%. You may want this to be 100% while + // in development and sample at a lower rate in production + replaysSessionSampleRate: 0.1, + + // If the entire session is not sampled, use the below sample rate to sample + // sessions when an error occurs. + replaysOnErrorSampleRate: 1.0, + + // If you don't want to use Session Replay, just remove the line below: + integrations: [Sentry.replayIntegration()], + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nuxt/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + + // Setting this option to true will print useful information to the console while you're setting up Sentry. + debug: false, + }); + " + `); + }); + + it("generates Sentry config with performance monitoring disabled", () => { + const template = getSentryConfigContents( + "https://sentry.io/123", + "client", + { + performance: false, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "import * as Sentry from "@sentry/nuxt"; + + Sentry.init({ + // If set up, you can use your runtime config here + // dsn: useRuntimeConfig().public.sentry.dsn, + dsn: "https://sentry.io/123", + + // This sets the sample rate to be 10%. You may want this to be 100% while + // in development and sample at a lower rate in production + replaysSessionSampleRate: 0.1, + + // If the entire session is not sampled, use the below sample rate to sample + // sessions when an error occurs. + replaysOnErrorSampleRate: 1.0, + + // If you don't want to use Session Replay, just remove the line below: + integrations: [Sentry.replayIntegration()], + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nuxt/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + + // Setting this option to true will print useful information to the console while you're setting up Sentry. + debug: false, + }); + " + `); + }); + + it("generates Sentry config with session replay disabled", () => { + const template = getSentryConfigContents( + "https://sentry.io/123", + "client", + { + performance: true, + replay: false, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "import * as Sentry from "@sentry/nuxt"; + + Sentry.init({ + // If set up, you can use your runtime config here + // dsn: useRuntimeConfig().public.sentry.dsn, + dsn: "https://sentry.io/123", + + // We recommend adjusting this value in production, or using tracesSampler + // for finer control + tracesSampleRate: 1.0, + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nuxt/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + + // Setting this option to true will print useful information to the console while you're setting up Sentry. + debug: false, + }); + " + `); + }); + + it("generates Sentry config with performance monitoring and session replay disabled", () => { + const template = getSentryConfigContents( + "https://sentry.io/123", + "client", + { + performance: false, + replay: false, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "import * as Sentry from "@sentry/nuxt"; + + Sentry.init({ + // If set up, you can use your runtime config here + // dsn: useRuntimeConfig().public.sentry.dsn, + dsn: "https://sentry.io/123", + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nuxt/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + + // Setting this option to true will print useful information to the console while you're setting up Sentry. + debug: false, + }); + " + `); + }); + + it("generates Sentry config with all features disabled", () => { + const template = getSentryConfigContents( + "https://sentry.io/123", + "client", + { + performance: false, + replay: false, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "import * as Sentry from "@sentry/nuxt"; + + Sentry.init({ + // If set up, you can use your runtime config here + // dsn: useRuntimeConfig().public.sentry.dsn, + dsn: "https://sentry.io/123", + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nuxt/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + + // Setting this option to true will print useful information to the console while you're setting up Sentry. + debug: false, + }); + " + `); + }); + + it("generates Sentry config with reduced data collection", () => { + const template = getSentryConfigContents( + "https://sentry.io/123", + "client", + { + performance: true, + replay: true, + }, + true, + ); + + expect(template).toContain("userInfo: false,"); + expect(template).toContain( + 'httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] },', + ); + expect(template).not.toContain( + "// To disable sending user data and HTTP bodies, uncomment the lines below.", + ); + expect(template).toMatchInlineSnapshot(` + "import * as Sentry from "@sentry/nuxt"; + + Sentry.init({ + // If set up, you can use your runtime config here + // dsn: useRuntimeConfig().public.sentry.dsn, + dsn: "https://sentry.io/123", + + // We recommend adjusting this value in production, or using tracesSampler + // for finer control + tracesSampleRate: 1.0, + + // This sets the sample rate to be 10%. You may want this to be 100% while + // in development and sample at a lower rate in production + replaysSessionSampleRate: 0.1, + + // If the entire session is not sampled, use the below sample rate to sample + // sessions when an error occurs. + replaysOnErrorSampleRate: 1.0, + + // If you don't want to use Session Replay, just remove the line below: + integrations: [Sentry.replayIntegration()], + + // Turns off collection of data that could identify users. Adjust per category: + // https://docs.sentry.io/platforms/javascript/configuration/options/#dataCollection + dataCollection: { + userInfo: false, + graphQL: { document: false, variables: false }, + genAI: { inputs: false, outputs: false }, + databaseQueryData: false, + queues: false, + httpBodies: [], + httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + cookies: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + urlQueryParams: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + }, + + // Setting this option to true will print useful information to the console while you're setting up Sentry. + debug: false, + }); + " + `); + }); + }); + + describe("server config", () => { + it("generates Sentry config with all features enabled", () => { + const template = getSentryConfigContents( + "https://sentry.io/123", + "server", + { + performance: true, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "import * as Sentry from "@sentry/nuxt"; + + Sentry.init({ + dsn: "https://sentry.io/123", + + // We recommend adjusting this value in production, or using tracesSampler + // for finer control + tracesSampleRate: 1.0, + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nuxt/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + + // Setting this option to true will print useful information to the console while you're setting up Sentry. + debug: false, + }); + " + `); + }); + + it("generates Sentry config with performance monitoring disabled", () => { + const template = getSentryConfigContents( + "https://sentry.io/123", + "server", + { + performance: false, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "import * as Sentry from "@sentry/nuxt"; + + Sentry.init({ + dsn: "https://sentry.io/123", + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nuxt/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + + // Setting this option to true will print useful information to the console while you're setting up Sentry. + debug: false, + }); + " + `); + }); + + it("generates Sentry config with all features disabled", () => { + const template = getSentryConfigContents( + "https://sentry.io/123", + "server", + { + performance: false, + replay: false, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "import * as Sentry from "@sentry/nuxt"; + + Sentry.init({ + dsn: "https://sentry.io/123", + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nuxt/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + + // Setting this option to true will print useful information to the console while you're setting up Sentry. + debug: false, + }); + " + `); + }); + + it("generates Sentry config with reduced data collection", () => { + const template = getSentryConfigContents( + "https://sentry.io/123", + "server", + { + performance: true, + replay: false, + }, + true, + ); + + expect(template).toContain("userInfo: false,"); + expect(template).toContain( + 'httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] },', + ); + expect(template).not.toContain( + "// To disable sending user data and HTTP bodies, uncomment the lines below.", + ); + expect(template).toMatchInlineSnapshot(` + "import * as Sentry from "@sentry/nuxt"; + + Sentry.init({ + dsn: "https://sentry.io/123", + + // We recommend adjusting this value in production, or using tracesSampler + // for finer control + tracesSampleRate: 1.0, + + // Turns off collection of data that could identify users. Adjust per category: + // https://docs.sentry.io/platforms/javascript/configuration/options/#dataCollection + dataCollection: { + userInfo: false, + graphQL: { document: false, variables: false }, + genAI: { inputs: false, outputs: false }, + databaseQueryData: false, + queues: false, + httpBodies: [], + httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + cookies: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + urlQueryParams: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + }, + + // Setting this option to true will print useful information to the console while you're setting up Sentry. + debug: false, + }); + " + `); + }); + }); + }); + + describe("getNuxtModuleFallbackTemplate", () => { + it("generates configuration options for the nuxt config", () => { + const template = getNuxtModuleFallbackTemplate({ + org: "my-org", + project: "my-project", + url: "https://sentry.io", + selfHosted: false, + }); + + expect(template).toMatchInlineSnapshot(` + " modules: ["@sentry/nuxt/module"], + sentry: { + org: "my-org", + project: "my-project", + sourcemaps: { + // This will delete all .map files in the build output after uploading them to Sentry. Modify as needed. + // For more information, see: https://docs.sentry.io/platforms/javascript/guides/nuxt/sourcemaps/ + filesToDeleteAfterUpload: ['.*/**/*.map'] + }, + }, + sourcemap: { client: "hidden" }," + `); + }); + + it("generates configuration options for the nuxt config with self-hosted url", () => { + const template = getNuxtModuleFallbackTemplate({ + org: "my-org", + project: "my-project", + url: "https://sentry.example.com", + selfHosted: true, + }); + + expect(template).toMatchInlineSnapshot(` + " modules: ["@sentry/nuxt/module"], + sentry: { + org: "my-org", + project: "my-project", + sentryUrl: "https://sentry.example.com", + sourcemaps: { + // This will delete all .map files in the build output after uploading them to Sentry. Modify as needed. + // For more information, see: https://docs.sentry.io/platforms/javascript/guides/nuxt/sourcemaps/ + filesToDeleteAfterUpload: ['.*/**/*.map'] + }, + }, + sourcemap: { client: "hidden" }," + `); + }); + }); + + describe("getSentryExamplePageTemplate", () => { + it("lets the API route's 500 reject so the page shows its success state", () => { + const template = getSentryExamplePageTemplate({ + org: "my-org", + projectId: "1", + }); + expect(template).toContain("$fetch('/api/sentry-example-api'"); + expect(template).not.toContain("ignoreResponseError"); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/nuxt/utils.test.ts b/packages/cli/test/lib/wizard/nuxt/utils.test.ts new file mode 100644 index 000000000..77b55e993 --- /dev/null +++ b/packages/cli/test/lib/wizard/nuxt/utils.test.ts @@ -0,0 +1,46 @@ +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { isNuxtV4 } from "../../../../src/lib/wizard/nuxt/utils.js"; + +vi.mock("@clack/prompts", () => ({ + confirm: vi.fn(), + isCancel: vi.fn().mockReturnValue(false), +})); + +let dir: string; +let nuxtConfig: string; + +beforeEach(() => { + dir = mkdtempSync(path.join(tmpdir(), "wizard-nuxt-utils-")); + nuxtConfig = path.join(dir, "nuxt.config.ts"); + writeFileSync(nuxtConfig, "export default defineNuxtConfig({});\n"); +}); + +afterEach(() => { + rmSync(dir, { recursive: true, force: true }); +}); + +describe("isNuxtV4", () => { + it.each(["^4.0.0", "4.0.0-rc.1", "^4.2.0-beta.1"])( + "detects %s as Nuxt 4", + async (version) => { + expect(await isNuxtV4(nuxtConfig, version)).toBe(true); + }, + ); + + it("does not treat Nuxt 3 as Nuxt 4", async () => { + expect(await isNuxtV4(nuxtConfig, "^3.15.0")).toBe(false); + }); + + it("reads compatibilityVersion when the version is unknown", async () => { + writeFileSync( + nuxtConfig, + "export default defineNuxtConfig({ future: { compatibilityVersion: 4 } });\n", + ); + expect(await isNuxtV4(nuxtConfig, undefined)).toBe(true); + }); +}); diff --git a/packages/cli/test/lib/wizard/sourcemaps/ci.test.ts b/packages/cli/test/lib/wizard/sourcemaps/ci.test.ts new file mode 100644 index 000000000..e0f1fc16b --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/ci.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from "vitest"; + +import { getCIEnvVars } from "../../../../src/lib/wizard/sourcemaps/ci.js"; + +describe("getCIEnvVars", () => { + it("lists only the auth token without an upload target", () => { + expect(getCIEnvVars("tok", undefined)).toEqual(["SENTRY_AUTH_TOKEN=tok"]); + }); + + it("lists only the auth token for sentry.io, which resolves the DSN", () => { + expect( + getCIEnvVars("tok", { org: "my-org", project: "my-project" }), + ).toEqual(["SENTRY_AUTH_TOKEN=tok"]); + }); + + it("adds the org, project, and URL for self-hosted Sentry", () => { + expect( + getCIEnvVars("tok", { + org: "my-org", + project: "my-project", + url: "https://sentry.example.com/", + }), + ).toEqual([ + "SENTRY_AUTH_TOKEN=tok", + "SENTRY_ORG=my-org", + "SENTRY_PROJECT=my-project", + "SENTRY_URL=https://sentry.example.com/", + ]); + }); +}); diff --git a/packages/cli/test/lib/wizard/sourcemaps/tools/angular.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/angular.test.ts new file mode 100644 index 000000000..082add11d --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/angular.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it, vi } from "vitest"; + +import { configureAngularSourcemapGenerationFlow } from "../../../../../src/lib/wizard/sourcemaps/tools/angular.js"; +import { clack } from "../../../../../src/lib/wizard/utils/clack/prompts.js"; + +describe("configureAngularSourcemapGenerationFlow", () => { + it("shows sourceMap under the production configuration, like the automatic angular.json edit", async () => { + vi.spyOn(clack.log, "info").mockImplementation(() => {}); + vi.spyOn(clack, "select").mockResolvedValue(true); + const rawOutput = vi.spyOn(clack, "rawOutput").mockImplementation(() => {}); + + await configureAngularSourcemapGenerationFlow(); + + const snippet = rawOutput.mock.calls.map(([value]) => value).join("\n"); + expect(snippet).toMatch( + /"configurations": \{\s*"production": \{[\s\S]*"sourceMap": true/, + ); + expect(snippet).not.toContain('"options"'); + }); +}); diff --git a/packages/cli/test/lib/wizard/sourcemaps/tools/sentry-cli.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/sentry-cli.test.ts new file mode 100644 index 000000000..556857727 --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/sentry-cli.test.ts @@ -0,0 +1,309 @@ +import { mkdtempSync, promises, realpathSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { + addSentryCommandToBuildCommand, + configureSentryCLI, + getSentryCliNpmScript, + SENTRY_CLI_PACKAGE_SPEC, + setSentryCliRcDefaults, +} from "../../../../../src/lib/wizard/sourcemaps/tools/sentry-cli.js"; +import { CLI_VERSION } from "../../../../../src/lib/constants.js"; + +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as packageManagerHelpers from "../../../../../src/lib/wizard/utils/package-manager.js"; +import { + getPackageDotJson, + installPackage, +} from "../../../../../src/lib/wizard/utils/clack/index.js"; + +import { vi, it, describe, expect, afterEach } from "vitest"; + +const { selectMock, textMock } = vi.hoisted(() => ({ + selectMock: vi.fn().mockResolvedValue(true), + textMock: vi.fn(), +})); + +const writeFileSpy = vi + .spyOn(promises, "writeFile") + .mockImplementation(() => Promise.resolve()); + +vi.mock("@clack/prompts", () => { + return { + log: { + info: vi.fn(), + success: vi.fn(), + }, + confirm: vi.fn().mockResolvedValue(true), + select: selectMock, + text: textMock, + isCancel: vi.fn().mockReturnValue(false), + }; +}); +vi.mock("../../../../../src/lib/wizard/utils/clack/index.js", async () => ({ + ...(await vi.importActual( + "../../../../../src/lib/wizard/utils/clack/index.js", + )), + installPackage: vi.fn().mockResolvedValue(undefined), + addSentryCliConfig: vi.fn().mockResolvedValue(undefined), + getPackageDotJson: vi.fn().mockResolvedValue({ + scripts: { + build: "tsc", + }, + version: "1.0.0", + }), +})); + +describe("addSentryCommandToBuildCommand", () => { + afterEach(() => { + vi.clearAllMocks(); + }); + it.each([ + [ + packageManagerHelpers.NPM, + packageManagerHelpers.PNPM, + packageManagerHelpers.YARN_V1, + packageManagerHelpers.YARN_V2, + packageManagerHelpers.BUN, + packageManagerHelpers.DENO, + ], + ])("adds the cli command to the script command (%s)", async (_, pacMan) => { + vi.spyOn(packageManagerHelpers, "_detectPackageManger").mockReturnValue( + pacMan, + ); + await addSentryCommandToBuildCommand(); + expect(writeFileSpy).toHaveBeenCalledWith( + expect.stringContaining("package.json"), + expect.stringContaining( + `tsc && ${pacMan.runScriptCommand} sentry:sourcemaps`, + ), + ); + }); + + it("does not add the cli command to the script command if it is already in there", async () => { + vi.mocked(getPackageDotJson).mockResolvedValue({ + scripts: { + build: "tsc && sentry:sourcemaps", + }, + version: "1.0.0", + }); + + await addSentryCommandToBuildCommand(); + + expect(writeFileSpy).not.toHaveBeenCalled(); + }); + + it("does not ask for a CI step when the build command already runs the script", async () => { + // A fresh module, so `addedToBuildCommand` starts out false + vi.resetModules(); + const { getPackageDotJson: freshGetPackageDotJson } = + await import("../../../../../src/lib/wizard/utils/clack/index.js"); + vi.mocked(freshGetPackageDotJson).mockResolvedValue({ + scripts: { + build: "tsc && sentry:sourcemaps", + }, + version: "1.0.0", + }); + const sentryCli = + await import("../../../../../src/lib/wizard/sourcemaps/tools/sentry-cli.js"); + + await sentryCli.addSentryCommandToBuildCommand(); + await sentryCli.setupNpmScriptInCI(); + + expect(selectMock).not.toHaveBeenCalled(); + }); +}); + +describe("getSentryCliNpmScript", () => { + it("uploads with the v4 sentry command, without org or project flags", () => { + expect(getSentryCliNpmScript("./dist")).toBe( + "sentry sourcemap upload ./dist", + ); + }); + + it.each(["dist", ".", "./build/client"])( + "leaves the plain path %s unquoted", + (artifactPath) => { + expect(getSentryCliNpmScript(artifactPath)).toBe( + `sentry sourcemap upload ${artifactPath}`, + ); + }, + ); + + it.each([ + ["dist/my app", '"dist/my app"'], + ["out/(client)", '"out/(client)"'], + ['dist/a"b', '"dist/a\\"b"'], + ["dist/$HOME", '"dist/\\$HOME"'], + ])("double-quotes %s as %s", (artifactPath, quoted) => { + expect(getSentryCliNpmScript(artifactPath)).toBe( + `sentry sourcemap upload ${quoted}`, + ); + }); +}); + +describe("configureSentryCLI", () => { + it("uses . for an absolute artifact path that is the project root", async () => { + const dir = realpathSync(mkdtempSync(path.join(tmpdir(), "sentry-cli-"))); + const originalCwd = process.cwd(); + try { + process.chdir(dir); + textMock.mockResolvedValueOnce(dir); + // Don't append the script to the build command. + selectMock.mockResolvedValueOnce(false); + vi.mocked(getPackageDotJson).mockResolvedValue({ + scripts: { build: "tsc" }, + version: "1.0.0", + }); + + await configureSentryCLI( + { + orgSlug: "my-org", + projectSlug: "my-project", + selfHosted: false, + url: "https://sentry.io/", + authToken: "token", + }, + () => Promise.resolve(), + true, + ); + + expect(writeFileSpy).toHaveBeenCalledWith( + expect.stringContaining("package.json"), + expect.stringContaining( + '"sentry:sourcemaps": "sentry sourcemap upload ."', + ), + ); + } finally { + process.chdir(originalCwd); + rmSync(dir, { recursive: true, force: true }); + } + }); +}); + +describe("configureSentryCLI forceInstall", () => { + it.each([true, false])( + "passes forceInstall=%s to the sentry CLI install", + async (forceInstall) => { + const dir = realpathSync( + mkdtempSync(path.join(tmpdir(), "sentry-cli-force-")), + ); + const originalCwd = process.cwd(); + try { + process.chdir(dir); + textMock.mockResolvedValueOnce(dir); + selectMock.mockResolvedValueOnce(false); + vi.mocked(getPackageDotJson).mockResolvedValue({ + scripts: { build: "tsc" }, + version: "1.0.0", + }); + + await configureSentryCLI( + { + orgSlug: "my-org", + projectSlug: "my-project", + selfHosted: false, + url: "https://sentry.io/", + authToken: "token", + forceInstall, + }, + () => Promise.resolve(), + true, + ); + + expect(installPackage).toHaveBeenLastCalledWith( + expect.objectContaining({ + packageName: SENTRY_CLI_PACKAGE_SPEC, + forceInstall, + }), + ); + } finally { + process.chdir(originalCwd); + rmSync(dir, { recursive: true, force: true }); + } + }, + ); +}); + +describe("SENTRY_CLI_PACKAGE_SPEC", () => { + it("installs the CLI major the wizard runs on", () => { + expect(SENTRY_CLI_PACKAGE_SPEC).toBe( + `sentry@${CLI_VERSION.split(".")[0]}.x`, + ); + expect(SENTRY_CLI_PACKAGE_SPEC).toMatch(/^sentry@\d+\.x$/); + }); + + it("has no shell metacharacters", () => { + expect(SENTRY_CLI_PACKAGE_SPEC).not.toMatch(/[<>|&;^$`'" ]/); + }); +}); + +describe("setSentryCliRcDefaults", () => { + const values = { org: "my-org", project: "my-project" }; + + it("creates a [defaults] section in an empty file", () => { + expect(setSentryCliRcDefaults("", values)).toBe( + "[defaults]\norg=my-org\nproject=my-project\n", + ); + }); + + it("appends [defaults] after other sections and keeps them", () => { + expect(setSentryCliRcDefaults("[auth]\ntoken=abc\n", values)).toBe( + "[auth]\ntoken=abc\n\n[defaults]\norg=my-org\nproject=my-project\n", + ); + expect(setSentryCliRcDefaults("[auth]\ntoken=abc", values)).toBe( + "[auth]\ntoken=abc\n\n[defaults]\norg=my-org\nproject=my-project\n", + ); + }); + + it("updates existing keys and keeps other keys, comments, and sections", () => { + const contents = [ + "; managed by hand", + "[defaults]", + "url = https://sentry.example.com/", + "org = old-org", + "", + "[auth]", + "token=abc", + "", + ].join("\n"); + + expect(setSentryCliRcDefaults(contents, values)).toBe( + [ + "; managed by hand", + "[defaults]", + "project=my-project", + "url = https://sentry.example.com/", + "org=my-org", + "", + "[auth]", + "token=abc", + "", + ].join("\n"), + ); + }); + + it("does not touch org or project keys outside [defaults]", () => { + expect( + setSentryCliRcDefaults("[other]\norg=keep\n[DEFAULTS]\n", values), + ).toBe("[other]\norg=keep\n[DEFAULTS]\norg=my-org\nproject=my-project\n"); + }); + + it("updates keys in every [defaults] section", () => { + expect( + setSentryCliRcDefaults( + "[defaults]\norg=a\n[auth]\ntoken=t\n[defaults]\nproject=b\n", + values, + ), + ).toBe( + "[defaults]\norg=my-org\n[auth]\ntoken=t\n[defaults]\nproject=my-project\n", + ); + }); + + it("keeps CRLF line endings on updated lines", () => { + expect( + setSentryCliRcDefaults("[defaults]\r\norg=a\r\nproject=b\r\n", values), + ).toBe("[defaults]\r\norg=my-org\r\nproject=my-project\r\n"); + }); +}); diff --git a/packages/cli/test/lib/wizard/sourcemaps/tools/sentryclirc-file.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/sentryclirc-file.test.ts new file mode 100644 index 000000000..a672f149c --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/sentryclirc-file.test.ts @@ -0,0 +1,131 @@ +/** + * `.sentryclirc` written by the wizard, read back the way v4 reads it. + * + * Writes the `[defaults]` org/project (and the self-hosted URL) and the + * `[auth]` token into a real temp dir in both orders and checks that + * `loadSentryCliRc` resolves them, and that `.sentryclirc` ends up in + * `.gitignore`. + */ + +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { + clearSentryCliRcCache, + loadSentryCliRc, +} from "../../../../../src/lib/sentryclirc.js"; +import { addUploadTargetToSentryCliRc } from "../../../../../src/lib/wizard/sourcemaps/tools/sentry-cli.js"; +import { addSentryCliConfig } from "../../../../../src/lib/wizard/utils/clack/index.js"; + +vi.mock("@clack/prompts", () => ({ + log: { + info: vi.fn(), + success: vi.fn(), + warn: vi.fn(), + warning: vi.fn(), + error: vi.fn(), + }, +})); + +let projectDir: string; +let configDir: string; +let originalCwd: string; +let originalConfigDir: string | undefined; + +beforeEach(() => { + originalCwd = process.cwd(); + originalConfigDir = process.env["SENTRY_CONFIG_DIR"]; + projectDir = mkdtempSync(path.join(tmpdir(), "wizard-rc-")); + // An empty config dir so a global ~/.sentryclirc can't leak in. + configDir = mkdtempSync(path.join(tmpdir(), "wizard-rc-config-")); + process.env["SENTRY_CONFIG_DIR"] = configDir; + writeFileSync(path.join(projectDir, ".gitignore"), "node_modules\n"); + process.chdir(projectDir); + clearSentryCliRcCache(); +}); + +afterEach(() => { + process.chdir(originalCwd); + if (originalConfigDir === undefined) { + delete process.env["SENTRY_CONFIG_DIR"]; + } else { + process.env["SENTRY_CONFIG_DIR"] = originalConfigDir; + } + clearSentryCliRcCache(); + rmSync(projectDir, { recursive: true, force: true }); + rmSync(configDir, { recursive: true, force: true }); +}); + +const rcPath = (): string => path.join(projectDir, ".sentryclirc"); + +function writeDefaults(selfHostedUrl?: string): Promise { + return addUploadTargetToSentryCliRc({ + orgSlug: "my-org", + projectSlug: "my-project", + selfHosted: selfHostedUrl !== undefined, + url: selfHostedUrl ?? "https://sentry.io/", + authToken: "sntrys_tok", + }); +} + +async function expectV4ReadsAll(): Promise { + const config = await loadSentryCliRc(projectDir); + expect(config.org).toBe("my-org"); + expect(config.project).toBe("my-project"); + expect(config.token).toBe("sntrys_tok"); + expect( + readFileSync(path.join(projectDir, ".gitignore"), "utf8").split("\n"), + ).toContain(".sentryclirc"); +} + +describe(".sentryclirc written by the wizard", () => { + it("keeps [auth] when [defaults] is written first", async () => { + await writeDefaults(); + await addSentryCliConfig({ authToken: "sntrys_tok" }); + await expectV4ReadsAll(); + }); + + it("keeps [auth] when [defaults] is written after the token", async () => { + await addSentryCliConfig({ authToken: "sntrys_tok" }); + await writeDefaults(); + await expectV4ReadsAll(); + }); + + it("writes no URL for sentry.io", async () => { + await writeDefaults(); + await addSentryCliConfig({ authToken: "sntrys_tok" }); + await expectV4ReadsAll(); + expect(readFileSync(rcPath(), "utf8")).not.toMatch(/^url=/m); + }); + + it("writes the self-hosted URL next to [auth], in either order", async () => { + await addSentryCliConfig({ authToken: "sntrys_tok" }); + await writeDefaults("https://sentry.example.com/"); + await expectV4ReadsAll(); + expect((await loadSentryCliRc(projectDir)).url).toBe( + "https://sentry.example.com/", + ); + + rmSync(rcPath()); + clearSentryCliRcCache(); + await writeDefaults("https://sentry.example.com/"); + await addSentryCliConfig({ authToken: "sntrys_tok" }); + await expectV4ReadsAll(); + expect((await loadSentryCliRc(projectDir)).url).toBe( + "https://sentry.example.com/", + ); + }); + + it("keeps the user's other keys", async () => { + writeFileSync(rcPath(), "[defaults]\nurl=https://sentry.example.com/\n"); + await writeDefaults(); + await addSentryCliConfig({ authToken: "sntrys_tok" }); + await expectV4ReadsAll(); + expect((await loadSentryCliRc(projectDir)).url).toBe( + "https://sentry.example.com/", + ); + }); +});