From 949060de6ede9e82943d381bbbc379f775ed6e5b Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:48:12 +0000 Subject: [PATCH 01/20] feat(cli): add sentry wizard with Next.js Start moving getsentry/sentry-wizard into the CLI as `sentry wizard`. This adds the command with the `@sentry/wizard` integrations and flags (`-i`, `--url`, `--org`, `--project`, `--saas`, `--spotlight`, and the rest), the shared wizard helpers, and the Next.js flow. The other integrations report that they are not available in this version yet. The wizard logs in with the CLI's own login: a stored `sentry auth login` session, an agent handoff, or the device flow, instead of the `account/settings/wizard/` browser flow. It then picks or creates the project, reads its DSN, and creates an org auth token for source map uploads. Telemetry goes through the CLI's client. `sentry init` stays the agent setup guide; its help now points to `sentry wizard` for the interactive setup. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .../cli-docs/src/content/docs/contributing.md | 3 +- .../cli-docs/src/fragments/commands/wizard.md | 24 + packages/cli/package.json | 1 + .../sentry-cli/skills/sentry-cli/SKILL.md | 8 + .../skills/sentry-cli/references/wizard.md | 44 + packages/cli/src/app.ts | 2 + packages/cli/src/command-manifest.ts | 1 + packages/cli/src/commands/init.ts | 4 +- packages/cli/src/commands/wizard.ts | 221 ++ packages/cli/src/lib/env-registry.ts | 18 + packages/cli/src/lib/errors.ts | 15 + packages/cli/src/lib/telemetry.ts | 13 + .../src/lib/wizard/nextjs/nextjs-wizard.ts | 1325 ++++++++++++ .../cli/src/lib/wizard/nextjs/templates.ts | 910 +++++++++ packages/cli/src/lib/wizard/nextjs/utils.ts | 182 ++ packages/cli/src/lib/wizard/run.ts | 128 ++ packages/cli/src/lib/wizard/sourcemaps/ci.ts | 130 ++ packages/cli/src/lib/wizard/telemetry.ts | 78 + .../cli/src/lib/wizard/utils/clack/index.ts | 1781 +++++++++++++++++ .../src/lib/wizard/utils/clack/mcp-config.ts | 639 ++++++ .../cli/src/lib/wizard/utils/clack/prompts.ts | 71 + .../src/lib/wizard/utils/data-collection.ts | 122 ++ packages/cli/src/lib/wizard/utils/debug.ts | 32 + packages/cli/src/lib/wizard/utils/git.ts | 75 + .../cli/src/lib/wizard/utils/node-version.ts | 50 + .../cli/src/lib/wizard/utils/package-json.ts | 186 ++ .../src/lib/wizard/utils/package-manager.ts | 239 +++ .../cli/src/lib/wizard/utils/project-data.ts | 479 +++++ packages/cli/src/lib/wizard/utils/semver.ts | 65 + packages/cli/src/lib/wizard/utils/types.ts | 104 + packages/cli/src/top-level-briefs.ts | 1 + packages/cli/test/commands/wizard.test.ts | 131 ++ .../test/lib/wizard/nextjs/templates.test.ts | 963 +++++++++ .../cli/test/lib/wizard/nextjs/utils.test.ts | 232 +++ .../wizard-double-wrap-prevention.test.ts | 300 +++ .../test/lib/wizard/utils/clack/index.test.ts | 719 +++++++ .../lib/wizard/utils/clack/mcp-config.test.ts | 1049 ++++++++++ .../lib/wizard/utils/data-collection.test.ts | 92 + .../cli/test/lib/wizard/utils/git.test.ts | 126 ++ .../lib/wizard/utils/node-version.test.ts | 69 + .../lib/wizard/utils/package-json.test.ts | 594 ++++++ .../lib/wizard/utils/package-manager.test.ts | 37 + .../lib/wizard/utils/project-data.test.ts | 252 +++ pnpm-lock.yaml | 50 + 44 files changed, 11563 insertions(+), 2 deletions(-) create mode 100644 apps/cli-docs/src/fragments/commands/wizard.md create mode 100644 packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md create mode 100644 packages/cli/src/commands/wizard.ts create mode 100644 packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts create mode 100644 packages/cli/src/lib/wizard/nextjs/templates.ts create mode 100644 packages/cli/src/lib/wizard/nextjs/utils.ts create mode 100644 packages/cli/src/lib/wizard/run.ts create mode 100644 packages/cli/src/lib/wizard/sourcemaps/ci.ts create mode 100644 packages/cli/src/lib/wizard/telemetry.ts create mode 100644 packages/cli/src/lib/wizard/utils/clack/index.ts create mode 100644 packages/cli/src/lib/wizard/utils/clack/mcp-config.ts create mode 100644 packages/cli/src/lib/wizard/utils/clack/prompts.ts create mode 100644 packages/cli/src/lib/wizard/utils/data-collection.ts create mode 100644 packages/cli/src/lib/wizard/utils/debug.ts create mode 100644 packages/cli/src/lib/wizard/utils/git.ts create mode 100644 packages/cli/src/lib/wizard/utils/node-version.ts create mode 100644 packages/cli/src/lib/wizard/utils/package-json.ts create mode 100644 packages/cli/src/lib/wizard/utils/package-manager.ts create mode 100644 packages/cli/src/lib/wizard/utils/project-data.ts create mode 100644 packages/cli/src/lib/wizard/utils/semver.ts create mode 100644 packages/cli/src/lib/wizard/utils/types.ts create mode 100644 packages/cli/test/commands/wizard.test.ts create mode 100644 packages/cli/test/lib/wizard/nextjs/templates.test.ts create mode 100644 packages/cli/test/lib/wizard/nextjs/utils.test.ts create mode 100644 packages/cli/test/lib/wizard/nextjs/wizard-double-wrap-prevention.test.ts create mode 100644 packages/cli/test/lib/wizard/utils/clack/index.test.ts create mode 100644 packages/cli/test/lib/wizard/utils/clack/mcp-config.test.ts create mode 100644 packages/cli/test/lib/wizard/utils/data-collection.test.ts create mode 100644 packages/cli/test/lib/wizard/utils/git.test.ts create mode 100644 packages/cli/test/lib/wizard/utils/node-version.test.ts create mode 100644 packages/cli/test/lib/wizard/utils/package-json.test.ts create mode 100644 packages/cli/test/lib/wizard/utils/package-manager.test.ts create mode 100644 packages/cli/test/lib/wizard/utils/project-data.test.ts diff --git a/apps/cli-docs/src/content/docs/contributing.md b/apps/cli-docs/src/content/docs/contributing.md index c10e6eb026..208c1d8747 100644 --- a/apps/cli-docs/src/content/docs/contributing.md +++ b/apps/cli-docs/src/content/docs/contributing.md @@ -97,7 +97,8 @@ toolkit/ │ │ │ ├── init.ts # Print instructions for a coding agent to set up Sentry │ │ │ ├── mcp.ts # Start a local Sentry MCP server │ │ │ ├── schema.ts # Browse the Sentry API schema -│ │ │ └── wasm-split.ts# Add build ids to WebAssembly modules and split out debug data +│ │ │ ├── wasm-split.ts# Add build ids to WebAssembly modules and split out debug data +│ │ │ └── wizard.ts # Set up the Sentry SDK in your project interactively │ │ ├── lib/ # Shared utilities │ │ └── types/ # TypeScript types and Valibot schemas │ ├── test/ # Test files (mirrors src/ structure) diff --git a/apps/cli-docs/src/fragments/commands/wizard.md b/apps/cli-docs/src/fragments/commands/wizard.md new file mode 100644 index 0000000000..1e49305bdb --- /dev/null +++ b/apps/cli-docs/src/fragments/commands/wizard.md @@ -0,0 +1,24 @@ + + +## Setting up Sentry interactively + +`sentry wizard` sets up the Sentry SDK in the project in the current +directory. It asks a few questions, installs the SDK for your framework, +writes its configuration, and sets up source map or debug file uploads. +Pass `-i` with an integration, such as `nextjs`, to skip the integration +picker. + +It logs in with your `sentry auth login` account, or starts a login when you +have none, and lets you pick or create the Sentry project to send data to. +Pass `--org` and `--project` to skip those questions. + +`sentry wizard` changes your project's files. To have a coding agent set up +Sentry instead, run `sentry init`, which prints the agent's setup guide and +changes nothing. + +## Coming from `@sentry/wizard` + +`sentry wizard` takes the same integrations and flags as +`npx @sentry/wizard`, so `npx @sentry/wizard -i nextjs` and +`sentry wizard -i nextjs` do the same thing. The Cordova and Electron wizards +were removed; follow their setup guides in the Sentry docs instead. diff --git a/packages/cli/package.json b/packages/cli/package.json index fc2d5ef556..ebda846304 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -131,6 +131,7 @@ "http-cache-semantics": "^4.2.0", "ignore": "^7.0.5", "jpeg-js": "^0.4.4", + "magicast": "0.2.11", "marked": "catalog:", "node-sqlite3-wasm": "0.8.59", "p-limit": "^7.3.0", diff --git a/packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md b/packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md index 70ab0025b3..963ccb51a1 100644 --- a/packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md +++ b/packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md @@ -814,6 +814,14 @@ Print instructions for a coding agent to set up Sentry → Full flags and examples: `references/init.md` +### Wizard + +Set up the Sentry SDK in your project interactively + +- `sentry wizard` — Set up the Sentry SDK in your project interactively + +→ Full flags and examples: `references/wizard.md` + ### Info Print configuration and verify authentication diff --git a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md new file mode 100644 index 0000000000..37be843225 --- /dev/null +++ b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md @@ -0,0 +1,44 @@ +--- +name: sentry-cli-wizard +version: 0.52.0-dev.0 +description: Set up the Sentry SDK in your project interactively +requires: + bins: ["sentry"] + auth: true +--- + +# Wizard Commands + +Set up the Sentry SDK in your project interactively + +### `sentry wizard` + +Set up the Sentry SDK in your project interactively + +**Flags:** +- `-i, --integration - Integration to set up (skips the picker)` +- `-u, --url - URL of your self-hosted Sentry instance` +- `--org - Slug of the Sentry organization to use` +- `--project - Slug of the Sentry project to use` +- `--saas - Use Sentry SaaS (sentry.io) without asking` +- `--spotlight - Set up Spotlight for local development, without a Sentry account` +- `--force-install - Install the SDK even when the package manager's checks fail` +- `--ignore-git-changes - Don't ask before changing a project with uncommitted changes` +- `--disable-telemetry - Don't send telemetry about this run to Sentry` +- `--debug - Print the wizard's debug output` +- `--promo-code - Promo code to apply when signing up` + +**Examples:** + +```bash +# Pick an integration and set it up +sentry wizard + +# Set up Next.js for a known org and project on sentry.io +sentry wizard -i nextjs --saas --org my-org --project my-project + +# Set up Next.js for Spotlight, without a Sentry account +sentry wizard -i nextjs --spotlight +``` + +All commands also support `--json`, `--fields`, `--help`, `--log-level`, and `--verbose` flags. diff --git a/packages/cli/src/app.ts b/packages/cli/src/app.ts index bfc9ef4f25..870afced8e 100644 --- a/packages/cli/src/app.ts +++ b/packages/cli/src/app.ts @@ -66,6 +66,7 @@ import { listCommand as traceListCommand } from "./commands/trace/list.js"; import { trialRoute } from "./commands/trial/index.js"; import { listCommand as trialListCommand } from "./commands/trial/list.js"; import { wasmSplitCommand } from "./commands/wasm-split.js"; +import { wizardCommand } from "./commands/wizard.js"; import { buildSentryApp, buildSentryRoutes } from "./app-root.js"; import { registerGraphicsBanner } from "./graphics-banner.js"; @@ -116,6 +117,7 @@ export const routes = buildSentryRoutes({ trace: traceRoute, trial: trialRoute, init: initCommand, + wizard: wizardCommand, info: infoCommand, local: localRoute, api: apiCommand, diff --git a/packages/cli/src/command-manifest.ts b/packages/cli/src/command-manifest.ts index 93ecb09e4f..9758b18f7d 100644 --- a/packages/cli/src/command-manifest.ts +++ b/packages/cli/src/command-manifest.ts @@ -139,6 +139,7 @@ export const COMMAND_MANIFEST: Readonly> = { trace: route(() => import("./commands/trace/index.js"), "traceRoute"), trial: route(() => import("./commands/trial/index.js"), "trialRoute"), init: route(() => import("./commands/init.js"), "initCommand"), + wizard: route(() => import("./commands/wizard.js"), "wizardCommand"), info: route(() => import("./commands/info.js"), "infoCommand"), local: route(() => import("./commands/local/index.js"), "localRoute"), api: route(() => import("./commands/api.js"), "apiCommand"), diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts index 334915591f..e6dcd6c6e3 100644 --- a/packages/cli/src/commands/init.ts +++ b/packages/cli/src/commands/init.ts @@ -50,7 +50,9 @@ export const initCommand = buildCommand({ "project already uses Sentry, the guide covers upgrading the SDKs and " + "turning on more features instead.\n\n" + "The command changes nothing and needs no login. The same guide is " + - "published at https://cli.sentry.dev/get-started-with-sentry.md.", + "published at https://cli.sentry.dev/get-started-with-sentry.md.\n\n" + + "To set up Sentry yourself with an interactive wizard that changes " + + "your project's files, run `sentry wizard` instead.", examples: [ { description: "Print the setup guide", diff --git a/packages/cli/src/commands/wizard.ts b/packages/cli/src/commands/wizard.ts new file mode 100644 index 0000000000..b48e6a6d2e --- /dev/null +++ b/packages/cli/src/commands/wizard.ts @@ -0,0 +1,221 @@ +/** + * sentry wizard + * + * Run the interactive setup wizard of a framework or platform: it installs + * the Sentry SDK, writes its config files, and sets up source map or debug + * file uploads in the current project. Ported from `@sentry/wizard`, whose + * `-i ` invocations keep working. + * + * The wizard logs in with the CLI's own login instead of the old browser + * hand-off, so `auth: false` here: a run in Spotlight mode, or with a + * preselected project, needs no login at all. + */ + +import type { SentryContext } from "../context.js"; +import { buildCommand } from "../lib/command.js"; +import { + parseOrgSlug, + parseProjectSlug, + parseText, + parseUrl, +} from "../lib/completion-target.js"; +import { getEnv } from "../lib/env.js"; +import { WizardExitError } from "../lib/errors.js"; +import { + disableTelemetryForRun, + isTelemetryEnabled, +} from "../lib/telemetry.js"; +import { INTEGRATION_IDS, runWizard } from "../lib/wizard/run.js"; +import { topLevelBrief } from "../top-level-briefs.js"; + +type WizardFlags = { + readonly integration?: string; + readonly url?: string; + readonly org?: string; + readonly project?: string; + readonly saas: boolean; + readonly debug: boolean; + readonly spotlight: boolean; + readonly "disable-telemetry": boolean; + readonly "force-install": boolean; + readonly "ignore-git-changes": boolean; + readonly "promo-code"?: string; + readonly "coming-from"?: string; + readonly signup: boolean; + readonly "skip-connect": boolean; + readonly quiet: boolean; + readonly uninstall: boolean; +}; + +/** The trimmed value of the environment variable `name`, unless empty. */ +function envValue(name: string): string | undefined { + return getEnv()[name]?.trim() || undefined; +} + +export const wizardCommand = buildCommand({ + auth: false, + docs: { + brief: topLevelBrief("wizard"), + fullDescription: + "Set up Sentry in the project in the current directory. The wizard " + + "asks you a few questions, installs the Sentry SDK for your framework, " + + "writes its configuration, and sets up source map or debug file " + + "uploads. It logs in with your `sentry auth login` account (or starts " + + "a login), and lets you pick or create the Sentry project to send " + + "data to.\n\n" + + "Pass `-i` to skip the integration picker. These are the same " + + "integrations and flags `npx @sentry/wizard` takes.\n\n" + + "The wizard changes files in your project. To have a coding agent set " + + "up Sentry instead, run `sentry init`, which prints the agent's setup " + + "guide and changes nothing.", + examples: [ + { + description: "Pick an integration and set it up", + run: "wizard", + }, + { + description: "Set up Next.js for a known org and project on sentry.io", + run: "wizard -i nextjs --saas --org my-org --project my-project", + }, + { + description: "Set up Next.js for Spotlight, without a Sentry account", + run: "wizard -i nextjs --spotlight", + }, + ], + }, + parameters: { + flags: { + integration: { + kind: "enum", + values: INTEGRATION_IDS, + brief: "Integration to set up (skips the picker)", + optional: true, + }, + url: { + kind: "parsed", + parse: parseUrl, + brief: "URL of your self-hosted Sentry instance", + placeholder: "url", + optional: true, + }, + org: { + kind: "parsed", + parse: parseOrgSlug, + brief: "Slug of the Sentry organization to use", + placeholder: "org", + optional: true, + }, + project: { + kind: "parsed", + parse: parseProjectSlug, + brief: "Slug of the Sentry project to use", + placeholder: "project", + optional: true, + }, + saas: { + kind: "boolean", + brief: "Use Sentry SaaS (sentry.io) without asking", + default: false, + }, + spotlight: { + kind: "boolean", + brief: + "Set up Spotlight for local development, without a Sentry account", + default: false, + }, + "force-install": { + kind: "boolean", + brief: "Install the SDK even when the package manager's checks fail", + default: false, + }, + "ignore-git-changes": { + kind: "boolean", + brief: "Don't ask before changing a project with uncommitted changes", + default: false, + }, + "disable-telemetry": { + kind: "boolean", + brief: "Don't send telemetry about this run to Sentry", + default: false, + }, + debug: { + kind: "boolean", + brief: "Print the wizard's debug output", + default: false, + }, + "promo-code": { + kind: "parsed", + parse: parseText, + brief: "Promo code to apply when signing up", + placeholder: "code", + optional: true, + }, + "coming-from": { + kind: "parsed", + parse: parseText, + brief: "Partner the command was copied from, such as vercel", + placeholder: "partner", + optional: true, + hidden: true as const, + }, + // Flags `@sentry/wizard` accepted that no flow reads any more. Kept so + // copied commands still run. + signup: { + kind: "boolean", + brief: "Ignored: the login page offers sign-up", + default: false, + hidden: true as const, + }, + "skip-connect": { + kind: "boolean", + brief: "Ignored", + default: false, + hidden: true as const, + }, + quiet: { + kind: "boolean", + brief: "Ignored", + default: false, + hidden: true as const, + }, + uninstall: { + kind: "boolean", + brief: "Ignored: only the retired Cordova wizard could uninstall", + default: false, + hidden: true as const, + }, + }, + aliases: { i: "integration", u: "url", s: "signup" }, + }, + // oxlint-disable-next-line require-yield -- The wizard prints its own interactive output; the command yields none. + async *func(this: SentryContext, flags: WizardFlags) { + if (flags["disable-telemetry"]) { + disableTelemetryForRun(); + } + + try { + await runWizard({ + integration: flags.integration ?? envValue("SENTRY_WIZARD_INTEGRATION"), + debug: flags.debug || envValue("SENTRY_WIZARD_DEBUG") === "true", + wizardOptions: { + telemetryEnabled: !flags["disable-telemetry"] && isTelemetryEnabled(), + promoCode: flags["promo-code"], + url: flags.url ?? envValue("SENTRY_WIZARD_URL"), + orgSlug: flags.org, + projectSlug: flags.project, + saas: flags.saas, + forceInstall: flags["force-install"], + comingFrom: flags["coming-from"], + ignoreGitChanges: flags["ignore-git-changes"], + spotlight: flags.spotlight, + }, + }); + } catch (error) { + if (!(error instanceof WizardExitError)) { + throw error; + } + // The wizard already explained why it stopped. + process.exitCode = error.exitCode; + } + }, +}); diff --git a/packages/cli/src/lib/env-registry.ts b/packages/cli/src/lib/env-registry.ts index 581c0c0a9c..b9b5edb556 100644 --- a/packages/cli/src/lib/env-registry.ts +++ b/packages/cli/src/lib/env-registry.ts @@ -139,6 +139,24 @@ export const ENV_VAR_REGISTRY: readonly EnvVarEntry[] = [ selfHosted: true, devGuide: "Sentry OAuth app client ID", }, + { + name: "SENTRY_WIZARD_INTEGRATION", + description: + "Integration for `sentry wizard` to set up when `-i` is not passed, such as `nextjs`. Kept from `@sentry/wizard`.", + example: "nextjs", + }, + { + name: "SENTRY_WIZARD_URL", + description: + "URL of the self-hosted Sentry instance for `sentry wizard` when `--url` is not passed. Kept from `@sentry/wizard`.", + example: "https://sentry.example.com", + }, + { + name: "SENTRY_WIZARD_DEBUG", + description: + "Set to `true` to print the debug output of `sentry wizard`, like `--debug`. Kept from `@sentry/wizard`.", + example: "true", + }, { name: "SENTRY_HANDOFF", description: diff --git a/packages/cli/src/lib/errors.ts b/packages/cli/src/lib/errors.ts index 37bdcbd010..54bc169566 100644 --- a/packages/cli/src/lib/errors.ts +++ b/packages/cli/src/lib/errors.ts @@ -791,6 +791,21 @@ export class VerifyFailedError extends CliError { } } +/** + * A setup wizard stopped: the user declined or cancelled a prompt (exit + * code 0), or the wizard can't continue (1). The wizard has already told the + * user why in its own output, so `sentry wizard` exits with `exitCode` + * without printing this error. + * + * @param exitCode - 0 when the user chose to stop, else the failure's code + */ +export class WizardExitError extends CliError { + constructor(exitCode: number) { + super("The setup wizard stopped.", exitCode); + this.name = "WizardExitError"; + } +} + /** * OAuth device flow errors (RFC 8628). * diff --git a/packages/cli/src/lib/telemetry.ts b/packages/cli/src/lib/telemetry.ts index 2467c3f349..b4e32c1640 100644 --- a/packages/cli/src/lib/telemetry.ts +++ b/packages/cli/src/lib/telemetry.ts @@ -176,6 +176,19 @@ export function isTelemetryEnabled(): boolean { return computeTelemetryEffective().enabled; } +/** + * Stop sending telemetry for the rest of this run, after `withTelemetry` + * already started it: the client drops every envelope from now on, including + * the command's own transaction. For flags such as `sentry wizard + * --disable-telemetry` that opt out of one run. + */ +export function disableTelemetryForRun(): void { + const client = Sentry.getClient(); + if (client) { + client.getOptions().enabled = false; + } +} + /** * Attributes a Snake score metric may carry. Everything else the SDK adds * (user.*, replay ids, ...) is dropped so a score cannot be linked to a user. diff --git a/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts b/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts new file mode 100644 index 0000000000..ef8e11b357 --- /dev/null +++ b/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts @@ -0,0 +1,1325 @@ +/** + * The Next.js setup wizard: installs `@sentry/nextjs`, wraps the Next.js + * config with `withSentryConfig`, and writes the SDK init files, an example + * page, and the auth token for source map uploads. + */ + +import { clack } from "../utils/clack/prompts.js"; +import chalk from "chalk"; +import { + existsSync, + lstatSync, + mkdirSync, + promises, + readFileSync, + unlinkSync, +} from "node:fs"; +import { parseModule } from "magicast"; +import path from "node:path"; + +import { Sentry } from "../telemetry.js"; + +import { setupCI } from "../sourcemaps/ci.js"; +import { traceStep, withTelemetry } from "../telemetry.js"; +import { + abort, + abortIfCancelled, + addDotEnvSentryBuildPluginFile, + askShouldCreateExamplePage, + confirmContinueIfNoOrDirtyGitRepo, + createNewConfigFile, + ensurePackageIsInstalled, + featureSelectionPrompt, + getOrAskForProjectData, + getPackageDotJson, + getPackageManager, + installPackage, + printSdkV11MigrationGuideIfOutdated, + isUsingTypeScript, + printWelcome, + runFormatters, + showCopyPasteInstructions, +} from "../utils/clack/index.js"; +import { + getPackageVersion, + hasPackageInstalled, +} from "../utils/package-json.js"; +import type { SentryProjectData, WizardOptions } from "../utils/types.js"; +import { offerProjectScopedMcpConfig } from "../utils/clack/mcp-config.js"; +import { + getFullUnderscoreErrorCopyPasteSnippet, + getGlobalErrorCopyPasteSnippet, + getInstrumentationHookContent, + getInstrumentationHookCopyPasteSnippet, + getNextjsConfigCjsAppendix, + getNextjsConfigCjsTemplate, + getNextjsConfigEsmCopyPasteSnippet, + getNextjsConfigMjsTemplate, + getRootLayout, + getSentryServersideConfigContents, + getInstrumentationClientFileContents, + getSentryDefaultGlobalErrorPage, + getSentryDefaultUnderscoreErrorPage, + getSentryExampleAppDirApiRoute, + getSentryExamplePageContents, + getSentryExamplePagesDirApiRoute, + getSimpleUnderscoreErrorCopyPasteSnippet, + getWithSentryConfigOptionsTemplate, + getInstrumentationClientHookCopyPasteSnippet, + getRootLayoutWithGenerateMetadata, + getGenerateMetadataSnippet, +} from "./templates.js"; +import { + getMaybeAppDirLocation, + getNextJsVersionBucket, + hasRootLayoutFile, + unwrapSentryConfigAst, + wrapWithSentryConfig, + addWithSentryConfigImport, + isNextJsVersionSupported, + MIN_SUPPORTED_NEXTJS_MAJOR, + MIN_SDK_VERSION_WITH_CONFIG_SUBPATH, + getExampleApiRouteDynamicStrategy, + getWithSentryConfigImportPath, +} from "./utils.js"; +import { SENTRY_NEXTJS_ROOT_IMPORT_PATH } from "./templates.js"; +import { warnIfNodeVersionUnsupportedBySdkV11 } from "../utils/node-version.js"; +import { + askShouldReduceDataCollection, + sdkSupportsDataCollection, +} from "../utils/data-collection.js"; +import { debug } from "../utils/debug.js"; + +export function runNextjsWizard(options: WizardOptions) { + return withTelemetry( + { + enabled: options.telemetryEnabled, + integration: "nextjs", + wizardOptions: options, + }, + () => runNextjsWizardWithTelemetry(options), + ); +} + +export async function runNextjsWizardWithTelemetry( + options: WizardOptions, +): Promise { + const { promoCode, telemetryEnabled, forceInstall } = options; + + printWelcome({ + wizardName: "Sentry Next.js Wizard", + promoCode, + telemetryEnabled, + }); + + const typeScriptDetected = isUsingTypeScript(); + + warnIfNodeVersionUnsupportedBySdkV11(); + + await confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: options.ignoreGitChanges, + cwd: undefined, + }); + + const packageJson = await getPackageDotJson(); + + await ensurePackageIsInstalled(packageJson, "next", "Next.js"); + + const nextVersion = getPackageVersion("next", packageJson); + Sentry.setTag("nextjs-version", getNextJsVersionBucket(nextVersion)); + + if (!isNextJsVersionSupported(nextVersion)) { + clack.log.warn( + `${chalk.yellow( + `Version 11 of the Sentry Next.js SDK requires Next.js ${MIN_SUPPORTED_NEXTJS_MAJOR} or newer, but this project uses ${chalk.bold( + `next@${nextVersion ?? "unknown"}`, + )}.`, + )} +The wizard will continue, but you may need to upgrade Next.js for the SDK to work.`, + ); + } + + const projectData = await getOrAskForProjectData( + options, + "javascript-nextjs", + ); + + const sdkAlreadyInstalled = hasPackageInstalled( + "@sentry/nextjs", + packageJson, + ); + Sentry.setTag("sdk-already-installed", sdkAlreadyInstalled); + + printSdkV11MigrationGuideIfOutdated("@sentry/nextjs", packageJson); + + const { packageManager: packageManagerFromInstallStep } = + await installPackage({ + packageName: "@sentry/nextjs@^11", + packageNameDisplayLabel: "@sentry/nextjs", + alreadyInstalled: !!packageJson.dependencies?.["@sentry/nextjs"], + forceInstall, + }); + + // `installPackage` may have skipped the install if the user declined the + // update prompt, so re-read package.json to learn which SDK is actually there. + const installedSdkVersion = getPackageVersion( + "@sentry/nextjs", + await getPackageDotJson(), + ); + const withSentryConfigImportPath = + getWithSentryConfigImportPath(installedSdkVersion); + if (withSentryConfigImportPath === SENTRY_NEXTJS_ROOT_IMPORT_PATH) { + clack.log.warn( + `${chalk.yellow( + `Your project uses ${chalk.bold( + `@sentry/nextjs@${installedSdkVersion ?? "unknown"}`, + )}, which predates ${MIN_SDK_VERSION_WITH_CONFIG_SUBPATH}.`, + )} +The wizard will import ${chalk.cyan( + "withSentryConfig", + )} from the root package for now. Once you upgrade the SDK (required for v11), change the import in your Next.js config to ${chalk.cyan( + "@sentry/nextjs/config", + )}.`, + ); + } + + // 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, "^10.73.0") && + (await askShouldReduceDataCollection()); + + let selectedProject: SentryProjectData; + let authToken: string; + let selfHosted: boolean; + let sentryUrl: string; + let spotlight: boolean; + + if (projectData.spotlight) { + // Spotlight mode: use empty DSN and skip auth + spotlight = true; + selfHosted = false; + sentryUrl = ""; + authToken = ""; + // Create a minimal project structure for type compatibility + selectedProject = { + id: "", + slug: "", + organization: { id: "", slug: "", name: "" }, + keys: [{ dsn: { public: "" } }], + }; + } else { + spotlight = false; + ({ selectedProject, authToken, selfHosted, sentryUrl } = projectData); + } + + await traceStep("configure-sdk", async () => { + const tunnelRoute = await askShouldSetTunnelRoute(); + + return await createOrMergeNextJsFiles( + selectedProject, + selfHosted, + sentryUrl, + { + tunnelRoute, + withSentryConfigImportPath, + reduceDataCollection, + spotlight, + }, + ); + }); + + await traceStep("create-underscoreerror-page", async () => { + const srcDir = path.join(process.cwd(), "src"); + const maybePagesDirPath = path.join(process.cwd(), "pages"); + const maybeSrcPagesDirPath = path.join(srcDir, "pages"); + + const pagesLocation = + existsSync(maybePagesDirPath) && + lstatSync(maybePagesDirPath).isDirectory() + ? ["pages"] + : existsSync(maybeSrcPagesDirPath) && + lstatSync(maybeSrcPagesDirPath).isDirectory() + ? ["src", "pages"] + : undefined; + + if (!pagesLocation) { + return; + } + + const underscoreErrorPageFile = existsSync( + path.join(process.cwd(), ...pagesLocation, "_error.tsx"), + ) + ? "_error.tsx" + : existsSync(path.join(process.cwd(), ...pagesLocation, "_error.ts")) + ? "_error.ts" + : existsSync(path.join(process.cwd(), ...pagesLocation, "_error.jsx")) + ? "_error.jsx" + : existsSync(path.join(process.cwd(), ...pagesLocation, "_error.js")) + ? "_error.js" + : undefined; + + if (!underscoreErrorPageFile) { + const underscoreErrorFileName = `_error.${ + typeScriptDetected ? "tsx" : "jsx" + }`; + + await promises.writeFile( + path.join(process.cwd(), ...pagesLocation, underscoreErrorFileName), + getSentryDefaultUnderscoreErrorPage(), + { encoding: "utf8", flag: "w" }, + ); + + clack.log.success( + `Created ${chalk.cyan( + path.join(...pagesLocation, underscoreErrorFileName), + )}.`, + ); + } else if ( + readFileSync( + path.join(process.cwd(), ...pagesLocation, underscoreErrorPageFile), + "utf8", + ).includes("getInitialProps") + ) { + clack.log.info( + `It seems like you already have a custom error page.\n\nPlease put the following function call in the ${chalk.bold( + "getInitialProps", + )}\nmethod of your custom error page at ${chalk.bold( + path.join(...pagesLocation, underscoreErrorPageFile), + )}:`, + ); + clack.rawOutput(getSimpleUnderscoreErrorCopyPasteSnippet()); + + const shouldContinue = await abortIfCancelled( + clack.confirm({ + message: `Did you modify your ${chalk.cyan( + path.join(...pagesLocation, underscoreErrorPageFile), + )} file as described above?`, + active: "Yes", + inactive: "No, get me out of here", + }), + ); + + if (!shouldContinue) { + await abort(); + } + } else { + clack.log.info( + `It seems like you already have a custom error page.\n\nPlease add the following code to your custom error page\nat ${chalk.cyan( + path.join(...pagesLocation, underscoreErrorPageFile), + )}:`, + ); + clack.rawOutput( + getFullUnderscoreErrorCopyPasteSnippet( + underscoreErrorPageFile === "_error.ts" || + underscoreErrorPageFile === "_error.tsx", + ), + ); + + const shouldContinue = await abortIfCancelled( + clack.confirm({ + message: `Did you add the code to your ${chalk.cyan( + path.join(...pagesLocation, underscoreErrorPageFile), + )} file as described above?`, + active: "Yes", + inactive: "No, get me out of here", + }), + ); + + if (!shouldContinue) { + await abort(); + } + } + }); + + await traceStep("create-global-error-page", async () => { + const appDirLocation = getMaybeAppDirLocation(); + + if (!appDirLocation) { + return; + } + + const globalErrorPageFile = existsSync( + path.join(process.cwd(), ...appDirLocation, "global-error.tsx"), + ) + ? "global-error.tsx" + : existsSync( + path.join(process.cwd(), ...appDirLocation, "global-error.ts"), + ) + ? "global-error.ts" + : existsSync( + path.join(process.cwd(), ...appDirLocation, "global-error.jsx"), + ) + ? "global-error.jsx" + : existsSync( + path.join(process.cwd(), ...appDirLocation, "global-error.js"), + ) + ? "global-error.js" + : undefined; + + if (!globalErrorPageFile) { + const newGlobalErrorFileName = `global-error.${ + typeScriptDetected ? "tsx" : "jsx" + }`; + + await promises.writeFile( + path.join(process.cwd(), ...appDirLocation, newGlobalErrorFileName), + getSentryDefaultGlobalErrorPage(typeScriptDetected), + { encoding: "utf8", flag: "w" }, + ); + + clack.log.success( + `Created ${chalk.cyan( + path.join(...appDirLocation, newGlobalErrorFileName), + )}.`, + ); + } else { + clack.log.info( + `It seems like you already have a custom error page for your app directory.\n\nPlease add the following code to your custom error page\nat ${chalk.cyan( + path.join(...appDirLocation, globalErrorPageFile), + )}:\n`, + ); + clack.rawOutput( + getGlobalErrorCopyPasteSnippet( + globalErrorPageFile === "global-error.ts" || + globalErrorPageFile === "global-error.tsx", + ), + ); + + const shouldContinue = await abortIfCancelled( + clack.confirm({ + message: `Did you add the code to your ${chalk.cyan( + path.join(...appDirLocation, globalErrorPageFile), + )} file as described above?`, + active: "Yes", + inactive: "No, get me out of here", + }), + ); + + if (!shouldContinue) { + await abort(); + } + } + }); + + await traceStep("add-generate-metadata-function", async () => { + const isNext14 = getNextJsVersionBucket(nextVersion) === "14.x"; + const appDirLocation = getMaybeAppDirLocation(); + + // We only need this specific change for app router on next@14 + if (!appDirLocation || !isNext14) { + return; + } + + const appDirPath = path.join(process.cwd(), ...appDirLocation); + const hasRootLayout = hasRootLayoutFile(appDirPath); + + if (!hasRootLayout) { + const newRootLayoutFilename = `layout.${ + typeScriptDetected ? "tsx" : "jsx" + }`; + + await promises.writeFile( + path.join(appDirPath, newRootLayoutFilename), + getRootLayoutWithGenerateMetadata(typeScriptDetected), + { encoding: "utf8", flag: "w" }, + ); + + clack.log.success( + `Created ${chalk.cyan( + path.join(...appDirLocation, newRootLayoutFilename), + )}.`, + ); + } else { + clack.log.info( + `It seems like you already have a root layout component. Please add or modify your generateMetadata function.`, + ); + + await showCopyPasteInstructions({ + filename: `layout.${typeScriptDetected ? "tsx" : "jsx"}`, + codeSnippet: getGenerateMetadataSnippet(typeScriptDetected), + }); + } + }); + + const shouldCreateExamplePage = await askShouldCreateExamplePage(); + if (shouldCreateExamplePage) { + await traceStep( + "create-example-page", + async () => + await createExamplePage( + selfHosted, + selectedProject, + sentryUrl, + typeScriptDetected, + nextVersion, + ), + ); + } + + if (!spotlight) { + await addDotEnvSentryBuildPluginFile(authToken); + } + + const isLikelyUsingTurbopack = await checkIfLikelyIsUsingTurbopack(); + if (isLikelyUsingTurbopack || isLikelyUsingTurbopack === null) { + await abortIfCancelled( + clack.select({ + message: + "Warning: The Sentry SDK is only compatible with Turbopack on Next.js version 15.4.1 or later.", + options: [ + { + label: "I understand.", + hint: "press enter", + value: true, + }, + ], + initialValue: true, + }), + ); + } + + const mightBeUsingVercel = existsSync( + path.join(process.cwd(), "vercel.json"), + ); + + if (mightBeUsingVercel && !options.comingFrom) { + clack.log.info( + "▲ It seems like you're using Vercel. We recommend using the Sentry Vercel \ + integration to set up an auth token for Vercel deployments: https://vercel.com/integrations/sentry", + ); + } else if (!spotlight) { + await setupCI("nextjs", authToken, options.comingFrom); + } + + const packageManagerForOutro = + packageManagerFromInstallStep ?? (await getPackageManager()); + + // Offer optional project-scoped MCP config for Sentry with org and project scope + await offerProjectScopedMcpConfig( + selectedProject.organization.slug, + selectedProject.slug, + ); + + // Run formatters as the last step to fix any formatting issues in generated/modified files + await runFormatters({ cwd: undefined }); + + clack.outro(` +${chalk.green("Successfully installed the Sentry Next.js SDK!")} ${ + shouldCreateExamplePage + ? `\n\nYou can validate your setup by (re)starting your dev environment (e.g. ${chalk.cyan( + `${packageManagerForOutro.runScriptCommand} dev`, + )}) and visiting ${chalk.cyan('"/sentry-example-page"')}` + : "" + } + +${chalk.dim( + "If you encounter any issues, let us know here: https://github.com/getsentry/sentry-javascript/issues", +)}`); +} + +type SDKConfigOptions = { + tunnelRoute: boolean; + /** Module `withSentryConfig` is imported from; depends on the installed SDK version. */ + withSentryConfigImportPath: string; + /** Write the reduced-PII `dataCollection` option into `Sentry.init()`. */ + reduceDataCollection: boolean; + /** Set up Spotlight only, without a Sentry project. */ + spotlight: boolean; +}; + +async function createOrMergeNextJsFiles( + selectedProject: SentryProjectData, + selfHosted: boolean, + sentryUrl: string, + sdkConfigOptions: SDKConfigOptions, +): Promise { + const { reduceDataCollection, spotlight } = sdkConfigOptions; + const dsn = selectedProject.keys[0].dsn.public; + 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", "edge"] 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 = []; + + 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), + getSentryServersideConfigContents( + dsn, + configVariant, + selectedFeatures, + reduceDataCollection, + spotlight, + ), + { encoding: "utf8", flag: "w" }, + ); + clack.log.success( + `Created fresh ${chalk.cyan( + typeScriptDetected ? tsConfig : jsConfig, + )}.`, + ); + Sentry.setTag(`created-${configVariant}-config`, true); + } + }); + } + + await traceStep("setup-instrumentation-hook", async () => { + const hasRootAppDirectory = hasDirectoryPathFromRoot("app"); + const hasRootPagesDirectory = hasDirectoryPathFromRoot("pages"); + const hasSrcDirectory = hasDirectoryPathFromRoot("src"); + + let instrumentationHookLocation: "src" | "root" | "does-not-exist"; + + const instrumentationTsExists = existsSync( + path.join(process.cwd(), "instrumentation.ts"), + ); + const instrumentationJsExists = existsSync( + path.join(process.cwd(), "instrumentation.js"), + ); + const srcInstrumentationTsExists = existsSync( + path.join(process.cwd(), "src", "instrumentation.ts"), + ); + const srcInstrumentationJsExists = existsSync( + path.join(process.cwd(), "src", "instrumentation.js"), + ); + + // https://nextjs.org/docs/app/building-your-application/configuring/src-directory + // https://nextjs.org/docs/app/api-reference/file-conventions/instrumentation + // The logic for where Next.js picks up the instrumentation file is as follows: + // - If there is either an `app` folder or a `pages` folder in the root directory of your Next.js app, Next.js looks + // for an `instrumentation.ts` file in the root of the Next.js app. + // - Otherwise, if there is neither an `app` folder or a `pages` folder in the rood directory of your Next.js app, + // AND if there is an `src` folder, Next.js will look for the `instrumentation.ts` file in the `src` folder. + if (hasRootPagesDirectory || hasRootAppDirectory) { + if (instrumentationJsExists || instrumentationTsExists) { + instrumentationHookLocation = "root"; + } else { + instrumentationHookLocation = "does-not-exist"; + } + } else { + if (srcInstrumentationTsExists || srcInstrumentationJsExists) { + instrumentationHookLocation = "src"; + } else { + instrumentationHookLocation = "does-not-exist"; + } + } + + const newInstrumentationFileName = `instrumentation.${ + typeScriptDetected ? "ts" : "js" + }`; + + if (instrumentationHookLocation === "does-not-exist") { + let newInstrumentationHookLocation: "root" | "src"; + if (hasRootPagesDirectory || hasRootAppDirectory) { + newInstrumentationHookLocation = "root"; + } else if (hasSrcDirectory) { + newInstrumentationHookLocation = "src"; + } else { + newInstrumentationHookLocation = "root"; + } + + const newInstrumentationHookPath = + newInstrumentationHookLocation === "root" + ? path.join(process.cwd(), newInstrumentationFileName) + : path.join(process.cwd(), "src", newInstrumentationFileName); + + const successfullyCreated = await createNewConfigFile( + newInstrumentationHookPath, + getInstrumentationHookContent(newInstrumentationHookLocation), + ); + + if (!successfullyCreated) { + await showCopyPasteInstructions({ + filename: newInstrumentationFileName, + codeSnippet: getInstrumentationHookCopyPasteSnippet( + newInstrumentationHookLocation, + ), + hint: "create the file if it doesn't already exist", + }); + } + } else { + await showCopyPasteInstructions({ + filename: + srcInstrumentationTsExists || instrumentationTsExists + ? "instrumentation.ts" + : srcInstrumentationJsExists || instrumentationJsExists + ? "instrumentation.js" + : newInstrumentationFileName, + codeSnippet: getInstrumentationHookCopyPasteSnippet( + instrumentationHookLocation, + ), + }); + } + }); + + await traceStep("setup-instrumentation-client-hook", async () => { + const hasRootAppDirectory = hasDirectoryPathFromRoot("app"); + const hasRootPagesDirectory = hasDirectoryPathFromRoot("pages"); + const hasSrcDirectory = hasDirectoryPathFromRoot("src"); + + let instrumentationClientHookLocation: "src" | "root" | "does-not-exist"; + + const instrumentationClientTsExists = existsSync( + path.join(process.cwd(), "instrumentation-client.ts"), + ); + const instrumentationClientJsExists = existsSync( + path.join(process.cwd(), "instrumentation-client.js"), + ); + const srcInstrumentationClientTsExists = existsSync( + path.join(process.cwd(), "src", "instrumentation-client.ts"), + ); + const srcInstrumentationClientJsExists = existsSync( + path.join(process.cwd(), "src", "instrumentation-client.js"), + ); + + // https://nextjs.org/docs/app/building-your-application/configuring/src-directory + // https://nextjs.org/docs/app/api-reference/file-conventions/instrumentation + // The logic for where Next.js picks up the instrumentation file is as follows: + // - If there is either an `app` folder or a `pages` folder in the root directory of your Next.js app, Next.js looks + // for an `instrumentation.ts` file in the root of the Next.js app. + // - Otherwise, if there is neither an `app` folder or a `pages` folder in the rood directory of your Next.js app, + // AND if there is an `src` folder, Next.js will look for the `instrumentation.ts` file in the `src` folder. + if (hasRootPagesDirectory || hasRootAppDirectory) { + if (instrumentationClientJsExists || instrumentationClientTsExists) { + instrumentationClientHookLocation = "root"; + } else { + instrumentationClientHookLocation = "does-not-exist"; + } + } else { + if ( + srcInstrumentationClientTsExists || + srcInstrumentationClientJsExists + ) { + instrumentationClientHookLocation = "src"; + } else { + instrumentationClientHookLocation = "does-not-exist"; + } + } + + const newInstrumentationClientFileName = `instrumentation-client.${ + typeScriptDetected ? "ts" : "js" + }`; + + if (instrumentationClientHookLocation === "does-not-exist") { + let newInstrumentationClientHookLocation: "root" | "src"; + if (hasRootPagesDirectory || hasRootAppDirectory) { + newInstrumentationClientHookLocation = "root"; + } else if (hasSrcDirectory) { + newInstrumentationClientHookLocation = "src"; + } else { + newInstrumentationClientHookLocation = "root"; + } + + const newInstrumentationClientHookPath = + newInstrumentationClientHookLocation === "root" + ? path.join(process.cwd(), newInstrumentationClientFileName) + : path.join(process.cwd(), "src", newInstrumentationClientFileName); + + const successfullyCreated = await createNewConfigFile( + newInstrumentationClientHookPath, + getInstrumentationClientFileContents( + dsn, + selectedFeatures, + reduceDataCollection, + spotlight, + ), + ); + + if (!successfullyCreated) { + await showCopyPasteInstructions({ + filename: newInstrumentationClientFileName, + codeSnippet: getInstrumentationClientHookCopyPasteSnippet( + dsn, + selectedFeatures, + reduceDataCollection, + spotlight, + ), + hint: "create the file if it doesn't already exist", + }); + } + } else { + await showCopyPasteInstructions({ + filename: + srcInstrumentationClientTsExists || instrumentationClientTsExists + ? "instrumentation-client.ts" + : srcInstrumentationClientJsExists || instrumentationClientJsExists + ? "instrumentation-client.js" + : newInstrumentationClientFileName, + codeSnippet: getInstrumentationClientHookCopyPasteSnippet( + dsn, + selectedFeatures, + reduceDataCollection, + spotlight, + ), + }); + } + }); + + await traceStep("setup-next-config", async () => { + const withSentryConfigOptionsTemplate = getWithSentryConfigOptionsTemplate({ + orgSlug: selectedProject.organization.slug, + projectSlug: selectedProject.slug, + selfHosted, + sentryUrl, + tunnelRoute: sdkConfigOptions.tunnelRoute, + }); + + const nextConfigPossibleFilesMap = { + js: "next.config.js", + mjs: "next.config.mjs", + cjs: "next.config.cjs", + ts: "next.config.ts", + mts: "next.config.mts", + cts: "next.config.cts", + }; + + const foundNextConfigFile = Object.entries(nextConfigPossibleFilesMap).find( + ([, fileName]) => existsSync(path.join(process.cwd(), fileName)), + ); + + if (!foundNextConfigFile) { + Sentry.setTag("next-config-strategy", "create"); + + // Try to figure out whether the user prefers ESM + let isTypeModule = false; + try { + const packageJsonText = await promises.readFile( + path.join(process.cwd(), "package.json"), + "utf8", + ); + const packageJson = JSON.parse(packageJsonText); + if (packageJson.type === "module") { + isTypeModule = true; + } + } catch (error) { + debug(error); + // noop + } + + // We are creating `next.config.(m)js` files by default as they are supported by the most Next.js versions + const configFilename = isTypeModule + ? nextConfigPossibleFilesMap.mjs + : nextConfigPossibleFilesMap.js; + const configContent = isTypeModule + ? getNextjsConfigMjsTemplate( + withSentryConfigOptionsTemplate, + sdkConfigOptions.withSentryConfigImportPath, + ) + : getNextjsConfigCjsTemplate( + withSentryConfigOptionsTemplate, + sdkConfigOptions.withSentryConfigImportPath, + ); + + await promises.writeFile( + path.join(process.cwd(), configFilename), + configContent, + { encoding: "utf8", flag: "w" }, + ); + + clack.log.success( + `Created ${chalk.cyan(configFilename)} with Sentry configuration.`, + ); + + return; + } + + const [foundNextConfigFileType, foundNextConfigFileFilename] = + foundNextConfigFile; + + if (foundNextConfigFileType === "js" || foundNextConfigFileType === "cjs") { + Sentry.setTag("next-config-strategy", "modify"); + + const nextConfigCjsContent = readFileSync( + path.join(process.cwd(), foundNextConfigFileFilename), + "utf8", + ); + + const probablyIncludesSdk = + nextConfigCjsContent.includes("@sentry/nextjs") && + nextConfigCjsContent.includes("withSentryConfig"); + + let shouldInject = true; + + if (probablyIncludesSdk) { + const injectAnyhow = await abortIfCancelled( + clack.confirm({ + message: `${chalk.cyan( + foundNextConfigFileFilename, + )} already contains Sentry SDK configuration. Should the wizard modify it anyways?`, + }), + ); + + shouldInject = injectAnyhow; + } + + if (shouldInject) { + await promises.appendFile( + path.join(process.cwd(), foundNextConfigFileFilename), + getNextjsConfigCjsAppendix( + withSentryConfigOptionsTemplate, + sdkConfigOptions.withSentryConfigImportPath, + ), + "utf8", + ); + + clack.log.success( + `Added Sentry configuration to ${chalk.cyan( + foundNextConfigFileFilename, + )}. ${chalk.dim("(you probably want to clean this up a bit!)")}`, + ); + } + + Sentry.setTag("next-config-mod-result", "success"); + } + + if ( + foundNextConfigFileType === "mjs" || + foundNextConfigFileType === "mts" || + foundNextConfigFileType === "cts" || + foundNextConfigFileType === "ts" + ) { + const nextConfigMjsContent = readFileSync( + path.join(process.cwd(), foundNextConfigFileFilename), + "utf8", + ); + + const probablyIncludesSdk = + nextConfigMjsContent.includes("@sentry/nextjs") && + nextConfigMjsContent.includes("withSentryConfig"); + + let shouldInject = true; + + if (probablyIncludesSdk) { + const injectAnyhow = await abortIfCancelled( + clack.confirm({ + message: `${chalk.cyan( + foundNextConfigFileFilename, + )} already contains Sentry SDK configuration. Should the wizard modify it anyways?`, + }), + ); + + shouldInject = injectAnyhow; + } + + try { + if (shouldInject) { + const mod = parseModule(nextConfigMjsContent); + addWithSentryConfigImport( + mod, + sdkConfigOptions.withSentryConfigImportPath, + ); + + if (probablyIncludesSdk) { + // Prevent double wrapping like: withSentryConfig(withSentryConfig(nextConfig), { ... }) + // Use AST manipulation instead of string parsing for better reliability + mod.exports["default"].$ast = unwrapSentryConfigAst( + mod.exports["default"].$ast, + ); + } + + // Use the shared utility function for wrapping + mod.exports["default"] = wrapWithSentryConfig( + mod.exports["default"], + withSentryConfigOptionsTemplate, + ); + + let newCode = mod.generate().code; + + // Post-process to fix formatting issues that magicast doesn't handle + // (needed for Biome/ESLint compatibility): + // 1. Add spaces inside import braces for various import patterns + // Single named import: {Foo} -> { Foo } + newCode = newCode.replace( + /import\s*{(\w+)}\s*from/g, + "import { $1 } from", + ); + // Multiple named imports: {Foo,Bar} or {Foo, Bar} -> { Foo, Bar } + newCode = newCode.replace( + /import\s*{([^}]+)}\s*from/g, + (_match: string, imports: string) => { + const formatted = imports + .split(",") + .map((i: string) => i.trim()) + .join(", "); + return `import { ${formatted} } from`; + }, + ); + // Default + named imports: Foo,{Bar} -> Foo, { Bar } + newCode = newCode.replace( + /import\s+(\w+)\s*,\s*{([^}]+)}\s*from/g, + (_match: string, defaultImport: string, namedImports: string) => { + const formatted = namedImports + .split(",") + .map((i: string) => i.trim()) + .join(", "); + return `import ${defaultImport}, { ${formatted} } from`; + }, + ); + // 2. Fix trailing comma and closing format for withSentryConfig call + // Biome wants: automaticVercelMonitors: true,\n }); + newCode = newCode.replace( + /automaticVercelMonitors:\s*true,?\s*},?\s*\);/g, + "automaticVercelMonitors: true,\n });\n", + ); + // 3. Ensure trailing newline + if (!newCode.endsWith("\n")) { + newCode += "\n"; + } + + await promises.writeFile( + path.join(process.cwd(), foundNextConfigFileFilename), + newCode, + { + encoding: "utf8", + flag: "w", + }, + ); + clack.log.success( + `${ + probablyIncludesSdk ? "Updated" : "Added" + } Sentry configuration ${ + probablyIncludesSdk ? "in" : "to" + } ${chalk.cyan(foundNextConfigFileFilename)}. ${chalk.dim( + "(you probably want to clean this up a bit!)", + )}`, + ); + + Sentry.setTag("next-config-mod-result", "success"); + } + } catch { + Sentry.setTag("next-config-mod-result", "fail"); + clack.log.warn( + chalk.yellow( + `Something went wrong writing to ${chalk.cyan( + foundNextConfigFileFilename, + )}.`, + ), + ); + clack.log.info( + `Please put the following code snippet into ${chalk.cyan( + foundNextConfigFileFilename, + )}: ${chalk.dim("You probably have to clean it up a bit.")}\n`, + ); + clack.rawOutput( + getNextjsConfigEsmCopyPasteSnippet( + withSentryConfigOptionsTemplate, + sdkConfigOptions.withSentryConfigImportPath, + ), + ); + + const shouldContinue = await abortIfCancelled( + clack.confirm({ + message: `Are you done putting the snippet above into ${chalk.cyan( + foundNextConfigFileFilename, + )}?`, + active: "Yes", + inactive: "No, get me out of here", + }), + ); + + if (!shouldContinue) { + await abort(); + } + } + } + }); +} + +function hasDirectoryPathFromRoot(dirnameOrDirs: string | string[]): boolean { + const dirPath = Array.isArray(dirnameOrDirs) + ? path.join(process.cwd(), ...dirnameOrDirs) + : path.join(process.cwd(), dirnameOrDirs); + + return existsSync(dirPath) && lstatSync(dirPath).isDirectory(); +} + +async function createExamplePage( + selfHosted: boolean, + selectedProject: SentryProjectData, + sentryUrl: string, + typeScriptDetected: boolean, + nextVersion: string | undefined, +): Promise { + const hasSrcDirectory = hasDirectoryPathFromRoot("src"); + const hasRootAppDirectory = hasDirectoryPathFromRoot("app"); + const hasRootPagesDirectory = hasDirectoryPathFromRoot("pages"); + const hasSrcAppDirectory = hasDirectoryPathFromRoot(["src", "app"]); + const hasSrcPagesDirectory = hasDirectoryPathFromRoot(["src", "pages"]); + + Sentry.setTag("nextjs-app-dir", hasRootAppDirectory || hasSrcAppDirectory); + + // If `pages` or an `app` directory exists in the root, we'll put the example page there. + // `app` directory takes priority over `pages` directory when they coexist, so we prioritize that. + // https://nextjs.org/docs/app/building-your-application/routing#the-app-router + + const appFolderLocation = hasRootAppDirectory + ? ["app"] + : hasSrcAppDirectory + ? ["src", "app"] + : undefined; + + let pagesFolderLocation = hasRootPagesDirectory + ? ["pages"] + : hasSrcPagesDirectory + ? ["src", "pages"] + : undefined; + + // If the user has neither pages nor app directory we create a pages folder for them + if (!appFolderLocation && !pagesFolderLocation) { + const newPagesFolderLocation = hasSrcDirectory + ? ["src", "pages"] + : ["pages"]; + mkdirSync(path.join(process.cwd(), ...newPagesFolderLocation), { + recursive: true, + }); + + pagesFolderLocation = newPagesFolderLocation; + } + + if (appFolderLocation) { + const appFolderPath = path.join(process.cwd(), ...appFolderLocation); + + const hasRootLayout = hasRootLayoutFile(appFolderPath); + + if (!hasRootLayout) { + // In case no root layout file exists, we create a simple one so that + // the example page can be rendered correctly. + const newRootLayoutFilename = `layout.${ + typeScriptDetected ? "tsx" : "jsx" + }`; + + await promises.writeFile( + path.join(appFolderPath, newRootLayoutFilename), + getRootLayout(typeScriptDetected), + { encoding: "utf8", flag: "w" }, + ); + + clack.log.success( + `Created ${chalk.cyan( + path.join(...appFolderLocation, newRootLayoutFilename), + )}.`, + ); + } + + const examplePageContents = getSentryExamplePageContents({ + selfHosted, + orgSlug: selectedProject.organization.slug, + projectId: selectedProject.id, + sentryUrl, + useClient: true, + isTypeScript: typeScriptDetected, + }); + + mkdirSync(path.join(appFolderPath, "sentry-example-page"), { + recursive: true, + }); + + const newPageFileName = `page.${typeScriptDetected ? "tsx" : "jsx"}`; + + await promises.writeFile( + path.join(appFolderPath, "sentry-example-page", newPageFileName), + examplePageContents, + { encoding: "utf8", flag: "w" }, + ); + + clack.log.success( + `Created ${chalk.cyan( + path.join(...appFolderLocation, "sentry-example-page", newPageFileName), + )}.`, + ); + + mkdirSync(path.join(appFolderPath, "api", "sentry-example-api"), { + recursive: true, + }); + + const newRouteFileName = `route.${typeScriptDetected ? "ts" : "js"}`; + + await promises.writeFile( + path.join(appFolderPath, "api", "sentry-example-api", newRouteFileName), + getSentryExampleAppDirApiRoute({ + isTypeScript: typeScriptDetected, + dynamicStrategy: getExampleApiRouteDynamicStrategy(nextVersion), + }), + { encoding: "utf8", flag: "w" }, + ); + + clack.log.success( + `Created ${chalk.cyan( + path.join( + ...appFolderLocation, + "api", + "sentry-example-api", + newRouteFileName, + ), + )}.`, + ); + } else if (pagesFolderLocation) { + const examplePageContents = getSentryExamplePageContents({ + selfHosted, + orgSlug: selectedProject.organization.slug, + projectId: selectedProject.id, + sentryUrl, + useClient: false, + isTypeScript: typeScriptDetected, + }); + + const examplePageFileName = `sentry-example-page.${ + typeScriptDetected ? "tsx" : "jsx" + }`; + + await promises.writeFile( + path.join(process.cwd(), ...pagesFolderLocation, examplePageFileName), + examplePageContents, + { encoding: "utf8", flag: "w" }, + ); + + clack.log.success( + `Created ${chalk.cyan( + path.join(...pagesFolderLocation, examplePageFileName), + )}.`, + ); + + mkdirSync(path.join(process.cwd(), ...pagesFolderLocation, "api"), { + recursive: true, + }); + + const apiRouteFileName = `sentry-example-api.${ + typeScriptDetected ? "ts" : "js" + }`; + + await promises.writeFile( + path.join(process.cwd(), ...pagesFolderLocation, "api", apiRouteFileName), + getSentryExamplePagesDirApiRoute({ + isTypeScript: typeScriptDetected, + }), + { encoding: "utf8", flag: "w" }, + ); + + clack.log.success( + `Created ${chalk.cyan( + path.join(...pagesFolderLocation, "api", apiRouteFileName), + )}.`, + ); + } +} + +/** + * Ask users if they want to set the tunnelRoute option. + * We can't set this by default because it potentially increases hosting bills. + * It's valuable enough to for users to justify asking the additional question. + */ +async function askShouldSetTunnelRoute() { + return await traceStep("ask-tunnelRoute-option", async (span) => { + const shouldSetTunnelRoute = await abortIfCancelled( + clack.select({ + message: + "Do you want to route Sentry requests in the browser through your Next.js server to avoid ad blockers?", + options: [ + { + label: "Yes", + value: true, + hint: "Can increase your server load and hosting bill", + }, + { + label: "No", + value: false, + hint: "Browser errors and events might be blocked by ad blockers before being sent to Sentry", + }, + ], + initialValue: true, + }), + ); + + if (!shouldSetTunnelRoute) { + clack.log.info( + "Sounds good! We'll leave the option commented for later, just in case :)", + ); + } + + span?.setAttribute("tunnelRoute", shouldSetTunnelRoute); + Sentry.setTag("tunnelRoute", shouldSetTunnelRoute); + + return shouldSetTunnelRoute; + }); +} + +/** + * Returns true or false depending on whether we think the user is using Turbopack. May return null in case we aren't sure. + */ +async function checkIfLikelyIsUsingTurbopack(): Promise { + let packageJsonContent: string; + try { + packageJsonContent = await promises.readFile( + path.join(process.cwd(), "package.json"), + "utf8", + ); + } catch (error) { + debug(error); + return null; + } + + return packageJsonContent.includes("--turbo"); +} diff --git a/packages/cli/src/lib/wizard/nextjs/templates.ts b/packages/cli/src/lib/wizard/nextjs/templates.ts new file mode 100644 index 0000000000..b9ce82f9d8 --- /dev/null +++ b/packages/cli/src/lib/wizard/nextjs/templates.ts @@ -0,0 +1,910 @@ +/** + * File and snippet templates the Next.js wizard writes or shows. + */ + +import chalk from "chalk"; +import { makeCodeSnippet } from "../utils/clack/index.js"; +import { getDataCollectionSnippet } from "../utils/data-collection.js"; + +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/nextjs/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + },`; + +/** + * The active PII-reducing preset when the user opted in, the commented-out + * hint otherwise. + */ +function getDataCollectionBlock(reduceDataCollection: boolean): string { + return reduceDataCollection + ? getDataCollectionSnippet(" ") + : DATA_COLLECTION_HINT; +} + +/** Root export of the Next.js SDK. Exposes `withSentryConfig` up to SDK v10 only. */ +export const SENTRY_NEXTJS_ROOT_IMPORT_PATH = "@sentry/nextjs"; + +/** Subpath that exposes `withSentryConfig` since SDK 10.73.0 and is the only location in v11. */ +export const SENTRY_NEXTJS_CONFIG_IMPORT_PATH = "@sentry/nextjs/config"; + +type WithSentryConfigOptions = { + orgSlug: string; + projectSlug: string; + selfHosted: boolean; + sentryUrl: string; + tunnelRoute: boolean; +}; + +export function getWithSentryConfigOptionsTemplate({ + orgSlug, + projectSlug, + selfHosted, + tunnelRoute, + sentryUrl, +}: WithSentryConfigOptions): string { + return `{ + // For all available options, see: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/sourcemaps/uploading/bundler-plugin-options/ + + org: "${orgSlug}", + project: "${projectSlug}",${ + selfHosted ? `\n sentryUrl: "${sentryUrl}",` : "" + } + + // Only print logs for uploading source maps in CI + silent: !process.env.CI, + + // For all available options, see: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/ + + // Upload a larger set of source maps for prettier stack traces (increases build time) + widenClientFileUpload: true, + + // ${ + tunnelRoute ? "Route" : "Uncomment to route" + } browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers. + // This can increase your server load as well as your hosting bill. + // Note: Check that the configured route will not match with your Next.js middleware, otherwise reporting of client- + // side errors will fail. + ${tunnelRoute ? "" : "// "}tunnelRoute: "/monitoring", + + webpack: { + // Enables automatic instrumentation of Vercel Cron Monitors. (Does not yet work with App Router route handlers.) + // See the following for more information: + // https://docs.sentry.io/product/crons/ + // https://vercel.com/docs/cron-jobs + automaticVercelMonitors: true, + + // Tree-shaking options for reducing bundle size + treeshake: { + // Automatically tree-shake Sentry logger statements to reduce bundle size + removeDebugLogging: true, + }, + }, +}`; +} + +export function getNextjsConfigCjsTemplate( + withSentryConfigOptionsTemplate: string, + withSentryConfigImportPath: string = SENTRY_NEXTJS_CONFIG_IMPORT_PATH, +): string { + return `const { withSentryConfig } = require("${withSentryConfigImportPath}"); + +/** @type {import('next').NextConfig} */ +const nextConfig = {}; + +module.exports = withSentryConfig(nextConfig, ${withSentryConfigOptionsTemplate}); +`; +} + +export function getNextjsConfigMjsTemplate( + withSentryConfigOptionsTemplate: string, + withSentryConfigImportPath: string = SENTRY_NEXTJS_CONFIG_IMPORT_PATH, +): string { + return `import { withSentryConfig } from "${withSentryConfigImportPath}"; + +/** @type {import('next').NextConfig} */ +const nextConfig = {}; + +export default withSentryConfig(nextConfig, ${withSentryConfigOptionsTemplate}); +`; +} + +export function getNextjsConfigCjsAppendix( + withSentryConfigOptionsTemplate: string, + withSentryConfigImportPath: string = SENTRY_NEXTJS_CONFIG_IMPORT_PATH, +): string { + return ` + +// Injected content via Sentry wizard below + +const { withSentryConfig } = require("${withSentryConfigImportPath}"); + +module.exports = withSentryConfig(module.exports, ${withSentryConfigOptionsTemplate}); +`; +} + +export function getNextjsConfigEsmCopyPasteSnippet( + withSentryConfigOptionsTemplate: string, + withSentryConfigImportPath: string = SENTRY_NEXTJS_CONFIG_IMPORT_PATH, +): string { + return ` + +// next.config.mjs +import { withSentryConfig } from "${withSentryConfigImportPath}"; + +export default withSentryConfig(yourNextConfig, ${withSentryConfigOptionsTemplate}); +`; +} + +function getClientIntegrationsSnippet(features: { replay: boolean }) { + if (features.replay) { + return ` + + // Add optional integrations for additional features + integrations: [Sentry.replayIntegration()],`; + } + + return ""; +} + +function getSpotlightOption(spotlight: boolean): string { + if (!spotlight) { + return ""; + } + + return ` + + // Spotlight enabled for local development (https://spotlightjs.com) + spotlight: true,`; +} + +export function getSentryServersideConfigContents( + dsn: string, + config: "server" | "edge", + selectedFeaturesMap: { + replay: boolean; + performance: boolean; + }, + reduceDataCollection: boolean, + spotlight = false, +): string { + let primer = ""; + if (config === "server") { + primer = `// This file configures the initialization of Sentry on the server. +// The config you add here will be used whenever the server handles a request. +// https://docs.sentry.io/platforms/javascript/guides/nextjs/`; + } else { + primer = `// This file configures the initialization of Sentry for edge features (middleware, edge routes, and so on). +// The config you add here will be used whenever one of the edge features is loaded. +// Note that this config is unrelated to the Vercel Edge Runtime and is also required when running locally. +// https://docs.sentry.io/platforms/javascript/guides/nextjs/`; + } + + let performanceOptions = ""; + if (selectedFeaturesMap.performance) { + performanceOptions += ` + + // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control. + tracesSampleRate: 1,`; + } + + const spotlightOptions = getSpotlightOption(spotlight); + return `${primer} + +import * as Sentry from "@sentry/nextjs"; + +Sentry.init({ + dsn: "${dsn}",${performanceOptions} + +${getDataCollectionBlock(reduceDataCollection)}${spotlightOptions} +}); +`; +} + +export function getInstrumentationClientFileContents( + dsn: string, + selectedFeaturesMap: { + replay: boolean; + performance: boolean; + }, + reduceDataCollection: boolean, + spotlight = false, +): string { + const integrationsOptions = getClientIntegrationsSnippet({ + replay: selectedFeaturesMap.replay, + }); + + let replayOptions = ""; + + if (selectedFeaturesMap.replay) { + replayOptions += ` + + // Define how likely Replay events are sampled. + // 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, + + // Define how likely Replay events are sampled when an error occurs. + replaysOnErrorSampleRate: 1.0,`; + } + + let performanceOptions = ""; + if (selectedFeaturesMap.performance) { + performanceOptions += ` + + // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control. + tracesSampleRate: 1,`; + } + + const spotlightOptions = getSpotlightOption(spotlight); + + return `// This file configures the initialization of Sentry on the client. +// The added config here will be used whenever a users loads a page in their browser. +// https://docs.sentry.io/platforms/javascript/guides/nextjs/ + +import * as Sentry from "@sentry/nextjs"; + +Sentry.init({ + dsn: "${dsn}",${integrationsOptions}${performanceOptions}${replayOptions} + +${getDataCollectionBlock(reduceDataCollection)}${spotlightOptions} +}); + +export const onRouterTransitionStart = Sentry.captureRouterTransitionStart; +`; +} + +export function getSentryExamplePageContents(options: { + selfHosted: boolean; + sentryUrl: string; + orgSlug: string; + projectId: string; + useClient: boolean; + isTypeScript?: boolean | undefined; +}): string { + const issuesPageLink = options.selfHosted + ? `${options.sentryUrl}organizations/${options.orgSlug}/issues/?project=${options.projectId}` + : `https://${options.orgSlug}.sentry.io/issues/?project=${options.projectId}`; + + const loggerPageLoad = ` + Sentry.logger.info("Sentry example page loaded");`; + + const loggerUserAction = ` + Sentry.logger.info("User clicked the button, throwing a sample error");`; + + return `${ + options.useClient ? '"use client";\n\n' : "" + }import * as Sentry from "@sentry/nextjs"; +import Head from "next/head"; +import { useEffect, useState } from "react"; + +class SentryExampleFrontendError extends Error { + constructor(message${options.isTypeScript ? ": string | undefined" : ""}) { + super(message); + this.name = "SentryExampleFrontendError"; + } +} + +export default function Page() { + const [hasSentError, setHasSentError] = useState(false); + const [isConnected, setIsConnected] = useState(true); + + useEffect(() => {${loggerPageLoad} + async function checkConnectivity() { + const result = await Sentry.diagnoseSdkConnectivity(); + setIsConnected(result !== "sentry-unreachable"); + } + checkConnectivity(); + }, []); + + return ( +
+ + sentry-example-page + + + +
+
+ + + +

sentry-example-page

+ +

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

+ + + + {hasSentError ? ( +

Error sent to Sentry.

+ ) : !isConnected ? ( +
+

+ It looks like network requests to Sentry are being blocked, which + will prevent errors from being captured. Try disabling your + ad-blocker to complete the test. +

+
+ ) : ( +
+ )} + +
+
+ + +
+ ); +} +`; +} + +export function getSentryExamplePagesDirApiRoute({ + isTypeScript, +}: { + isTypeScript: boolean; +}) { + const sentryImport = `import * as Sentry from "@sentry/nextjs"; + +`; + + const loggerCall = ` Sentry.logger.info("Sentry example API called"); +`; + + return `${sentryImport}// Custom error class for Sentry testing +class SentryExampleAPIError extends Error { + constructor(message${isTypeScript ? ": string | undefined" : ""}) { + super(message); + this.name = "SentryExampleAPIError"; + } +} +// A faulty API route to test Sentry's error monitoring +export default function handler(_req, res) { +${loggerCall}throw new SentryExampleAPIError("This error is raised on the backend called by the example page."); +res.status(200).json({ name: "John Doe" }); +} +`; +} + +export type ExampleApiRouteDynamicStrategy = "force-dynamic" | "connection"; + +export function getSentryExampleAppDirApiRoute({ + isTypeScript, + dynamicStrategy, +}: { + isTypeScript: boolean; + /** + * How the route opts out of static rendering so the throwing handler runs at + * request time instead of during the build: + * - `force-dynamic`: `export const dynamic = "force-dynamic"`. Needed on Next.js 14, + * where GET route handlers are cached by default. + * - `connection`: `await connection()` from `next/server` (Next.js 15+). Required on + * Next.js 16 with `cacheComponents`, which rejects route segment config. + */ + dynamicStrategy: ExampleApiRouteDynamicStrategy; +}) { + const useConnection = dynamicStrategy === "connection"; + + const sentryImport = `import * as Sentry from "@sentry/nextjs"; +${useConnection ? 'import { connection } from "next/server";\n' : ""}`; + + const forceDynamicExport = useConnection + ? "" + : `export const dynamic = "force-dynamic"; + +`; + + const connectionCall = useConnection + ? ` + // Opt out of prerendering so the error is thrown at request time + await connection();` + : ""; + + const loggerCall = ` + Sentry.logger.info("Sentry example API called");`; + + // Note: We intentionally don't have a return statement after throw - it would be unreachable code + // We also don't import NextResponse since we don't use it (Biome noUnusedImports rule) + return `${sentryImport}${forceDynamicExport}class SentryExampleAPIError extends Error { + constructor(message${isTypeScript ? ": string | undefined" : ""}) { + super(message); + this.name = "SentryExampleAPIError"; + } +} + +// A faulty API route to test Sentry's error monitoring +export ${ + useConnection ? "async " : "" + }function GET() {${connectionCall}${loggerCall} + throw new SentryExampleAPIError( + "This error is raised on the backend called by the example page.", + ); +} +`; +} + +export function getSentryDefaultUnderscoreErrorPage() { + return `import * as Sentry from "@sentry/nextjs"; +import Error from "next/error"; + +const CustomErrorComponent = (props) => { + return ; +}; + +CustomErrorComponent.getInitialProps = async (contextData) => { + // In case this is running in a serverless function, await this in order to give Sentry + // time to send the error before the lambda exits + await Sentry.captureUnderscoreErrorException(contextData); + + // This will contain the status code of the response + return Error.getInitialProps(contextData); +}; + +export default CustomErrorComponent; +`; +} + +export function getSimpleUnderscoreErrorCopyPasteSnippet() { + return ` +${chalk.green(`import * as Sentry from '@sentry/nextjs';`)} +${chalk.green(`import Error from "next/error";`)} + +${chalk.dim( + '// Replace "YourCustomErrorComponent" with your custom error component!', +)} +YourCustomErrorComponent.getInitialProps = async (${chalk.green( + "contextData", + )}) => { + ${chalk.green("await Sentry.captureUnderscoreErrorException(contextData);")} + + ${chalk.dim("// ...other getInitialProps code")} + + return Error.getInitialProps(contextData); +}; +`; +} + +export function getGenerateMetadataSnippet(isTs: boolean) { + return makeCodeSnippet(true, (unchanged, plus) => { + return plus(` + import * as Sentry from '@sentry/nextjs'; + ${isTs ? `import type { Metadata } from 'next';` : ""} + + ${unchanged( + '// Add or edit your "generateMetadata" to include the Sentry trace data:', + )} + export function generateMetadata()${isTs ? ": Metadata" : ""} { + return { + // ... your existing metadata + other: { + ...Sentry.getTraceData() + } + }; + } +`); + }); +} + +export function getFullUnderscoreErrorCopyPasteSnippet(isTs: boolean) { + return ` +import * as Sentry from '@sentry/nextjs';${ + isTs ? '\nimport type { NextPageContext } from "next";' : "" + } +import Error from "next/error"; + +${chalk.dim( + '// Replace "YourCustomErrorComponent" with your custom error component!', +)} +YourCustomErrorComponent.getInitialProps = async (contextData${ + isTs ? ": NextPageContext" : "" + }) => { + await Sentry.captureUnderscoreErrorException(contextData); + + return Error.getInitialProps(contextData); +}; +`; +} + +export function getInstrumentationHookContent( + instrumentationHookLocation: "src" | "root", +) { + return `import * as Sentry from "@sentry/nextjs"; + +export async function register() { + if (process.env.NEXT_RUNTIME === "nodejs") { + await import("${ + instrumentationHookLocation === "root" ? "." : ".." + }/sentry.server.config"); + } + + if (process.env.NEXT_RUNTIME === "edge") { + await import("${ + instrumentationHookLocation === "root" ? "." : ".." + }/sentry.edge.config"); + } +} + +export const onRequestError = Sentry.captureRequestError; +`; +} + +export function getInstrumentationHookCopyPasteSnippet( + instrumentationHookLocation: "src" | "root", +) { + return makeCodeSnippet(true, (unchanged, plus) => { + return unchanged(`${plus("import * as Sentry from '@sentry/nextjs';")} + +export ${plus("async")} function register() { + ${plus(`if (process.env.NEXT_RUNTIME === 'nodejs') { + await import('${ + instrumentationHookLocation === "root" ? "." : ".." + }/sentry.server.config'); + } + + if (process.env.NEXT_RUNTIME === 'edge') { + await import('${ + instrumentationHookLocation === "root" ? "." : ".." + }/sentry.edge.config'); + }`)} +} + +${plus("export const onRequestError = Sentry.captureRequestError;")} +`); + }); +} + +export function getInstrumentationClientHookCopyPasteSnippet( + dsn: string, + selectedFeaturesMap: { + replay: boolean; + performance: boolean; + }, + reduceDataCollection: boolean, + spotlight = false, +) { + return makeCodeSnippet(true, (_unchanged, plus) => { + return plus( + getInstrumentationClientFileContents( + dsn, + selectedFeaturesMap, + reduceDataCollection, + spotlight, + ), + ); + }); +} + +export function getSentryDefaultGlobalErrorPage(isTs: boolean) { + return isTs + ? `"use client"; + +import * as Sentry from "@sentry/nextjs"; +import NextError from "next/error"; +import { useEffect } from "react"; + +export default function GlobalError({ + error, +}: { + error: Error & { digest?: string }; +}) { + useEffect(() => { + Sentry.captureException(error); + }, [error]); + + return ( + + + {/* \`NextError\` is the default Next.js error page component. Its type + definition requires a \`statusCode\` prop. However, since the App Router + does not expose status codes for errors, we simply pass 0 to render a + generic error message. */} + + + + ); +} +` + : `"use client"; + +import * as Sentry from "@sentry/nextjs"; +import NextError from "next/error"; +import { useEffect } from "react"; + +export default function GlobalError({ error }) { + useEffect(() => { + Sentry.captureException(error); + }, [error]); + + return ( + + + {/* \`NextError\` is the default Next.js error page component. Its type + definition requires a \`statusCode\` prop. However, since the App Router + does not expose status codes for errors, we simply pass 0 to render a + generic error message. */} + + + + ); +} +`; +} + +export function getGlobalErrorCopyPasteSnippet(isTs: boolean) { + if (isTs) { + return `"use client"; + +${chalk.green('import * as Sentry from "@sentry/nextjs";')} +${chalk.green('import Error from "next/error";')} +${chalk.green('import { useEffect } from "react";')} + +export default function GlobalError(${chalk.green( + "{ error }: { error: Error }", + )}) { + ${chalk.green(`useEffect(() => { + Sentry.captureException(error); + }, [error]);`)} + + return ( + + + {/* Your Error component here... */} + + + ); +} +`; + } + return `"use client"; + +${chalk.green('import * as Sentry from "@sentry/nextjs";')} +${chalk.green('import Error from "next/error";')} +${chalk.green('import { useEffect } from "react";')} + +export default function GlobalError(${chalk.green("{ error }")}) { + ${chalk.green(`useEffect(() => { + Sentry.captureException(error); + }, [error]);`)} + + return ( + + + {/* Your Error component here... */} + + + ); +} +`; +} + +export const getRootLayout = ( + isTs: boolean, +) => `// This file was generated by the Sentry wizard because we couldn't find a root layout file. +// You can delete this file at any time. + +export const metadata = { + title: 'Sentry NextJS Example', + description: 'Generated by Sentry', +} + +export default function RootLayout({ + children, +}${ + isTs + ? `: { + children: React.ReactNode +}` + : "" +}) { + return ( + + {children} + + ) +} +`; + +export const getRootLayoutWithGenerateMetadata = ( + isTs: boolean, +) => `// This file was generated by the Sentry wizard because we couldn't find a root layout file. +import * as Sentry from '@sentry/nextjs'; +${isTs ? `import type { Metadata } from 'next';` : ""} + +export function generateMetadata()${isTs ? ": Metadata" : ""} { + return { + other: { + ...Sentry.getTraceData(), + } + } +}; + +export default function RootLayout({ + children, +}${ + isTs + ? `: { + children: React.ReactNode +}` + : "" +}) { + return ( + + {children} + + ) +} +`; diff --git a/packages/cli/src/lib/wizard/nextjs/utils.ts b/packages/cli/src/lib/wizard/nextjs/utils.ts new file mode 100644 index 0000000000..c99e6ecc25 --- /dev/null +++ b/packages/cli/src/lib/wizard/nextjs/utils.ts @@ -0,0 +1,182 @@ +/** + * Helpers of the Next.js wizard: SDK versions, project layout, and + * config-file detection. + */ + +import { existsSync, lstatSync } from "node:fs"; +import path from "node:path"; +import { lt, major, minVersion } from "semver"; +import { type ASTNode, builders, type ProxifiedModule } from "magicast"; +import { + SENTRY_NEXTJS_CONFIG_IMPORT_PATH, + SENTRY_NEXTJS_ROOT_IMPORT_PATH, + type ExampleApiRouteDynamicStrategy, +} from "./templates.js"; +import { debug } from "../utils/debug.js"; + +/** First `@sentry/nextjs` release that exposes `withSentryConfig` on the `/config` subpath. */ +export const MIN_SDK_VERSION_WITH_CONFIG_SUBPATH = "10.73.0"; + +/** + * Returns the module `withSentryConfig` should be imported from for the + * installed SDK version. The wizard installs `^11`, but a user can keep an + * older SDK by declining the update prompt. Those releases only expose + * `withSentryConfig` on the root export, so fall back to it there. Unknown or + * unparseable versions get the subpath, which is the only option on v11. + */ +export function getWithSentryConfigImportPath( + sdkVersion: string | undefined, +): string { + if (!sdkVersion) { + return SENTRY_NEXTJS_CONFIG_IMPORT_PATH; + } + + try { + const minVer = minVersion(sdkVersion); + if (minVer && lt(minVer, MIN_SDK_VERSION_WITH_CONFIG_SUBPATH)) { + return SENTRY_NEXTJS_ROOT_IMPORT_PATH; + } + } catch (error) { + debug(error); + // fall through + } + + return SENTRY_NEXTJS_CONFIG_IMPORT_PATH; +} + +/** Minimum Next.js major supported by the Sentry Next.js SDK (v11 dropped Next.js 13). */ +export const MIN_SUPPORTED_NEXTJS_MAJOR = 14; + +/** + * Returns `false` when the given Next.js version range is definitely below the + * minimum the SDK supports. Unknown or unparseable versions are treated as supported. + */ +export function isNextJsVersionSupported(version: string | undefined): boolean { + if (!version) { + return true; + } + + try { + const minVer = minVersion(version); + if (!minVer) { + return true; + } + return major(minVer) >= MIN_SUPPORTED_NEXTJS_MAJOR; + } catch (error) { + debug(error); + return true; + } +} + +/** + * Picks how the generated example API route opts out of static rendering. + * Next.js 14 caches GET route handlers by default, so the route needs + * `export const dynamic = "force-dynamic"` or the build evaluates (and fails on) + * the throwing handler. Next.js 15+ ships `connection()` from `next/server`, + * which also works on Next.js 16 with `cacheComponents`, where route segment + * config is rejected. Unknown versions keep the previous `force-dynamic` behavior. + */ +export function getExampleApiRouteDynamicStrategy( + version: string | undefined, +): ExampleApiRouteDynamicStrategy { + if (!version) { + return "force-dynamic"; + } + + try { + const minVer = minVersion(version); + if (!minVer) { + return "force-dynamic"; + } + return major(minVer) >= 15 ? "connection" : "force-dynamic"; + } catch (error) { + debug(error); + return "force-dynamic"; + } +} + +/** + * Adds `import { withSentryConfig } from ` to the module. + * If the module already imports `withSentryConfig` (e.g. from the root + * `@sentry/nextjs` export used by SDK v10 and earlier), the existing import is + * rewritten to the given path instead of adding a duplicate binding. + */ +export function addWithSentryConfigImport( + mod: ProxifiedModule, + importPath: string = SENTRY_NEXTJS_CONFIG_IMPORT_PATH, +): void { + mod.imports.$add({ + from: importPath, + imported: "withSentryConfig", + local: "withSentryConfig", + }); +} + +export function getNextJsVersionBucket(version: string | undefined) { + if (!version) { + return "none"; + } + + try { + const minVer = minVersion(version); + if (!minVer) { + return "invalid"; + } + const majorVersion = major(minVer); + if (majorVersion >= 11) { + return `${majorVersion}.x`; + } + return "<11.0.0"; + } catch (error) { + debug(error); + return "unknown"; + } +} + +export function getMaybeAppDirLocation() { + const maybeAppDirPath = path.join(process.cwd(), "app"); + const maybeSrcAppDirPath = path.join(process.cwd(), "src", "app"); + + return existsSync(maybeAppDirPath) && lstatSync(maybeAppDirPath).isDirectory() + ? ["app"] + : existsSync(maybeSrcAppDirPath) && + lstatSync(maybeSrcAppDirPath).isDirectory() + ? ["src", "app"] + : undefined; +} + +export function hasRootLayoutFile(appFolderPath: string) { + return ["jsx", "tsx", "js"].some((ext) => + existsSync(path.join(appFolderPath, `layout.${ext}`)), + ); +} + +/** + * Unwraps a withSentryConfig call expression using magicast. + */ +export function unwrapSentryConfigAst(astNode: ASTNode): ASTNode { + if ( + astNode.type === "CallExpression" && + astNode.callee.type === "Identifier" && + astNode.callee.name === "withSentryConfig" + ) { + // Return the first argument (the config being wrapped) + return astNode.arguments[0] ?? astNode; + } + + return astNode; +} + +/** + * Wraps a magicast module export with withSentryConfig using magicast + */ +export function wrapWithSentryConfig( + moduleExport: unknown, + optionsTemplate: string, +): ReturnType { + return builders.functionCall( + "withSentryConfig", + moduleExport, + builders.raw(optionsTemplate), + ); +} diff --git a/packages/cli/src/lib/wizard/run.ts b/packages/cli/src/lib/wizard/run.ts new file mode 100644 index 0000000000..8bd377980b --- /dev/null +++ b/packages/cli/src/lib/wizard/run.ts @@ -0,0 +1,128 @@ +/** + * Pick and run a setup wizard for `sentry wizard`. + * + * Each integration's flow lives in its own directory and loads with a + * dynamic `import()`, so a run loads only the flow it needs (and its heavy + * dependencies, such as magicast). + */ + +import { ValidationError } from "../errors.js"; +import { abortIfCancelled } from "./utils/clack/index.js"; +import { clack } from "./utils/clack/prompts.js"; +import { enableDebugLogs } from "./utils/debug.js"; +import type { WizardOptions } from "./utils/types.js"; +import { CLI_VERSION } from "../constants.js"; + +/** + * The integrations `sentry wizard -i` accepts, in the order the picker lists + * them. The ids are the ones `@sentry/wizard -i` took. + */ +export const WIZARD_INTEGRATIONS = [ + { id: "reactNative", label: "React Native" }, + { id: "flutter", label: "Flutter" }, + { id: "ios", label: "iOS" }, + { id: "appleSnapshots", label: "Apple Snapshots" }, + { id: "angular", label: "Angular" }, + { id: "android", label: "Android" }, + { id: "nextjs", label: "Next.js" }, + { id: "nuxt", label: "Nuxt" }, + { id: "remix", label: "Remix" }, + { id: "reactRouter", label: "React Router" }, + { id: "sveltekit", label: "SvelteKit" }, + { id: "cloudflare", label: "Cloudflare" }, + { id: "sourcemaps", label: "Configure Source Maps Upload" }, +] as const; + +/** An integration id `sentry wizard -i` accepts. */ +export type WizardIntegration = (typeof WIZARD_INTEGRATIONS)[number]["id"]; + +/** + * Every value `-i` accepts. The Cordova and Electron wizards of + * `@sentry/wizard` were retired; their setup guides are in the Sentry docs. + */ +export const INTEGRATION_IDS: readonly WizardIntegration[] = + WIZARD_INTEGRATIONS.map((integration) => integration.id); + +/** Runs the wizard of one integration. */ +type WizardRunner = (options: WizardOptions) => Promise; + +/** + * The flow of each integration. Integrations without one are still being + * moved over from sentry-wizard. + */ +const WIZARD_RUNNERS: Partial> = { + nextjs: async (options) => { + const { runNextjsWizard } = await import("./nextjs/nextjs-wizard.js"); + await runNextjsWizard(options); + }, +}; + +/** What `sentry wizard` passes to {@link runWizard}. */ +export type RunWizardArgs = { + /** `-i`: the integration to set up; prompts for one when unset. */ + integration?: string | undefined; + /** `--debug`: print the wizard's debug output. */ + debug: boolean; + /** The options every wizard flow takes. */ + wizardOptions: WizardOptions; +}; + +/** + * Run the wizard of `args.integration`, after asking for one when it is + * unset. + * + * @throws {ValidationError} For an unknown integration, or one that has no + * flow in this version yet + */ +export async function runWizard(args: RunWizardArgs): Promise { + if (args.debug) { + enableDebugLogs(); + } + + const integration = args.integration + ? toWizardIntegration(args.integration) + : await askForIntegration(); + + const runner = WIZARD_RUNNERS[integration]; + if (!runner) { + throw new ValidationError( + `The ${integration} wizard is not available in this version yet.`, + "integration", + ); + } + await runner(args.wizardOptions); +} + +/** + * `id` as one of {@link WIZARD_INTEGRATIONS}. `-i` already checks its + * value; `SENTRY_WIZARD_INTEGRATION` is checked here. + * + * @throws {ValidationError} When `id` names no integration + */ +function toWizardIntegration(id: string): WizardIntegration { + const match = WIZARD_INTEGRATIONS.find( + (integration) => integration.id === id, + ); + if (!match) { + throw new ValidationError( + `Unknown integration "${id}". Pick one of: ${INTEGRATION_IDS.join(", ")}.`, + "integration", + ); + } + return match.id; +} + +/** Ask which integration to set up, out of the ones that have a flow. */ +async function askForIntegration(): Promise { + clack.intro(`Sentry Wizard ${CLI_VERSION}`); + const integration = await abortIfCancelled( + clack.select({ + message: "What do you want to set up?", + options: WIZARD_INTEGRATIONS.filter(({ id }) => id in WIZARD_RUNNERS).map( + ({ id, label }) => ({ value: id, label }), + ), + }), + ); + clack.outro(`Starting ${integration} setup`); + return integration; +} diff --git a/packages/cli/src/lib/wizard/sourcemaps/ci.ts b/packages/cli/src/lib/wizard/sourcemaps/ci.ts new file mode 100644 index 0000000000..e725f44a51 --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/ci.ts @@ -0,0 +1,130 @@ +/** + * Help the user make the source map upload auth token available in CI. + * + * Shared by the framework wizards and the source maps wizard. Ported from + * sentry-wizard's `src/sourcemaps/sourcemaps-wizard.ts`. + */ + +import chalk from "chalk"; +import { Sentry, traceStep } from "../telemetry.js"; +import { + abortIfCancelled, + SENTRY_CLI_RC_FILE, + SENTRY_DOT_ENV_FILE, +} from "../utils/clack/index.js"; +import { clack } from "../utils/clack/prompts.js"; +import type { WizardOptions } from "../utils/types.js"; + +/** Tools that upload with `sentry` commands and read `.sentryclirc`. */ +const CLI_BASED_FLOW_TOOLS: readonly string[] = [ + "sentry-cli", + "tsc", + "angular", + "create-react-app", +]; + +/** + * Ask whether the user builds in CI and, if so, show the auth token to set + * there. Skipped for partner flows (Vercel) that already set the token. + * + * @param selectedTool - The build tool the wizard configured, such as `nextjs` + * @param authToken - The token written to the local config file + * @param comingFrom - The partner the command came from (`--coming-from`) + */ +export async function setupCI( + selectedTool: string, + authToken: string, + comingFrom: WizardOptions["comingFrom"], +): Promise { + if (comingFrom === "vercel") { + clack.log.info( + "Sentry Vercel integration is already configured. Skipping CI setup.", + ); + Sentry.setTag("using-ci", true); + } else { + await traceStep("configure-ci", () => configureCI(selectedTool, authToken)); + } +} + +/** Ask about CI and show the auth token to set there. */ +async function configureCI( + selectedTool: string, + authToken: string, +): Promise { + const isUsingCI = await abortIfCancelled( + clack.select({ + message: `Are you using a CI/CD tool to build and deploy your application?`, + options: [ + { + label: "Yes", + hint: "I use a tool like GitHub Actions, GitLab, CircleCI, TravisCI, Jenkins, Vercel, ...", + value: true, + }, + { + label: "No", + hint: "I build and deploy my application manually", + value: false, + }, + ], + initialValue: true, + }), + ); + + Sentry.setTag("using-ci", isUsingCI); + + const authTokenFile = CLI_BASED_FLOW_TOOLS.includes(selectedTool) + ? SENTRY_CLI_RC_FILE + : SENTRY_DOT_ENV_FILE; + + if (!isUsingCI) { + clack.log.info( + `No Problem! Just make sure that the Sentry auth token from ${chalk.cyan( + authTokenFile, + )} is available whenever you build and deploy your app.`, + ); + return; + } + + await traceStep("ci-auth-token-setup", () => setupAuthTokenInCI(authToken)); +} + +/** Show the auth token to add to the CI environment. */ +async function setupAuthTokenInCI(authToken: string): Promise { + clack.log.step( + "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} +`), + ); + + clack.log.warn( + chalk.yellow("DO NOT commit this auth token to your repository!"), + ); + + const addedEnvVarToCI = await abortIfCancelled( + clack.select({ + message: "Did you configure CI as shown above?", + options: [ + { label: "Yes, continue!", value: true }, + { + label: "I'll do it later...", + value: false, + hint: chalk.yellow( + "You need to set the auth token to upload source maps in CI", + ), + }, + ], + initialValue: true, + }), + ); + + Sentry.setTag("added-env-var-to-ci", addedEnvVarToCI); + + if (!addedEnvVarToCI) { + clack.log.info("Don't forget! :)"); + } +} diff --git a/packages/cli/src/lib/wizard/telemetry.ts b/packages/cli/src/lib/wizard/telemetry.ts new file mode 100644 index 0000000000..09a39e330d --- /dev/null +++ b/packages/cli/src/lib/wizard/telemetry.ts @@ -0,0 +1,78 @@ +/** + * Telemetry for the setup wizards, recorded through the CLI's own Sentry + * client. + * + * `sentry wizard` already runs inside the CLI's command transaction, so a + * wizard flow is a `wizard.flow` span under it and each step a `wizard.step` + * span under that. Tags go on the same scope as the CLI's. Telemetry is off + * when the CLI's is (`SENTRY_CLI_NO_TELEMETRY`, `DO_NOT_TRACK`, or + * `sentry cli defaults telemetry off`), and `--disable-telemetry` turns it + * off for the run. + * + * The old wizard sent its telemetry to a project of its own; the tag names + * stay the same so its dashboards can move over. + */ + +import { type Span, setTag, setUser, startSpan } from "@sentry/node"; +import type { WizardOptions } from "./utils/types.js"; + +/** + * The scope helpers the wizard flows call as `Sentry.setTag(…)`. + * + * Report errors with `reportCliError` from `lib/error-reporting.js`, never a + * raw `captureException`. + */ +export const Sentry = { setTag, setUser }; + +/** + * Run a wizard flow in a `wizard.flow` span, tagged with the integration and + * which of `--org`, `--project`, and `--saas` were passed. + */ +export async function withTelemetry( + options: { + /** Unused: the CLI decides whether telemetry is on. Kept for the flows' call sites. */ + enabled?: boolean | undefined; + integration: string; + wizardOptions: WizardOptions; + }, + callback: () => F | Promise, +): Promise { + setTag("integration", options.integration); + setTag("args.project", Boolean(options.wizardOptions.projectSlug)); + setTag("args.org", Boolean(options.wizardOptions.orgSlug)); + setTag("args.saas", Boolean(options.wizardOptions.saas)); + + return await startSpan( + { + name: "sentry-wizard-execution", + op: "wizard.flow", + onlyIfParent: true, + }, + async () => { + updateProgress("start"); + const result = await callback(); + updateProgress("finished"); + return result; + }, + ); +} + +/** + * Run one wizard step in a `wizard.step` span and record it as the latest + * `progress` tag, so an aborted run shows where it stopped. + */ +export function traceStep( + step: string, + callback: (span: Span | undefined) => T, +): T { + updateProgress(step); + return startSpan( + { name: step, op: "wizard.step", onlyIfParent: true }, + (span) => callback(span), + ); +} + +/** Record `step` as the furthest step the wizard reached. */ +export function updateProgress(step: string): void { + setTag("progress", step); +} diff --git a/packages/cli/src/lib/wizard/utils/clack/index.ts b/packages/cli/src/lib/wizard/utils/clack/index.ts new file mode 100644 index 0000000000..fd740e4b6e --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/clack/index.ts @@ -0,0 +1,1781 @@ +/** + * Shared prompts and project helpers of the setup wizards: aborting, git + * checks, package installs, Sentry CLI config files, formatters, and + * copy/paste instructions. Ported from sentry-wizard's `src/utils/clack`. + * + * The wizards never exit the process: {@link abort} and + * {@link abortIfCancelled} throw a {@link WizardExitError}, which + * `sentry wizard` turns into its exit code. + */ + +import { execSync, spawn } from "node:child_process"; +import { + accessSync, + existsSync, + promises, + readFileSync, + writeFileSync, +} from "node:fs"; +import { createRequire } from "node:module"; +import path, { basename, dirname, isAbsolute, join, relative } from "node:path"; +import chalk from "chalk"; +import { gte, minVersion, validRange } from "semver"; +import { sentry } from "../../../app-identity.js"; +import { CLI_VERSION } from "../../../constants.js"; +import { reportCliError } from "../../../error-reporting.js"; +import { WizardExitError } from "../../../errors.js"; +import { Sentry, traceStep } from "../../telemetry.js"; +import { debug } from "../debug.js"; +import { getUncommittedOrUntrackedFilePaths, isInGitRepo } from "../git.js"; +import { + getPackageVersion, + hasPackageInstalled, + type PackageDotJson, +} from "../package-json.js"; +import { + _detectPackageManger, + NPM, + type PackageManager, + packageManagers, +} from "../package-manager.js"; +import { fulfillsVersionRange } from "../semver.js"; +import type { Feature } from "../types.js"; +import { clack } from "./prompts.js"; + +export { getOrAskForProjectData } from "../project-data.js"; + +export const SENTRY_DOT_ENV_FILE = ".env.sentry-build-plugin"; +export const SENTRY_CLI_RC_FILE = ".sentryclirc"; +export const SENTRY_PROPERTIES_FILE = "sentry.properties"; + +export interface CliSetupConfig { + filename: string; + name: string; + gitignore: boolean; + + likelyAlreadyHasAuthToken(contents: string): boolean; + tokenContent(authToken: string): string; + + likelyAlreadyHasOrgAndProject(contents: string): boolean; + orgAndProjContent(org: string, project: string): string; + + likelyAlreadyHasUrl?(contents: string): boolean; + urlContent?(url: string): string; +} + +export interface CliSetupConfigContent { + authToken: string; + org?: string | undefined; + project?: string | undefined; + url?: string | undefined; +} + +export const rcCliSetupConfig: CliSetupConfig = { + filename: SENTRY_CLI_RC_FILE, + name: "source maps", + gitignore: true, + likelyAlreadyHasAuthToken: function (contents: string): boolean { + return !!(contents.includes("[auth]") && contents.match(/token=./g)); + }, + tokenContent: function (authToken: string): string { + return `[auth]\ntoken=${authToken}`; + }, + likelyAlreadyHasOrgAndProject: function (contents: string): boolean { + return !!( + contents.includes("[defaults]") && + contents.match(/org=./g) && + contents.match(/project=./g) + ); + }, + orgAndProjContent: function (org: string, project: string): string { + return `[defaults]\norg=${org}\nproject=${project}`; + }, +}; + +export const propertiesCliSetupConfig: Required = { + filename: SENTRY_PROPERTIES_FILE, + gitignore: true, + name: "debug files", + likelyAlreadyHasAuthToken(contents: string): boolean { + return !!contents.match(/auth\.token=./g); + }, + tokenContent(authToken: string): string { + return `auth.token=${authToken}`; + }, + likelyAlreadyHasOrgAndProject(contents: string): boolean { + return !!( + contents.match(/defaults\.org=./g) && + contents.match(/defaults\.project=./g) + ); + }, + orgAndProjContent(org: string, project: string): string { + return `defaults.org=${org}\ndefaults.project=${project}`; + }, + likelyAlreadyHasUrl(contents: string): boolean { + return !!contents.match(/defaults\.url=./g); + }, + urlContent(url: string): string { + return `defaults.url=${url}`; + }, +}; + +/** + * Stop the wizard with `message`. `status` 0 means the user chose to stop; + * anything else is a failure. Throws, so code after it never runs. + * + * @param message - Shown as the outro. Defaults to "Wizard setup cancelled." + * @param status - Exit code of `sentry wizard`. Defaults to 1. + */ +export async function abort(message?: string, status?: number): Promise { + clack.outro(message ?? "Wizard setup cancelled."); + Sentry.setTag("wizard.outcome", status === 0 ? "cancelled" : "aborted"); + throw new WizardExitError(status ?? 1); +} + +/** + * Resolve `input`, or stop the wizard with exit code 0 when the user + * cancelled the prompt (Ctrl+C). + */ +export async function abortIfCancelled( + input: T | Promise, +): Promise> { + const value = await input; + if (clack.isCancel(value)) { + clack.cancel("Wizard setup cancelled."); + Sentry.setTag("wizard.outcome", "cancelled"); + throw new WizardExitError(0); + } + return value as Exclude; +} + +/** Print the intro banner and welcome note of a wizard. */ +export function printWelcome(options: { + wizardName: string; + promoCode?: string | undefined; + message?: string | undefined; + telemetryEnabled?: boolean | undefined; +}): void { + clack.rawOutput(""); + clack.intro(chalk.inverse(` ${options.wizardName} `)); + + let welcomeText = + options.message || + `The ${options.wizardName} will help you set up Sentry for your application.\nThank you for using Sentry :)`; + + if (options.promoCode) { + welcomeText = `${welcomeText}\n\nUsing promo-code: ${options.promoCode}`; + } + + welcomeText = `${welcomeText}\n\nVersion: ${CLI_VERSION}`; + + if (options.telemetryEnabled) { + welcomeText = `${welcomeText} + +This wizard sends telemetry data and crash reports to Sentry. This helps us improve the Wizard. +You can turn this off at any time by running ${chalk.cyanBright( + sentry`wizard --disable-telemetry`, + )}.`; + } + + clack.note(welcomeText); +} + +/** + * Confirms if the user wants to continue with the wizard if the project is not a git repository. + * + * @param options.ignoreGitChanges If true, the wizard will not check if the project is a git repository. + * @param options.cwd The directory of the project. If undefined, the current process working directory will be used. + */ +export async function confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges, + cwd, + nonInteractive = false, +}: { + ignoreGitChanges: boolean | undefined; + cwd: string | undefined; + nonInteractive?: boolean | undefined; +}): Promise { + return await traceStep("check-git-status", async () => { + if ( + !isInGitRepo({ + cwd: cwd, + }) && + ignoreGitChanges !== true + ) { + if (nonInteractive) { + clack.log.error( + "Project is not inside a git repository in non-interactive mode. Run from a git repository or pass --ignore-git-changes to skip this safety check.", + ); + Sentry.setTag("continue-without-git", false); + await abort(); + } + + const continueWithoutGit = await abortIfCancelled( + clack.confirm({ + message: + "You are not inside a git repository. The wizard will create and update files. Do you want to continue anyway?", + }), + ); + + Sentry.setTag("continue-without-git", continueWithoutGit); + + if (!continueWithoutGit) { + await abort(undefined, 0); + } + // return early to avoid checking for uncommitted files + return; + } + + const uncommittedOrUntrackedFilePaths = getUncommittedOrUntrackedFilePaths({ + cwd: cwd, + }); + + if (uncommittedOrUntrackedFilePaths.length && ignoreGitChanges !== true) { + clack.log.warn( + `You have uncommitted or untracked files in your repo: + +${uncommittedOrUntrackedFilePaths.map((file) => `- ${file}`).join("\n")} + +The wizard will create and update files.`, + ); + + if (nonInteractive) { + clack.log.error( + "Project has uncommitted or untracked files in non-interactive mode. Commit or stash your changes, or pass --ignore-git-changes to skip this safety check.", + ); + Sentry.setTag("continue-with-dirty-repo", false); + await abort(); + } + + const continueWithDirtyRepo = await abortIfCancelled( + clack.confirm({ + message: "Do you want to continue anyway?", + }), + ); + + Sentry.setTag("continue-with-dirty-repo", continueWithDirtyRepo); + + if (!continueWithDirtyRepo) { + await abort(undefined, 0); + } + } + }); +} + +export async function askToInstallSentryCLI(): Promise { + return await abortIfCancelled( + clack.confirm({ + message: + "You don't have Sentry CLI installed. Do you want to install it?", + }), + ); +} + +export async function askForItemSelection( + items: string[], + message: string, +): Promise<{ value: string; index: number }> { + const selection: { value: string; index: number } | symbol = + await abortIfCancelled( + clack.select({ + maxItems: 12, + message: message, + options: items.map((item, index) => { + return { + value: { value: item, index: index }, + label: item, + }; + }), + }), + ); + + return selection; +} + +export async function confirmContinueIfPackageVersionNotSupported({ + packageId, + packageName, + packageVersion, + acceptableVersions, + note, +}: { + packageId: string; + packageName: string; + packageVersion: string; + acceptableVersions: string; + note?: string | undefined; +}): Promise { + return await traceStep(`check-package-version`, async () => { + Sentry.setTag(`${packageName.toLowerCase()}-version`, packageVersion); + const isSupportedVersion = fulfillsVersionRange({ + acceptableVersions, + version: packageVersion, + canBeLatest: true, + }); + + if (isSupportedVersion) { + Sentry.setTag(`${packageName.toLowerCase()}-supported`, true); + return; + } + + clack.log.warn( + `You have an unsupported version of ${packageName} installed: + + ${packageId}@${packageVersion}`, + ); + + clack.note( + note ?? + `Please upgrade to ${acceptableVersions} if you wish to use the Sentry Wizard.`, + ); + const continueWithUnsupportedVersion = await abortIfCancelled( + clack.confirm({ + message: "Do you want to continue anyway?", + }), + ); + Sentry.setTag( + `${packageName.toLowerCase()}-continue-with-unsupported-version`, + continueWithUnsupportedVersion, + ); + + if (!continueWithUnsupportedVersion) { + await abort(undefined, 0); + } + }); +} + +const JS_SDK_V11_MIGRATION_GUIDE_URL = + "https://docs.sentry.io/platforms/javascript/migration/v10-to-v11/"; + +/** Docs guide slugs of the SDKs that have a platform-specific migration guide. */ +const JS_SDK_V11_MIGRATION_GUIDE_SLUGS: Record = { + "@sentry/angular": "angular", + "@sentry/cloudflare": "cloudflare", + "@sentry/nextjs": "nextjs", + "@sentry/nuxt": "nuxt", + "@sentry/react-router": "react-router", + "@sentry/remix": "remix", + "@sentry/sveltekit": "sveltekit", +}; + +function getSdkV11MigrationGuideUrl(packageName: string): string { + const slug = JS_SDK_V11_MIGRATION_GUIDE_SLUGS[packageName]; + + return slug + ? `https://docs.sentry.io/platforms/javascript/guides/${slug}/migration/v10-to-v11/` + : JS_SDK_V11_MIGRATION_GUIDE_URL; +} + +/** + * Logs a link to the v10 to v11 migration guide if @param packageName is + * already installed at a version below v11. The wizard updates the SDK to v11, + * which contains breaking changes the user must apply to their code. + */ +export function printSdkV11MigrationGuideIfOutdated( + packageName: string, + packageJson: PackageDotJson, +): void { + const installedRange = getPackageVersion(packageName, packageJson); + const installedVersion = + installedRange && validRange(installedRange) + ? minVersion(installedRange) + : null; + + if (!installedVersion || gte(installedVersion, "11.0.0")) { + return; + } + + clack.log.warn( + `The wizard updates ${chalk.cyan( + packageName, + )} to version 11, which has ${chalk.bold("breaking changes")}. +Follow the migration guide to update your code: ${chalk.cyan( + getSdkV11MigrationGuideUrl(packageName), + )}`, + ); +} + +type InstallPackageOptions = { + /** The string that is passed to the package manager CLI as identifier to install (e.g. `@sentry/nextjs`, or `@sentry/nextjs@^8`) */ + packageName: string; + alreadyInstalled: boolean; + askBeforeUpdating?: boolean | undefined; + /** Overrides what is shown in the installation logs in place of the `packageName` option. Useful if the `packageName` is ugly (e.g. `@sentry/nextjs@^8`) */ + packageNameDisplayLabel?: string | undefined; + packageManager?: PackageManager | undefined; + /** Add force install flag to command to skip install precondition fails */ + forceInstall?: boolean | undefined; + /** Install as a dev dependency (@default: false) */ + devDependency?: boolean | undefined; +}; + +/** + * Installs or updates a package with the user's package manager. + * + * IMPORTANT: This function modifies the `package.json`! Be sure to re-read + * it if you make additional modifications to it after calling this function! + */ +export async function installPackage({ + packageName, + alreadyInstalled, + askBeforeUpdating = true, + packageNameDisplayLabel, + packageManager, + forceInstall = false, + devDependency = false, +}: InstallPackageOptions): Promise<{ packageManager?: PackageManager }> { + return await traceStep("install-package", async () => { + if (alreadyInstalled && askBeforeUpdating) { + const shouldUpdatePackage = await abortIfCancelled( + clack.confirm({ + message: `The ${chalk.bold.cyan( + packageNameDisplayLabel ?? packageName, + )} package is already installed. Do you want to update it to the latest version?`, + }), + ); + + if (!shouldUpdatePackage) { + return {}; + } + } + + const sdkInstallSpinner = clack.spinner(); + + const pkgManager = packageManager || (await getPackageManager()); + + if (pkgManager.name === "pnpm") { + clack.log.info( + `If you use pnpm 11, dependency build scripts require explicit approval. If installation fails with ${chalk.cyan( + "ERR_PNPM_IGNORED_BUILDS", + )}, review the pending packages, run ${chalk.cyan( + "pnpm approve-builds", + )}, and then rerun the wizard.`, + ); + } + + sdkInstallSpinner.start( + `${alreadyInstalled ? "Updating" : "Installing"} ${chalk.bold.cyan( + packageNameDisplayLabel ?? packageName, + )} with ${chalk.bold(pkgManager.label)}.`, + ); + + try { + await new Promise((resolve, reject) => { + const installArgs = [ + pkgManager.installCommand, + ...(devDependency ? ["-D"] : []), + pkgManager.registry + ? `${pkgManager.registry}:${packageName}` + : packageName, + ...(pkgManager.flags ? pkgManager.flags.split(" ") : []), + ...(forceInstall ? [pkgManager.forceInstallFlag] : []), + ]; + + const stringifiedInstallCmd = `${pkgManager.name} ${installArgs.join( + " ", + )}`; + + function handleErrorAndReject( + code: number | null, + cause: Error | string, + type: "spawn_error" | "process_error", + ) { + const output = [stdout, stderr].filter(Boolean).join("\n"); + // Write a log file so we can better troubleshoot issues + writeFileSync( + join( + process.cwd(), + `sentry-wizard-installation-error-${Date.now()}.log`, + ), + output, + { encoding: "utf8" }, + ); + + reportCliError(new Error("Package Installation Error"), { + tags: { + "install-command": stringifiedInstallCmd, + "package-manager": pkgManager.name, + "package-name": packageName, + "error-type": type, + }, + }); + + reject( + new Error( + `Installation command ${chalk.cyan( + stringifiedInstallCmd, + )} exited with code ${code ?? "null"}.`, + { + cause, + }, + ), + ); + } + + const installProcess = spawn(pkgManager.name, installArgs, { + shell: true, + // Ignoring Yarn `stdout` to prevent certain node + yarn v4 (observed on ubuntu + snap) + // combinations from crashing here. See #851 + stdio: [ + "pipe", + pkgManager.name === "yarn" ? "ignore" : "pipe", + "pipe", + ], + }); + + let stdout = ""; + let stderr = ""; + + // Defining data as unknown to avoid TS and ESLint errors because of `any` type + installProcess.stdout?.on("data", (data: unknown) => { + stdout += String(data); + }); + installProcess.stderr?.on("data", (data: unknown) => { + stderr += String(data); + }); + + installProcess.on("error", (err) => { + handleErrorAndReject(null, err, "spawn_error"); + }); + + installProcess.on("close", (code) => { + if (code !== 0) { + handleErrorAndReject(code, stderr, "process_error"); + } else { + resolve(); + } + }); + }); + } catch (e) { + sdkInstallSpinner.stop("Installation failed."); + clack.log.error( + `${chalk.red( + "Encountered the following error during installation:", + )}\n\n${String(e)}\n\n${chalk.dim( + "The wizard has created a `sentry-wizard-installation-error-*.log` file. Review it for sensitive information before sharing it. If you think this issue is caused by the Sentry wizard, create an issue on GitHub and include the redacted log file's content:\nhttps://github.com/getsentry/toolkit/issues", + )}`, + ); + await abort(); + } + + sdkInstallSpinner.stop( + `${alreadyInstalled ? "Updated" : "Installed"} ${chalk.bold.cyan( + packageNameDisplayLabel ?? packageName, + )} with ${chalk.bold(pkgManager.label)}.`, + ); + + return { packageManager: pkgManager }; + }); +} + +export async function addSentryCliConfig( + { authToken, org, project, url }: CliSetupConfigContent, + setupConfig: CliSetupConfig = rcCliSetupConfig, +): Promise { + return await traceStep("add-sentry-cli-config", async () => { + const configPath = join(process.cwd(), setupConfig.filename); + const configExists = existsSync(configPath); + + let configContents = + (configExists && readFileSync(configPath, "utf8")) || ""; + configContents = addAuthTokenToSentryConfig( + configContents, + authToken, + setupConfig, + ); + configContents = addOrgAndProjectToSentryConfig( + configContents, + org, + project, + setupConfig, + ); + configContents = addUrlToSentryConfig(configContents, url, setupConfig); + + try { + await promises.writeFile(configPath, configContents, { + encoding: "utf8", + flag: "w", + }); + clack.log.success( + `${configExists ? "Saved" : "Created"} ${chalk.cyan( + setupConfig.filename, + )}.`, + ); + } catch { + clack.log.warning( + `Failed to add auth token to ${chalk.cyan( + setupConfig.filename, + )}. Uploading ${ + setupConfig.name + } during build will likely not work locally.`, + ); + } + + if (setupConfig.gitignore) { + await addCliConfigFileToGitIgnore(setupConfig.filename); + } else { + clack.log.warn( + chalk.yellow("DO NOT commit auth token to your repository!"), + ); + } + }); +} + +function addAuthTokenToSentryConfig( + configContents: string, + authToken: string | undefined, + setupConfig: CliSetupConfig, +): string { + if (!authToken) { + return configContents; + } + + if (setupConfig.likelyAlreadyHasAuthToken(configContents)) { + clack.log.warn( + `${chalk.cyan( + setupConfig.filename, + )} already has auth token. Will not add one.`, + ); + return configContents; + } + + const newContents = `${configContents}\n${setupConfig.tokenContent( + authToken, + )}\n`; + clack.log.success( + `Added auth token to ${chalk.cyan( + setupConfig.filename, + )} for you to test uploading ${setupConfig.name} locally.`, + ); + return newContents; +} + +function addOrgAndProjectToSentryConfig( + configContents: string, + org: string | undefined, + project: string | undefined, + setupConfig: CliSetupConfig, +): string { + if (!org || !project) { + return configContents; + } + + if (setupConfig.likelyAlreadyHasOrgAndProject(configContents)) { + clack.log.warn( + `${chalk.cyan( + setupConfig.filename, + )} already has org and project. Will not add them.`, + ); + return configContents; + } + + const newContents = `${configContents}\n${setupConfig.orgAndProjContent( + org, + project, + )}\n`; + clack.log.success( + `Added default org and project to ${chalk.cyan( + setupConfig.filename, + )} for you to test uploading ${setupConfig.name} locally.`, + ); + return newContents; +} + +function addUrlToSentryConfig( + configContents: string, + url: string | undefined, + setupConfig: CliSetupConfig, +): string { + if (!url || !setupConfig.urlContent || !setupConfig.likelyAlreadyHasUrl) { + return configContents; + } + + if (setupConfig.likelyAlreadyHasUrl(configContents)) { + clack.log.warn( + `${chalk.cyan(setupConfig.filename)} already has url. Will not add one.`, + ); + return configContents; + } + + const newContents = `${configContents}\n${setupConfig.urlContent(url)}\n`; + clack.log.success( + `Added default url to ${chalk.cyan( + setupConfig.filename, + )} for you to test uploading ${setupConfig.name} locally.`, + ); + return newContents; +} + +export async function addDotEnvSentryBuildPluginFile( + authToken: string, +): Promise { + const envVarContent = `# DO NOT commit this file to your repository! +# The SENTRY_AUTH_TOKEN variable is picked up by the Sentry Build Plugin. +# It's used for authentication when uploading source maps. +# You can also set this env variable in your own \`.env\` files and remove this file. +SENTRY_AUTH_TOKEN=${authToken} +`; + + const dotEnvFilePath = join(process.cwd(), SENTRY_DOT_ENV_FILE); + const dotEnvFileExists = existsSync(dotEnvFilePath); + + if (dotEnvFileExists) { + const dotEnvFileContent = readFileSync(dotEnvFilePath, "utf8"); + + const hasAuthToken = !!dotEnvFileContent.match( + /^\s*SENTRY_AUTH_TOKEN\s*=/g, + ); + + if (hasAuthToken) { + clack.log.warn( + `${chalk.bold.cyan( + SENTRY_DOT_ENV_FILE, + )} already has auth token. Will not add one.`, + ); + } else { + try { + await promises.writeFile( + dotEnvFilePath, + `${dotEnvFileContent}\n${envVarContent}`, + { + encoding: "utf8", + flag: "w", + }, + ); + clack.log.success( + `Added auth token to ${chalk.bold.cyan(SENTRY_DOT_ENV_FILE)}`, + ); + } catch { + clack.log.warning( + `Failed to add auth token to ${chalk.bold.cyan( + SENTRY_DOT_ENV_FILE, + )}. Uploading source maps during build will likely not work locally.`, + ); + } + } + } else { + try { + await promises.writeFile(dotEnvFilePath, envVarContent, { + encoding: "utf8", + flag: "w", + }); + clack.log.success( + `Created ${chalk.bold.cyan( + SENTRY_DOT_ENV_FILE, + )} with auth token for you to test source map uploading locally.`, + ); + } catch { + clack.log.warning( + `Failed to create ${chalk.bold.cyan( + SENTRY_DOT_ENV_FILE, + )} with auth token. Uploading source maps during build will likely not work locally.`, + ); + } + } + + await addCliConfigFileToGitIgnore(SENTRY_DOT_ENV_FILE); +} + +async function addCliConfigFileToGitIgnore(filename: string): Promise { + const gitignorePath = join(process.cwd(), ".gitignore"); + + try { + const gitignoreContent = await promises.readFile(gitignorePath, "utf8"); + if (gitignoreContent.split(/\r?\n/).includes(filename)) { + clack.log.info( + `${chalk.bold(".gitignore")} already has ${chalk.bold( + filename, + )}. Will not add it again.`, + ); + return; + } + + await promises.appendFile( + gitignorePath, + `\n# Sentry Config File\n${filename}\n`, + { encoding: "utf8" }, + ); + clack.log.success( + `Added ${chalk.cyan(filename)} to ${chalk.cyan(".gitignore")}.`, + ); + } catch { + clack.log.error( + `Failed adding ${chalk.cyan(filename)} to ${chalk.cyan( + ".gitignore", + )}. Please add it manually!`, + ); + } +} + +/** + * Returns the changed or untracked files for the formatter step, or null if not + * in a git repo or nothing changed. + */ +function getFormatterTargetFiles(): string[] | null { + if (!isInGitRepo({ cwd: undefined })) { + return null; + } + + const changedOrUntrackedFiles = + getUncommittedOrUntrackedFilePaths().filter(Boolean); + + return changedOrUntrackedFiles.length ? changedOrUntrackedFiles : null; +} + +/** Resolves a package's bin entry point from the target project, or null. */ +function resolveFormatterBinary( + packageName: string, + binName: string, +): string | null { + const requireFromProject = createRequire(join(process.cwd(), "package.json")); + + const packageJsonCandidates: string[] = []; + try { + packageJsonCandidates.push( + requireFromProject.resolve(`${packageName}/package.json`), + ); + } catch (error) { + debug(error); + // Package may not expose package.json via exports; fall through. + } + packageJsonCandidates.push( + join(process.cwd(), "node_modules", packageName, "package.json"), + ); + + for (const packageJsonPath of packageJsonCandidates) { + try { + const pkg = JSON.parse(readFileSync(packageJsonPath, "utf8")) as { + bin?: string | Record | undefined; + }; + const relativeBin = + typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.[binName]; + if (relativeBin) { + return join(dirname(packageJsonPath), relativeBin); + } + } catch (error) { + debug(error); + // Try the next candidate. + } + } + + return null; +} + +/** + * Runs a formatter without passing file names through a shell (command + * injection) and with a `--` separator (option injection). POSIX runs `npx` + * directly; Windows resolves the bin and runs it via Node, since `npx.cmd` + * would otherwise need a shell. + * + * @param packageName The npm package that provides the formatter. + * @param binName The bin entry to run from that package (Windows only). + * @param subArgs The formatter flags and subcommands. + * @param files The file paths to format. + * @param options.ignoreExitCode When true, a non-zero exit or unresolved binary resolves instead of rejecting. + */ +function runFormatterCommand( + packageName: string, + binName: string, + subArgs: string[], + files: string[], + { ignoreExitCode }: { ignoreExitCode: boolean }, +): Promise { + let command: string; + let args: string[]; + + if (process.platform === "win32") { + const binPath = resolveFormatterBinary(packageName, binName); + if (!binPath) { + return ignoreExitCode + ? Promise.resolve() + : Promise.reject( + new Error(`Could not resolve the ${packageName} binary.`), + ); + } + command = process.execPath; + args = [binPath, ...subArgs, "--", ...files]; + } else { + command = "npx"; + args = [packageName, ...subArgs, "--", ...files]; + } + + return new Promise((resolve, reject) => { + const child = spawn(command, args, { + shell: false, + stdio: "ignore", + }); + + child.on("error", (err) => { + if (ignoreExitCode) { + resolve(); + } else { + reject(err); + } + }); + + child.on("close", (code) => { + if (code !== 0 && !ignoreExitCode) { + reject(new Error(`Formatter exited with code ${code ?? "null"}.`)); + } else { + resolve(); + } + }); + }); +} + +/** + * Runs available formatters (Prettier and/or Biome) on the changed or untracked files in the project. + * This function provides a unified interface for running multiple formatters with a single user prompt. + * + * @param _opts The directory of the project. If undefined, the current process working directory will be used. + */ +export async function runFormatters(_opts: { + cwd: string | undefined; +}): Promise { + return await traceStep("run-formatters", async () => { + const targetFiles = getFormatterTargetFiles(); + if (!targetFiles) { + return; + } + + const packageJson = await getPackageDotJson(); + const prettierInstalled = hasPackageInstalled("prettier", packageJson); + const biomeInstalled = hasPackageInstalled("@biomejs/biome", packageJson); + + Sentry.setTag("prettier-installed", prettierInstalled); + Sentry.setTag("biome-installed", biomeInstalled); + + if (!prettierInstalled && !biomeInstalled) { + return; + } + + // Determine prompt message based on what's installed + const formattersAvailable = []; + if (prettierInstalled) formattersAvailable.push("Prettier"); + if (biomeInstalled) formattersAvailable.push("Biome"); + + const message = + formattersAvailable.length === 1 + ? `Looks like you have ${formattersAvailable[0]} in your project. Do you want to run it on your files?` + : `Looks like you have ${formattersAvailable.join( + " and ", + )} in your project. Do you want to run them on your files?`; + + const shouldRun = await abortIfCancelled(clack.confirm({ message })); + + if (!shouldRun) { + return; + } + + const spinner = clack.spinner(); + spinner.start("Running formatters on your files."); + + try { + // Run Prettier first if installed (handles general formatting) + if (prettierInstalled) { + await runFormatterCommand( + "prettier", + "prettier", + ["--ignore-unknown", "--write"], + targetFiles, + { ignoreExitCode: false }, + ); + } + + // Run Biome if installed (handles linting + additional formatting) + if (biomeInstalled) { + // Format first + await runFormatterCommand( + "@biomejs/biome", + "biome", + ["format", "--write"], + targetFiles, + // Ignore errors, just continue + { ignoreExitCode: true }, + ); + + // Then lint with fixes (using --unsafe for auto-fixable issues) + // See: https://biomejs.dev/linter/#unsafe-fixes + // The --unsafe flag applies potentially behavior-changing fixes like removing unused imports. + // This is acceptable for wizard-generated code which may have fixable issues. + await runFormatterCommand( + "@biomejs/biome", + "biome", + ["check", "--write", "--unsafe"], + targetFiles, + // Ignore errors, Biome exits non-zero if there are remaining issues + { ignoreExitCode: true }, + ); + } + + spinner.stop("Formatters have processed your files."); + } catch (e) { + spinner.stop("Formatting encountered an issue."); + clack.log.warn( + "Formatting encountered an issue. There may be formatting or linting issues in your updated files.", + ); + } + }); +} + +/** + * Runs prettier on the changed or untracked files in the project. + * + * @param options.cwd The directory of the project. If undefined, the current process working directory will be used. + */ +export async function runPrettierIfInstalled(_opts: { + cwd: string | undefined; +}): Promise { + return await traceStep("run-prettier", async () => { + const changedOrUntrackedFiles = getFormatterTargetFiles(); + if (!changedOrUntrackedFiles) { + return; + } + + const packageJson = await getPackageDotJson(); + const prettierInstalled = hasPackageInstalled("prettier", packageJson); + + Sentry.setTag("prettier-installed", prettierInstalled); + + if (!prettierInstalled) { + return; + } + + // prompt the user if they want to run prettier + const shouldRunPrettier = await abortIfCancelled( + clack.confirm({ + message: + "Looks like you have Prettier in your project. Do you want to run it on your files?", + }), + ); + + if (!shouldRunPrettier) { + return; + } + + const prettierSpinner = clack.spinner(); + prettierSpinner.start("Running Prettier on your files."); + + try { + await runFormatterCommand( + "prettier", + "prettier", + ["--ignore-unknown", "--write"], + changedOrUntrackedFiles, + { ignoreExitCode: false }, + ); + } catch (e) { + prettierSpinner.stop("Prettier failed to run."); + clack.log.warn( + "Prettier failed to run. There may be formatting issues in your updated files.", + ); + return; + } + + prettierSpinner.stop("Prettier has formatted your files."); + }); +} + +/** + * Runs Biome on the changed or untracked files in the project. + * + * @param options.cwd The directory of the project. If undefined, the current process working directory will be used. + */ +export async function runBiomeIfInstalled(_opts: { + cwd: string | undefined; +}): Promise { + return await traceStep("run-biome", async () => { + const changedOrUntrackedFiles = getFormatterTargetFiles(); + if (!changedOrUntrackedFiles) { + return; + } + + const packageJson = await getPackageDotJson(); + const biomeInstalled = hasPackageInstalled("@biomejs/biome", packageJson); + + Sentry.setTag("biome-installed", biomeInstalled); + + if (!biomeInstalled) { + return; + } + + // prompt the user if they want to run biome + const shouldRunBiome = await abortIfCancelled( + clack.confirm({ + message: + "Looks like you have Biome in your project. Do you want to run it on your files?", + }), + ); + + if (!shouldRunBiome) { + return; + } + + const biomeSpinner = clack.spinner(); + biomeSpinner.start("Running Biome on your files."); + + try { + // Use biome format --write for formatting (always succeeds if it can format) + // Then biome check --write for lint fixes + // We ignore exit codes because Biome exits non-zero if there are unfixable issues + await runFormatterCommand( + "@biomejs/biome", + "biome", + ["format", "--write"], + changedOrUntrackedFiles, + // Ignore errors, just continue + { ignoreExitCode: true }, + ); + + await runFormatterCommand( + "@biomejs/biome", + "biome", + ["check", "--write", "--unsafe"], + changedOrUntrackedFiles, + // Ignore errors, Biome exits non-zero if there are remaining issues + { ignoreExitCode: true }, + ); + } catch (e) { + biomeSpinner.stop("Biome encountered an issue."); + clack.log.warn( + "Biome encountered an issue. There may be formatting or linting issues in your updated files.", + ); + return; + } + + biomeSpinner.stop("Biome has formatted your files."); + }); +} + +/** + * Checks if @param packageId is listed as a dependency in @param packageJson. + * If not, it will ask users if they want to continue without the package. + * + * Use this function to check if e.g. a the framework of the SDK is installed + * + * @param packageJson the package.json object + * @param packageId the npm name of the package + * @param packageName a human readable name of the package + */ +export async function ensurePackageIsInstalled( + packageJson: PackageDotJson, + packageId: string, + packageName: string, +): Promise { + return await traceStep("ensure-package-installed", async () => { + const installed = hasPackageInstalled(packageId, packageJson); + + Sentry.setTag(`${packageName.toLowerCase()}-installed`, installed); + + if (!installed) { + Sentry.setTag(`${packageName.toLowerCase()}-installed`, false); + const continueWithoutPackage = await abortIfCancelled( + clack.confirm({ + message: `${packageName} does not seem to be installed. Do you still want to continue?`, + initialValue: false, + }), + ); + + if (!continueWithoutPackage) { + await abort(undefined, 0); + } + } + }); +} + +export async function getPackageDotJson(): Promise { + const packageJsonFileContents = await promises + .readFile(join(process.cwd(), "package.json"), "utf8") + .catch(() => { + clack.log.error( + "Could not find package.json. Make sure to run the wizard in the root of your app!", + ); + return abort(); + }); + + let packageJson: PackageDotJson | undefined = undefined; + + try { + packageJson = JSON.parse(packageJsonFileContents); + } catch { + clack.log.error( + `Unable to parse your ${chalk.cyan( + "package.json", + )}. Make sure it has a valid format!`, + ); + + await abort(); + } + + return packageJson || {}; +} + +export async function updatePackageDotJson( + packageDotJson: PackageDotJson, +): Promise { + try { + await promises.writeFile( + join(process.cwd(), "package.json"), + // TODO: maybe figure out the original indentation + JSON.stringify(packageDotJson, null, 2), + { + encoding: "utf8", + flag: "w", + }, + ); + } catch { + clack.log.error(`Unable to update your ${chalk.cyan("package.json")}.`); + + await abort(); + } +} + +/** + * Use this function to get the used JS Package manager. + * + * This function: + * - attempts to auto-detect the used package manager and return it + * - if unsuccessful, returns the passed fallback package manager + * - if no fallback is passed, it asks the user to select a package manager + * + * The result is cached on the first invocation to avoid asking the user multiple times. + * + * @param fallback the package manager to use if auto-detection fails and you don't want to + * ask the user. This is useful in cases where asking users would be too intrusive/low in value + * and where it's okay to fall back to a default package manager. Use this with caution. + */ +export async function getPackageManager( + fallback?: PackageManager, +): Promise { + const globalWithSentryWizard: typeof global & { + __sentry_wizard_cached_package_manager?: PackageManager | undefined; + } = global; + + if (globalWithSentryWizard.__sentry_wizard_cached_package_manager) { + return globalWithSentryWizard.__sentry_wizard_cached_package_manager; + } + + const detectedPackageManager = _detectPackageManger(); + + if (detectedPackageManager) { + globalWithSentryWizard.__sentry_wizard_cached_package_manager = + detectedPackageManager; + return detectedPackageManager; + } + + if (fallback) { + // explicitly avoiding to cache the fallback in case this function + // gets called again without a fallback (or a different fallback) + // later on in the wizard flow. + return fallback; + } + + const selectedPackageManager: PackageManager | symbol = + await abortIfCancelled( + clack.select({ + message: "Please select your package manager.", + options: packageManagers.map((packageManager) => ({ + value: packageManager, + label: packageManager.label, + })), + }), + ); + + globalWithSentryWizard.__sentry_wizard_cached_package_manager = + selectedPackageManager; + + Sentry.setTag("package-manager", selectedPackageManager.name); + + return selectedPackageManager; +} + +export function isUsingTypeScript() { + try { + return existsSync(join(process.cwd(), "tsconfig.json")); + } catch (error) { + debug(error); + return false; + } +} + +/** + * Asks users if they have a config file for @param tool (e.g. Vite). + * If yes, asks users to specify the path to their config file. + * + * Use this helper function as a fallback mechanism if the lookup for + * a config file with its most usual location/name fails. + * + * @param toolName Name of the tool for which we're looking for the config file + * @param configFileName Name of the most common config file name (e.g. vite.config.js) + * + * @returns a user path to the config file or undefined if the user doesn't have a config file + */ +export async function askForToolConfigPath( + toolName: string, + configFileName: string, +): Promise { + const hasConfig = await abortIfCancelled( + clack.confirm({ + message: `Do you have a ${toolName} config file (e.g. ${chalk.cyan( + configFileName, + )})?`, + initialValue: true, + }), + ); + + if (!hasConfig) { + return undefined; + } + + return await abortIfCancelled( + clack.text({ + message: `Please enter the path to your ${toolName} config file:`, + placeholder: join(".", configFileName), + validate: (value) => { + if (!value) { + return "Please enter a path."; + } + + try { + accessSync(value); + } catch (error) { + debug(error); + return "Could not access the file at this path."; + } + return undefined; + }, + }), + ); +} + +type ShowCopyPasteInstructionsOptions = { codeSnippet: string } & ( + | { + filename: string; + hint?: string | undefined; + } + | { + instructions: string; + } +); + +/** + * Prints copy/paste-able instructions to the console. + * Afterwards asks the user if they added the code snippet to their file. + * + * While there's no point in providing a "no" answer here, it gives users time to fulfill the + * task before the wizard continues with additional steps. + * + * Use this function if you want to show users instructions on how to add/modify + * code in their file. This is helpful if automatic insertion failed or is not possible/feasible. + * + * @param filename the name of the file to which the code snippet should be applied. + * If a path is provided, only the filename will be used. + * + * @param codeSnippet the snippet to be printed. Use {@link makeCodeSnippet} to create the + * diff-like format for visually highlighting unchanged or modified lines of code. + * + * @param hint (optional) a hint to be printed after the main instruction to add + * the code from @param codeSnippet to their @param filename. + * + * More guidelines on copy/paste instructions: + * @see {@link https://develop.sentry.dev/sdk/setup-wizards/#copy--paste-snippets} + * + * TODO: refactor copy paste instructions across different wizards to use this function. + * this might require adding a custom message parameter to the function + */ +export async function showCopyPasteInstructions( + opts: ShowCopyPasteInstructionsOptions, +): Promise { + if ("instructions" in opts) { + clack.log.step(opts.instructions); + } else { + const defaultInstructions = `Add the following code to your ${chalk.cyan( + basename(opts.filename), + )} file:${opts.hint ? chalk.dim(` (${chalk.dim(opts.hint)})`) : ""}`; + + clack.log.step(defaultInstructions); + } + + // Padding the code snippet to be printed with a \n at the beginning and end + // This makes it easier to distinguish the snippet from the rest of the output + // Printed outside clack's gutter so that the code can be copied/pasted directly + clack.rawOutput(`\n${opts.codeSnippet}\n`); + + await abortIfCancelled( + clack.select({ + message: "Did you apply the snippet above?", + options: [{ label: "Yes, continue!", value: true }], + initialValue: true, + }), + ); +} + +/** + * Callback that exposes formatting helpers for a code snippet. + * @param unchanged - Formats text as old code. + * @param plus - Formats text as new code. + * @param minus - Formats text as removed code. + */ +type CodeSnippetFormatter = ( + unchanged: (txt: string) => string, + plus: (txt: string) => string, + minus: (txt: string) => string, +) => string; + +/** + * Crafts a code snippet that can be used to e.g. + * - print copy/paste instructions to the console + * - create a new config file. + * + * @param colors set this to true if you want the final snippet to be colored. + * This is useful for printing the snippet to the console as part of copy/paste instructions. + * + * @param callback the callback that returns the formatted code snippet. + * It exposes takes the helper functions for marking code as unchanged, new or removed. + * These functions no-op if no special formatting should be applied + * and otherwise apply the appropriate formatting/coloring. + * (@see {@link CodeSnippetFormatter}) + * + * @see {@link showCopyPasteInstructions} for the helper with which to display the snippet in the console. + * + * @returns a string containing the final, formatted code snippet. + */ +export function makeCodeSnippet( + colors: boolean, + callback: CodeSnippetFormatter, +): string { + const unchanged = (txt: string) => (colors ? chalk.grey(txt) : txt); + const plus = (txt: string) => (colors ? chalk.greenBright(txt) : txt); + const minus = (txt: string) => (colors ? chalk.redBright(txt) : txt); + + return callback(unchanged, plus, minus); +} + +/** + * Creates a new config file with the given @param filepath and @param codeSnippet. + * + * Use this function to create a new config file for users. This is useful + * when users answered that they don't yet have a config file for a tool. + * + * (This doesn't mean that they don't yet have some other way of configuring + * their tool but we can leave it up to them to figure out how to merge configs + * here.) + * + * @param filepath absolute path to the new config file + * @param codeSnippet the snippet to be inserted into the file + * @param moreInformation (optional) the message to be printed after the file was created + * For example, this can be a link to more information about configuring the tool. + * + * @returns true on success, false otherwise + */ +export async function createNewConfigFile( + filepath: string, + codeSnippet: string, + moreInformation?: string, +): Promise { + if (!isAbsolute(filepath)) { + debug(`createNewConfigFile: filepath is not absolute: ${filepath}`); + return false; + } + + const prettyFilename = chalk.cyan(relative(process.cwd(), filepath)); + + try { + await promises.writeFile(filepath, codeSnippet); + + clack.log.success(`Added new ${prettyFilename} file.`); + + if (moreInformation) { + clack.log.info(chalk.gray(moreInformation)); + } + + return true; + } catch (e) { + debug(e); + clack.log.warn( + `Could not create a new ${prettyFilename} file. Please create one manually and follow the instructions below.`, + ); + } + + return false; +} + +export async function askShouldCreateExamplePage( + customRoute?: string, +): Promise { + const route = chalk.cyan(customRoute ?? "/sentry-example-page"); + + const createExamplePage = await traceStep("ask-create-example-page", () => + abortIfCancelled( + clack.select({ + message: `Do you want to create an example page ("${route}") to test your Sentry setup?`, + initialValue: true, + options: [ + { + value: true, + label: "Yes", + hint: "Recommended - Check your git status before committing!", + }, + { value: false, label: "No" }, + ], + }), + ), + ); + + Sentry.setTag("create-example-page", createExamplePage); + return createExamplePage; +} + +export async function askShouldCreateExampleComponent(): Promise { + return await traceStep("ask-create-example-component", () => + abortIfCancelled( + clack.select({ + message: `Do you want to create an example component to test your Sentry setup?`, + options: [ + { + value: true, + label: "Yes", + hint: "Recommended - Check your git status before committing!", + }, + { value: false, label: "No" }, + ], + }), + ), + ); +} + +export async function featureSelectionPrompt>( + features: F, +): Promise> { + return await traceStep("feature-selection", async () => { + const selectedFeatures: Record = {}; + + for (const feature of features) { + const selected = await abortIfCancelled( + clack.select({ + message: feature.prompt, + initialValue: true, + options: [ + { + value: true, + label: "Yes", + ...(feature.enabledHint ? { hint: feature.enabledHint } : {}), + }, + { + value: false, + label: "No", + ...(feature.disabledHint ? { hint: feature.disabledHint } : {}), + }, + ], + }), + ); + + selectedFeatures[feature.id] = selected; + } + + return selectedFeatures; + }); +} + +export async function askShouldInstallPackage( + pkgName: string, +): Promise { + return await traceStep(`ask-install-package`, () => + abortIfCancelled( + clack.confirm({ + message: `Do you want to install ${chalk.cyan(pkgName)}?`, + }), + ), + ); +} + +export async function askShouldAddPackageOverride( + pkgName: string, + pkgVersion: string, +): Promise { + return await traceStep(`ask-add-package-override`, () => + abortIfCancelled( + clack.confirm({ + message: `Do you want to add an override for ${chalk.cyan( + pkgName, + )} version ${chalk.cyan(pkgVersion)}?`, + }), + ), + ); +} + +async function getBuildCommand(): Promise { + const packageDotJson = await getPackageDotJson(); + return typeof packageDotJson.scripts?.["build"] === "string" ? "build" : null; +} + +export function artifactsExist(relativePath: string): boolean { + return existsSync(path.join(process.cwd(), relativePath)); +} + +export async function askToRunBuildOrEnterPathOrProceed({ + relativeArtifactPath, +}: { + relativeArtifactPath: string; +}): Promise<{ validPath: boolean; relativeArtifactPath?: string }> { + const options: { label: string; value: string }[] = []; + + const buildCommand = await getBuildCommand(); + + if (buildCommand) { + options.push({ + label: "Let the wizard run the build command", + value: "run-build", + }); + } + + options.push( + { + label: "Enter a different path manually", + value: "manual", + }, + { + label: "Proceed anyway — I believe the path is correct", + value: "proceed", + }, + ); + + const whatToDo = await abortIfCancelled( + clack.select({ + message: `We couldn't find build artifacts at "${relativeArtifactPath}". What would you like to do?`, + options, + initialValue: buildCommand ? "run-build" : "manual", + }), + ); + + if (whatToDo === "proceed") { + return { + validPath: true, + }; + } + + if (whatToDo === "run-build" && buildCommand) { + const ranBuildAndCheckArtifacts = await runBuildAndCheckArtifacts( + buildCommand, + relativeArtifactPath, + ); + + if (!ranBuildAndCheckArtifacts.validPath) { + return await askToRunBuildOrEnterPathOrProceed({ relativeArtifactPath }); + } + + return ranBuildAndCheckArtifacts; + } + + return { + validPath: false, + }; +} + +function getPossibleBuildFolders(): string[] { + const commonBuildFolders = ["build", "dist", "out", ".next"]; + + return commonBuildFolders.filter((folder) => + existsSync(path.join(process.cwd(), folder)), + ); +} + +async function promptForAlternativeArtifactPath(): Promise { + const folders = getPossibleBuildFolders(); + + if (!folders.length) { + return undefined; + } + + if (folders.length === 1) { + const [onlyFolder] = folders; + + const confirmed = await abortIfCancelled( + clack.select({ + message: `Detected one possible build folder. Use "${onlyFolder}" as your build artifacts folder?`, + options: [ + { + value: true, + label: "Yes", + }, + { value: false, label: "No" }, + ], + }), + ); + + return confirmed ? onlyFolder : undefined; + } + + const selected = await abortIfCancelled( + clack.select({ + message: `Detected multiple possible build folders. Is one of these your build artifacts folder?`, + options: [ + ...folders.map((f) => ({ value: f, label: f })), + { value: false, label: "No" }, + ], + }), + ); + + if (selected) { + return String(selected); + } + + return undefined; +} + +async function runBuildCommand(buildCommand: string): Promise { + const packageManager = await getPackageManager(NPM); + const command = `${packageManager.runScriptCommand} ${buildCommand}`; + const spinner = clack.spinner(); + + spinner.start(`Running ${chalk.cyan(command)}...`); + try { + execSync(command, { + stdio: "inherit", + cwd: process.cwd(), + }); + spinner.stop("Build finished running."); + return true; + } catch (error) { + spinner.stop( + `Build failed: ${error instanceof Error ? error.message : String(error)}`, + ); + clack.log.error( + "Failed to run your build command. Please run it manually and try again.", + ); + return false; + } +} + +async function runBuildAndCheckArtifacts( + buildCommand: string, + relativeArtifactPath: string, +): Promise<{ validPath: boolean; relativeArtifactPath?: string }> { + const buildRan = await runBuildCommand(buildCommand); + + if (!buildRan) { + return { validPath: false }; + } + + const found = artifactsExist(relativeArtifactPath); + + if (found) { + clack.log.success("Build completed and build artifacts folder found!"); + return { validPath: true }; + } + + clack.log.warn( + `Build ran, but build artifacts folder still not found at ${relativeArtifactPath}.`, + ); + + const fallbackPath = await promptForAlternativeArtifactPath(); + + if (!fallbackPath) { + return { validPath: false }; + } + + return { + validPath: artifactsExist(fallbackPath), + relativeArtifactPath: fallbackPath, + }; +} diff --git a/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts b/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts new file mode 100644 index 0000000000..867c9c0140 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts @@ -0,0 +1,639 @@ +/** + * Offer to add a project-scoped Sentry MCP server to the user's editors + * (Cursor, VS Code, Claude Code) at the end of a wizard run. + */ + +import { mkdirSync, promises } from "node:fs"; +import path from "node:path"; +import { spawn } from "node:child_process"; +import { Sentry } from "../../telemetry.js"; +import chalk from "chalk"; +import { clack } from "./prompts.js"; +import { abortIfCancelled, showCopyPasteInstructions } from "./index.js"; +import { debug } from "../debug.js"; + +const SENTRY_MCP_BASE_URL = "https://mcp.sentry.dev/mcp"; + +// Type definitions for MCP configurations +interface CursorMcpConfig { + mcpServers?: Record | undefined; +} + +interface VsCodeMcpConfig { + servers?: Record | undefined; +} + +interface ClaudeCodeMcpConfig { + mcpServers?: Record | undefined; +} + +interface OpenCodeMcpConfig { + $schema?: string | undefined; + mcp?: + | Record + | undefined; +} + +/** + * Constructs the MCP URL with optional org and project slugs + */ +function getMcpUrl(orgSlug?: string, projectSlug?: string): string { + if (orgSlug && projectSlug) { + return `${SENTRY_MCP_BASE_URL}/${orgSlug}/${projectSlug}`; + } + return SENTRY_MCP_BASE_URL; +} + +function ensureDir(dirpath: string): void { + mkdirSync(dirpath, { recursive: true }); +} + +async function readJsonIfExists(filepath: string): Promise { + try { + const txt = await promises.readFile(filepath, "utf8"); + return JSON.parse(txt) as unknown; + } catch (error) { + debug(error); + return null; + } +} + +async function writeJson(filepath: string, obj: unknown): Promise { + ensureDir(path.dirname(filepath)); + await promises.writeFile(filepath, JSON.stringify(obj, null, 2), "utf8"); +} + +function getCursorMcpJsonSnippet( + orgSlug?: string, + projectSlug?: string, +): string { + const obj = { + mcpServers: { + Sentry: { + url: getMcpUrl(orgSlug, projectSlug), + }, + }, + } as const; + return JSON.stringify(obj, null, 2); +} + +function getVsCodeMcpJsonSnippet( + orgSlug?: string, + projectSlug?: string, +): string { + const obj = { + servers: { + Sentry: { + url: getMcpUrl(orgSlug, projectSlug), + type: "http", + }, + }, + } as const; + return JSON.stringify(obj, null, 2); +} + +function getClaudeCodeMcpJsonSnippet( + orgSlug?: string, + projectSlug?: string, +): string { + const obj = { + mcpServers: { + Sentry: { + url: getMcpUrl(orgSlug, projectSlug), + }, + }, + } as const; + return JSON.stringify(obj, null, 2); +} + +function getJetBrainsMcpJsonSnippet( + orgSlug?: string, + projectSlug?: string, +): string { + const obj = { + mcpServers: { + Sentry: { + url: getMcpUrl(orgSlug, projectSlug), + }, + }, + } as const; + return JSON.stringify(obj, null, 2); +} + +function getOpenCodeMcpJsonSnippet( + orgSlug?: string, + projectSlug?: string, +): string { + const obj = { + $schema: "https://opencode.ai/config.json", + mcp: { + Sentry: { + type: "remote", + url: getMcpUrl(orgSlug, projectSlug), + oauth: {}, + }, + }, + } as const; + return JSON.stringify(obj, null, 2); +} + +function getGenericMcpJsonSnippet( + orgSlug?: string, + projectSlug?: string, +): string { + const obj = { + mcpServers: { + Sentry: { + url: getMcpUrl(orgSlug, projectSlug), + }, + }, + } as const; + return JSON.stringify(obj, null, 2); +} + +async function addCursorMcpConfig( + orgSlug?: string, + projectSlug?: string, +): Promise { + const file = path.join(process.cwd(), ".cursor", "mcp.json"); + const existing = await readJsonIfExists(file); + if (!existing) { + await writeJson( + file, + JSON.parse(getCursorMcpJsonSnippet(orgSlug, projectSlug)), + ); + clack.log.success( + chalk.cyan(path.join(".cursor", "mcp.json")) + " created.", + ); + return; + } + try { + const updated = { ...existing } as CursorMcpConfig; + updated.mcpServers = updated.mcpServers || {}; + updated.mcpServers["Sentry"] = { + url: getMcpUrl(orgSlug, projectSlug), + }; + await writeJson(file, updated); + clack.log.success("Updated .cursor/mcp.json"); + } catch { + throw new Error("Failed to update .cursor/mcp.json"); + } +} + +async function addVsCodeMcpConfig( + orgSlug?: string, + projectSlug?: string, +): Promise { + const file = path.join(process.cwd(), ".vscode", "mcp.json"); + const existing = await readJsonIfExists(file); + if (!existing) { + await writeJson( + file, + JSON.parse(getVsCodeMcpJsonSnippet(orgSlug, projectSlug)), + ); + clack.log.success( + chalk.cyan(path.join(".vscode", "mcp.json")) + " created.", + ); + return; + } + try { + const updated = { ...existing } as VsCodeMcpConfig; + updated.servers = updated.servers || {}; + updated.servers["Sentry"] = { + url: getMcpUrl(orgSlug, projectSlug), + type: "http", + }; + await writeJson(file, updated); + clack.log.success("Updated .vscode/mcp.json"); + } catch { + throw new Error("Failed to update .vscode/mcp.json"); + } +} + +async function addClaudeCodeMcpConfig( + orgSlug?: string, + projectSlug?: string, +): Promise { + const file = path.join(process.cwd(), ".mcp.json"); + const existing = await readJsonIfExists(file); + if (!existing) { + await writeJson( + file, + JSON.parse(getClaudeCodeMcpJsonSnippet(orgSlug, projectSlug)), + ); + clack.log.success(chalk.cyan(".mcp.json") + " created."); + return; + } + try { + const updated = { ...existing } as ClaudeCodeMcpConfig; + updated.mcpServers = updated.mcpServers || {}; + updated.mcpServers["Sentry"] = { + url: getMcpUrl(orgSlug, projectSlug), + }; + await writeJson(file, updated); + clack.log.success("Updated .mcp.json"); + } catch { + throw new Error("Failed to update .mcp.json"); + } +} + +async function addOpenCodeMcpConfig( + orgSlug?: string, + projectSlug?: string, +): Promise { + const file = path.join(process.cwd(), "opencode.json"); + const existing = await readJsonIfExists(file); + if (!existing) { + await writeJson( + file, + JSON.parse(getOpenCodeMcpJsonSnippet(orgSlug, projectSlug)), + ); + clack.log.success(chalk.cyan("opencode.json") + " created."); + return; + } + try { + const updated = { ...existing } as OpenCodeMcpConfig; + updated.$schema ||= "https://opencode.ai/config.json"; + updated.mcp = updated.mcp || {}; + updated.mcp["Sentry"] = { + type: "remote", + url: getMcpUrl(orgSlug, projectSlug), + oauth: {}, + }; + await writeJson(file, updated); + clack.log.success("Updated opencode.json"); + } catch { + throw new Error("Failed to update opencode.json"); + } +} + +/** + * Copies text to clipboard across different platforms + */ +async function copyToClipboard(text: string): Promise { + try { + const platform = process.platform; + let command: string; + + if (platform === "darwin") { + command = "pbcopy"; + } else if (platform === "win32") { + command = "clip"; + } else { + // Linux + command = "xclip -selection clipboard"; + } + + const proc = spawn(command, [], { shell: true }); + proc.stdin.write(text); + proc.stdin.end(); + + return await new Promise((resolve) => { + proc.on("close", (code) => { + resolve(code === 0); + }); + proc.on("error", () => { + resolve(false); + }); + }); + } catch (error) { + debug(error); + return false; + } +} + +/** + * Shows MCP configuration for JetBrains IDEs with copy-to-clipboard option + */ +async function showJetBrainsMcpConfig( + orgSlug?: string, + projectSlug?: string, +): Promise { + const configSnippet = getJetBrainsMcpJsonSnippet(orgSlug, projectSlug); + + clack.log.info( + chalk.cyan("For JetBrains IDEs (WebStorm, IntelliJ IDEA, PyCharm, etc.):"), + ); + clack.log.info( + chalk.dim( + "Add the following configuration to your IDE's MCP settings.\n" + + "See: https://www.jetbrains.com/help/webstorm/mcp-server.html", + ), + ); + + // Display the configuration + clack.rawOutput("\n" + chalk.green(configSnippet) + "\n"); + + // Ask if user wants to copy to clipboard + const shouldCopy: boolean = await abortIfCancelled( + clack.select({ + message: "Copy configuration to clipboard?", + options: [ + { label: "Yes", value: true }, + { label: "No", value: false }, + ], + initialValue: true, + }), + ); + + if (shouldCopy) { + const copied = await copyToClipboard(configSnippet); + + if (copied) { + clack.log.success("Configuration copied to clipboard!"); + Sentry.setTag("mcp-clipboard-copy", "success"); + } else { + clack.log.warn( + "Failed to copy to clipboard. Please copy the configuration above manually.", + ); + Sentry.setTag("mcp-clipboard-copy", "failed"); + } + } else { + Sentry.setTag("mcp-clipboard-copy", "declined"); + } + + clack.log.info( + chalk.dim( + "Note: You may need to restart your IDE for MCP changes to take effect.", + ), + ); +} + +/** + * Shows generic MCP configuration for unsupported IDEs with copy-to-clipboard option + */ +async function showGenericMcpConfig( + orgSlug?: string, + projectSlug?: string, +): Promise { + const configSnippet = getGenericMcpJsonSnippet(orgSlug, projectSlug); + + clack.log.info(chalk.cyan("Generic MCP configuration for your IDE:")); + clack.log.info( + chalk.dim( + "If your IDE supports MCP servers, you can use the following configuration.\n" + + "Please consult your IDE's documentation for how to add MCP server configurations.", + ), + ); + + // Display the configuration + clack.rawOutput("\n" + chalk.green(configSnippet) + "\n"); + + // Ask if user wants to copy to clipboard + const shouldCopy: boolean = await abortIfCancelled( + clack.select({ + message: "Copy configuration to clipboard?", + options: [ + { label: "Yes", value: true }, + { label: "No", value: false }, + ], + initialValue: true, + }), + ); + + if (shouldCopy) { + const copied = await copyToClipboard(configSnippet); + + if (copied) { + clack.log.success("Configuration copied to clipboard!"); + Sentry.setTag("mcp-clipboard-copy", "success"); + } else { + clack.log.warn( + "Failed to copy to clipboard. Please copy the configuration above manually.", + ); + Sentry.setTag("mcp-clipboard-copy", "failed"); + } + } else { + Sentry.setTag("mcp-clipboard-copy", "declined"); + } + + clack.log.info( + chalk.dim( + "Note: The exact configuration format may vary depending on your IDE.\n" + + "If your IDE doesn't support MCP yet, please check back later or open an issue at:\n" + + "https://github.com/getsentry/toolkit/issues", + ), + ); +} + +/** + * Explains what MCP is and its benefits for Sentry users + */ +async function explainMCP(): Promise { + clack.log.info(chalk.cyan("What is MCP (Model Context Protocol)?")); + + clack.log.info( + chalk.dim( + "MCP is a protocol that allows AI assistants in your IDE to interact with external tools and services.\n\n" + + "The Sentry MCP server enables AI assistants to:\n" + + " • Query and analyze your Sentry issues directly from your IDE\n" + + " • Get context about errors and performance problems\n" + + " • Help debug issues with production data insights\n" + + " • Suggest fixes based on real error patterns\n\n" + + "This makes it easier to fix bugs by bringing Sentry's insights directly into your development workflow.\n\n" + + "Learn more: " + + chalk.cyan("https://docs.sentry.io/product/sentry-mcp/"), + ), + ); + + // Ask again after explanation + const shouldAddAfterExplanation: boolean = await abortIfCancelled( + clack.select({ + message: "Would you like to configure MCP for your IDE now?", + options: [ + { label: "Yes", value: true }, + { label: "No", value: false, hint: "You can add it later anytime" }, + ], + initialValue: true, + }), + ); + + return shouldAddAfterExplanation; +} + +/** + * Offers to add a project-scoped MCP server configuration for the Sentry MCP. + * Supports Cursor, VS Code, and Claude Code. + * @param orgSlug - Optional organization slug to include in the MCP URL + * @param projectSlug - Optional project slug to include in the MCP URL + */ +export async function offerProjectScopedMcpConfig( + orgSlug?: string, + projectSlug?: string, +): Promise { + type InitialChoice = "yes" | "no" | "explain"; + + const initialChoice: InitialChoice = await abortIfCancelled( + clack.select({ + message: + "Optionally add a project-scoped MCP server configuration for the Sentry MCP?", + options: [ + { label: "Yes", value: "yes" }, + { label: "No", value: "no", hint: "You can add it later anytime" }, + { + label: "What is MCP?", + value: "explain", + hint: "Learn about MCP benefits", + }, + ], + initialValue: "yes", + }), + ); + + let shouldAdd: boolean; + + if (initialChoice === "explain") { + Sentry.setTag("mcp-choice", "explain"); + shouldAdd = await explainMCP(); + Sentry.setTag("mcp-configured-after-explain", shouldAdd); + } else { + shouldAdd = initialChoice === "yes"; + Sentry.setTag("mcp-choice", initialChoice); + } + + if (!shouldAdd) { + Sentry.setTag("mcp-configured", false); + return; + } + + Sentry.setTag("mcp-configured", true); + + type EditorChoice = + | "cursor" + | "vscode" + | "claudeCode" + | "openCode" + | "jetbrains" + | "other"; + const editors: EditorChoice[] = await abortIfCancelled( + clack.multiselect({ + message: "Which editor(s) do you want to configure?", + options: [ + { value: "cursor", label: "Cursor (project .cursor/mcp.json)" }, + { value: "vscode", label: "VS Code (project .vscode/mcp.json)" }, + { value: "claudeCode", label: "Claude Code (project .mcp.json)" }, + { value: "openCode", label: "OpenCode (project opencode.json)" }, + { + value: "jetbrains", + label: "JetBrains IDE (WebStorm, IntelliJ IDEA, PyCharm, etc.)", + hint: "Manual configuration required", + }, + { + value: "other", + label: "I use a different IDE", + hint: "We'll show you the configuration to copy", + }, + ], + required: false, + }), + ); + + // If no editors were selected, return early + if (editors.length === 0) { + clack.log.info("No editors selected. You can add MCP configuration later."); + Sentry.setTag("mcp-configured", false); + return; + } + + // Track number of editors selected + Sentry.setTag("mcp-editors-count", editors.length); + + // Configure each selected editor + for (const editor of editors) { + // Track which editor is being configured + Sentry.setTag("mcp-editor", editor); + + try { + switch (editor) { + case "cursor": + await addCursorMcpConfig(orgSlug, projectSlug); + clack.log.success( + "Added project-scoped Sentry MCP configuration for Cursor.", + ); + clack.log.info( + chalk.dim( + "Note: You may need to reload your editor for MCP changes to take effect.", + ), + ); + break; + case "vscode": + await addVsCodeMcpConfig(orgSlug, projectSlug); + clack.log.success( + "Added project-scoped Sentry MCP configuration for VS Code.", + ); + clack.log.info( + chalk.dim( + "Note: You may need to reload your editor for MCP changes to take effect.", + ), + ); + break; + case "claudeCode": + await addClaudeCodeMcpConfig(orgSlug, projectSlug); + clack.log.success( + "Added project-scoped Sentry MCP configuration for Claude Code.", + ); + clack.log.info( + chalk.dim( + "Note: You may need to reload your editor for MCP changes to take effect.", + ), + ); + break; + case "openCode": + await addOpenCodeMcpConfig(orgSlug, projectSlug); + clack.log.success( + "Added project-scoped Sentry MCP configuration for OpenCode.", + ); + clack.log.info( + chalk.dim( + "Note: You may need to restart OpenCode for MCP changes to take effect.", + ), + ); + break; + case "jetbrains": + await showJetBrainsMcpConfig(orgSlug, projectSlug); + Sentry.setTag("mcp-config-manual", true); + break; + case "other": + await showGenericMcpConfig(orgSlug, projectSlug); + Sentry.setTag("mcp-config-manual", true); + break; + } + Sentry.setTag(`mcp-config-${editor}-success`, true); + } catch (e) { + Sentry.setTag(`mcp-config-${editor}-success`, false); + Sentry.setTag("mcp-config-fallback", true); + clack.log.warn( + chalk.yellow( + `Failed to write MCP config for ${editor} automatically. Please copy/paste the snippet below into your project config file.`, + ), + ); + + // Fallback: show per-editor instructions + if (editor === "cursor") { + await showCopyPasteInstructions({ + filename: path.join(".cursor", "mcp.json"), + codeSnippet: getCursorMcpJsonSnippet(orgSlug, projectSlug), + hint: "create the file if it does not exist", + }); + } else if (editor === "vscode") { + await showCopyPasteInstructions({ + filename: path.join(".vscode", "mcp.json"), + codeSnippet: getVsCodeMcpJsonSnippet(orgSlug, projectSlug), + hint: "create the file if it does not exist", + }); + } else if (editor === "claudeCode") { + await showCopyPasteInstructions({ + filename: ".mcp.json", + codeSnippet: getClaudeCodeMcpJsonSnippet(orgSlug, projectSlug), + hint: "create the file if it does not exist", + }); + } else if (editor === "openCode") { + await showCopyPasteInstructions({ + filename: "opencode.json", + codeSnippet: getOpenCodeMcpJsonSnippet(orgSlug, projectSlug), + hint: "create the file if it does not exist", + }); + } + } + } +} diff --git a/packages/cli/src/lib/wizard/utils/clack/prompts.ts b/packages/cli/src/lib/wizard/utils/clack/prompts.ts new file mode 100644 index 0000000000..3e969a1c52 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/clack/prompts.ts @@ -0,0 +1,71 @@ +/** + * The `@clack/prompts` functions the setup wizards use, gathered on one + * object so the ported flows keep their `clack.log.info(…)` call sites. + * + * The wizards run only under `sentry wizard`, whose chunk loads on demand, so + * importing clack here does not reach other commands or the completion bundle. + * + * `rawOutput` prints text the user copies as-is (code snippets, tokens): + * outside clack's gutter, so nothing gets prefixed to the copied lines. + * + * Each member is a getter, so a test that mocks `@clack/prompts` with only + * the functions its code path calls (as the sentry-wizard tests do) still + * loads this module. + */ + +import { + cancel, + confirm, + intro, + isCancel, + log, + multiselect, + note, + outro, + select, + spinner, + text, +} from "@clack/prompts"; + +/** Print `value` to stdout on its own lines, outside clack's gutter. */ +function rawOutput(value: string): void { + process.stdout.write(`${value}\n`); +} + +/** The clack prompts and log helpers the wizards call. */ +export const clack = { + get cancel() { + return cancel; + }, + get confirm() { + return confirm; + }, + get intro() { + return intro; + }, + get isCancel() { + return isCancel; + }, + get log() { + return log; + }, + get multiselect() { + return multiselect; + }, + get note() { + return note; + }, + get outro() { + return outro; + }, + rawOutput, + get select() { + return select; + }, + get spinner() { + return spinner; + }, + get text() { + return text; + }, +}; diff --git a/packages/cli/src/lib/wizard/utils/data-collection.ts b/packages/cli/src/lib/wizard/utils/data-collection.ts new file mode 100644 index 0000000000..8c157c1cf7 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/data-collection.ts @@ -0,0 +1,122 @@ +/** + * Ask whether the SDK should collect less personal data, for the + * `dataCollection` option the wizards write into `Sentry.init()`. + */ + +import { clack } from "./clack/prompts.js"; +import { Sentry } from "../telemetry.js"; +import chalk from "chalk"; + +import { traceStep } from "../telemetry.js"; +import { abortIfCancelled } from "./clack/index.js"; +import { getMajorVersion } from "./semver.js"; + +export const DATA_COLLECTION_DOCS_URL = + "https://docs.sentry.io/platforms/javascript/configuration/options/#dataCollection"; + +/** + * Keys that commonly reveal user identity in HTTP headers, cookies, and URL + * query parameters (forwarding chains, IP addresses, user hints). + */ +const PII_KEY_DENYLIST = ["forwarded", "-ip", "remote-", "via", "-user"]; + +const PII_KEY_DENYLIST_SNIPPET = `[${PII_KEY_DENYLIST.map( + (key) => `"${key}"`, +).join(", ")}]`; + +/** + * `dataCollection` value the wizard writes when the user opts to reduce data + * collection. Kept as an object so magicast-based wizards can insert it as an + * AST node; `getDataCollectionSnippet` renders the same preset for + * template-string-based wizards. + */ +export const DATA_COLLECTION_PII_PRESET = { + userInfo: false, + graphQL: { document: false, variables: false }, + genAI: { inputs: false, outputs: false }, + databaseQueryData: false, + queues: false, + httpBodies: [], + httpHeaders: { deny: [...PII_KEY_DENYLIST] }, + cookies: { deny: [...PII_KEY_DENYLIST] }, + urlQueryParams: { deny: [...PII_KEY_DENYLIST] }, +}; + +export const DATA_COLLECTION_COMMENT_LINES = [ + "Turns off collection of data that could identify users. Adjust per category:", + DATA_COLLECTION_DOCS_URL, +]; + +/** + * Renders the PII preset (with its explanatory comment) as code to embed in a + * generated `Sentry.init` options object. Every line is prefixed with + * `indent`; the result ends without a trailing newline. + */ +export function getDataCollectionSnippet(indent = " "): string { + const lines = [ + ...DATA_COLLECTION_COMMENT_LINES.map((line) => `// ${line}`), + "dataCollection: {", + " userInfo: false,", + " graphQL: { document: false, variables: false },", + " genAI: { inputs: false, outputs: false },", + " databaseQueryData: false,", + " queues: false,", + " httpBodies: [],", + ` httpHeaders: { deny: ${PII_KEY_DENYLIST_SNIPPET} },`, + ` cookies: { deny: ${PII_KEY_DENYLIST_SNIPPET} },`, + ` urlQueryParams: { deny: ${PII_KEY_DENYLIST_SNIPPET} },`, + "},", + ]; + + return lines.map((line) => `${indent}${line}`).join("\n"); +} + +/** + * The `dataCollection` option only makes sense to offer from SDK v11 on, + * where the SDK collects rich context by default. Unknown or unparseable + * installed versions fall back to the major of the range the wizard installs. + */ +export function sdkSupportsDataCollection( + installedSdkVersion: string | undefined, + wizardInstallRange: string, +): boolean { + const sdkMajor = + getMajorVersion(installedSdkVersion) ?? + getMajorVersion(wizardInstallRange) ?? + 0; + + return sdkMajor >= 11; +} + +/** + * Asks whether the wizard should write the PII-reducing `dataCollection` + * preset. Call this only when `sdkSupportsDataCollection` returned `true`. + */ +export async function askShouldReduceDataCollection(): Promise { + return await traceStep("data-collection", async () => { + const reduceDataCollection: boolean = await abortIfCancelled( + clack.select({ + message: + "Sentry collects request data, user info, and other context by default. Do you want to reduce this to avoid sending personally identifiable information (PII)?\n" + + `More info: ${chalk.cyan(DATA_COLLECTION_DOCS_URL)}`, + initialValue: false, + options: [ + { + value: true, + label: "Yes", + hint: "Add a dataCollection config to Sentry.init() that turns off PII-heavy categories", + }, + { + value: false, + label: "No", + hint: "Keep the SDK defaults", + }, + ], + }), + ); + + Sentry.setTag("data-collection-reduced", reduceDataCollection); + + return reduceDataCollection; + }); +} diff --git a/packages/cli/src/lib/wizard/utils/debug.ts b/packages/cli/src/lib/wizard/utils/debug.ts new file mode 100644 index 0000000000..c8668c78ce --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/debug.ts @@ -0,0 +1,32 @@ +/** + * Debug output of the setup wizards, shown with `sentry wizard --debug`. + */ + +import chalk from "chalk"; +import { clack } from "./clack/prompts.js"; + +let debugEnabled = false; + +/** Render one debug argument: strings as-is, errors with their stack. */ +function prepareMessage(msg: unknown): string { + if (typeof msg === "string") { + return msg; + } + if (msg instanceof Error) { + return msg.stack ?? msg.message; + } + return JSON.stringify(msg, null, "\t"); +} + +/** Log `args` in the wizard's output when `--debug` is on. */ +export function debug(...args: unknown[]): void { + if (!debugEnabled) { + return; + } + clack.log.info(chalk.dim(args.map((a) => prepareMessage(a)).join(" "))); +} + +/** Turn on {@link debug} output for the rest of the run. */ +export function enableDebugLogs(): void { + debugEnabled = true; +} diff --git a/packages/cli/src/lib/wizard/utils/git.ts b/packages/cli/src/lib/wizard/utils/git.ts new file mode 100644 index 0000000000..193d67460d --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/git.ts @@ -0,0 +1,75 @@ +/** + * Git checks the wizards run before they change a project's files. + */ + +import { execSync } from "node:child_process"; +import { debug } from "./debug.js"; + +/** + * Checks if the current working directory is a git repository. + * + * @param opts.cwd The directory of the project. If undefined, the current process working directory will be used. + * + * @returns true if the current working directory is a git repository, false otherwise. + */ +export function isInGitRepo(opts: { cwd: string | undefined }) { + try { + execSync("git rev-parse --is-inside-work-tree", { + stdio: "ignore", + cwd: opts.cwd, + }); + return true; + } catch (error) { + debug(error); + return false; + } +} + +/** + * Returns the exact paths of uncommitted or untracked files. + * + * Uses `git status --porcelain=v1 -z` so paths are NUL-terminated and verbatim, + * preserving spaces and unusual characters. Pass results as argv entries to a + * non-shell child process; do not interpolate them into a shell string. + * + * @param opts.cwd The project directory. Defaults to the current working directory. + */ +export function getUncommittedOrUntrackedFilePaths(opts?: { + cwd: string | undefined; +}): string[] { + try { + const gitStatus = execSync("git status --porcelain=v1 -z", { + // we only care about stdout + stdio: ["ignore", "pipe", "ignore"], + cwd: opts?.cwd, + }).toString(); + + const fields = gitStatus.split("\0"); + const files: string[] = []; + + for (let i = 0; i < fields.length; i++) { + const entry = fields[i]; + if (!entry) { + continue; + } + + // Entry is `XY `. Renames/copies (R/C) store the source in the + // next field, which we skip. + const status = entry.slice(0, 2); + const filePath = entry.slice(3); + + if (status[0] === "R" || status[0] === "C") { + i++; + } + + if (filePath) { + files.push(filePath); + } + } + + return files; + } catch (error) { + debug(error); + return []; + } +} diff --git a/packages/cli/src/lib/wizard/utils/node-version.ts b/packages/cli/src/lib/wizard/utils/node-version.ts new file mode 100644 index 0000000000..723b7d17fe --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/node-version.ts @@ -0,0 +1,50 @@ +/** + * Check the Node.js version a framework's SDK needs. + */ + +import { clack } from "./clack/prompts.js"; +import chalk from "chalk"; +import { coerce, satisfies } from "semver"; + +/** + * Node.js versions supported by version 11 of the Sentry JavaScript SDKs. + * See https://docs.sentry.io/platforms/javascript/migration/v10-to-v11/#nodejs + */ +export const NODE_VERSION_RANGE_FOR_SDK_V11 = + ">=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0"; + +/** + * Returns `false` when the given Node.js version is definitely not supported by + * SDK v11. Unparseable versions are treated as supported. + */ +export function isNodeVersionSupportedBySdkV11( + version: string = process.version, +): boolean { + const parsed = coerce(version); + if (!parsed) { + return true; + } + return satisfies(parsed, NODE_VERSION_RANGE_FOR_SDK_V11); +} + +/** + * Warns when the wizard runs on a Node.js version that SDK v11 does not + * support. The wizard continues either way: the project may be built and run + * on a different Node.js than the one the wizard runs on. + */ +export function warnIfNodeVersionUnsupportedBySdkV11( + version: string = process.version, +): void { + if (isNodeVersionSupportedBySdkV11(version)) { + return; + } + + clack.log.warn( + `${chalk.yellow( + `Version 11 of the Sentry JavaScript SDKs requires Node.js 20.19.0 or newer (22.12.0 on Node.js 22, 23.2.0 on Node.js 23), but this wizard is running on Node.js ${chalk.bold( + version, + )}.`, + )} +The wizard will continue. Make sure your project builds and runs on a supported Node.js version before moving to SDK v11.`, + ); +} diff --git a/packages/cli/src/lib/wizard/utils/package-json.ts b/packages/cli/src/lib/wizard/utils/package-json.ts new file mode 100644 index 0000000000..1de6728d35 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/package-json.ts @@ -0,0 +1,186 @@ +/** + * Read dependencies from a project's `package.json`, including versions + * pnpm resolves from a `pnpm-workspace.yaml` catalog. + */ + +import { clack } from "./clack/prompts.js"; +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; + +export type PackageDotJson = { + version?: string | undefined; + scripts?: Record; + dependencies?: Record | undefined; + devDependencies?: Record | undefined; + resolutions?: Record | undefined; + overrides?: Record | undefined; + pnpm?: { + overrides?: Record | undefined; + }; +}; + +type NpmPackage = { + name: string; + version: string; +}; + +type PnpmCatalogs = Record>; + +type PnpmWorkspace = { + catalog?: Record | undefined; + catalogs?: PnpmCatalogs | undefined; +}; + +/** Strip quotes and a trailing comment from a YAML scalar. */ +function yamlScalar(raw: string): string { + const value = raw.replace(/\s+#.*$/, "").trim(); + const quoted = /^(['"])(.*)\1$/.exec(value); + return quoted?.[2] ?? value; +} + +/** + * Read the `catalog` and `catalogs` sections of a `pnpm-workspace.yaml`. + * + * Only block mappings are read: `catalog:` with `name: version` entries, and + * `catalogs:` with a mapping of such catalogs. Everything else in the file is + * skipped, so the wizard needs no YAML parser. + */ +export function parsePnpmWorkspaceCatalogs(content: string): PnpmWorkspace { + const workspace: PnpmWorkspace = {}; + let section: "catalog" | "catalogs" | undefined; + let catalogName: string | undefined; + let namedIndent = -1; + + for (const line of content.split(/\r?\n/)) { + if (!line.trim() || line.trim().startsWith("#")) { + continue; + } + const indent = line.length - line.trimStart().length; + const entry = /^\s*(['"]?)([^'":]+)\1\s*:\s*(.*)$/.exec(line); + if (indent === 0) { + section = + entry?.[2] === "catalog" || entry?.[2] === "catalogs" + ? entry[2] + : undefined; + catalogName = undefined; + namedIndent = -1; + continue; + } + if (!(section && entry?.[2])) { + continue; + } + const key = entry[2].trim(); + const value = yamlScalar(entry[3] ?? ""); + if (section === "catalog") { + workspace.catalog = { ...workspace.catalog, [key]: value }; + } else if (namedIndent < 0 || indent <= namedIndent) { + namedIndent = indent; + catalogName = key; + } else if (catalogName) { + const catalogs = workspace.catalogs ?? {}; + catalogs[catalogName] = { ...catalogs[catalogName], [key]: value }; + workspace.catalogs = catalogs; + } + } + return workspace; +} + +/** + * Finds and parses the pnpm-workspace.yaml file to extract catalog definitions. + * Searches up to 10 parent directories from the current working directory. + * Returns null if the file doesn't exist or can't be parsed. + */ +function getPnpmWorkspace(): PnpmWorkspace | null { + let currentDir = process.cwd(); + const maxLevels = 10; + + for (let i = 0; i < maxLevels; i++) { + const workspaceFile = path.join(currentDir, "pnpm-workspace.yaml"); + + if (existsSync(workspaceFile)) { + const content = readFileSync(workspaceFile, "utf-8"); + + return parsePnpmWorkspaceCatalogs(content); + } + + const parentDir = path.dirname(currentDir); + + // Stop if we've reached the root directory + if (parentDir === currentDir) { + break; + } + + currentDir = parentDir; + } + + clack.log.error("Could not find pnpm-workspace.yaml."); + + return null; +} + +/** + * Resolves a catalog reference (e.g., "catalog:" or "catalog:sveltekit") to the actual version. + * - "catalog:" refers to the default catalog (workspace.catalog) + * - "catalog:customcatalog" refers to a named catalog (workspace.catalogs.customcatalog) + * Returns the actual version if found, or undefined if the catalog or package doesn't exist. + */ +function resolveCatalogVersion( + catalogRef: string, + packageName: string, +): string | undefined { + const catalogName = catalogRef.replace(/^catalog:/, ""); + const workspace = getPnpmWorkspace(); + + if (!workspace) { + return undefined; + } + + const catalog = + catalogName === "" ? workspace.catalog : workspace.catalogs?.[catalogName]; + + return catalog?.[packageName]; +} + +/** + * Checks if @param packageJson has any of the @param packageNamesList package names + * listed as a dependency or devDependency. + * If so, it returns the first package name that is found, including the + * version (range) specified in the package.json. + */ +export function findInstalledPackageFromList( + packageNamesList: string[], + packageJson: PackageDotJson, +): NpmPackage | undefined { + return packageNamesList + .map((packageName) => ({ + name: packageName, + version: getPackageVersion(packageName, packageJson), + })) + .find((sdkPackage): sdkPackage is NpmPackage => !!sdkPackage.version); +} + +export function hasPackageInstalled( + packageName: string, + packageJson: PackageDotJson, +): boolean { + return getPackageVersion(packageName, packageJson) !== undefined; +} + +export function getPackageVersion( + packageName: string, + packageJson: PackageDotJson, +): string | undefined { + const rawVersion = + packageJson.dependencies?.[packageName] || + packageJson.devDependencies?.[packageName]; + + if (!rawVersion) { + return undefined; + } + + const version = rawVersion.startsWith("catalog:") + ? resolveCatalogVersion(rawVersion, packageName) + : rawVersion; + + return version; +} diff --git a/packages/cli/src/lib/wizard/utils/package-manager.ts b/packages/cli/src/lib/wizard/utils/package-manager.ts new file mode 100644 index 0000000000..a772f768f6 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/package-manager.ts @@ -0,0 +1,239 @@ +/** + * Detect the project's package manager and the commands it runs. + */ + +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; + +import { Sentry } from "../telemetry.js"; +import { traceStep } from "../telemetry.js"; +import { getPackageDotJson, updatePackageDotJson } from "./clack/index.js"; +import { debug } from "./debug.js"; + +export interface PackageManager { + name: string; + label: string; + installCommand: string; + buildCommand: string; + /* The command that the package manager uses to run a script from package.json */ + runScriptCommand: string; + flags: string; + forceInstallFlag: string; + registry?: string | undefined; + detect: () => boolean; + addOverride: (pkgName: string, pkgVersion: string) => Promise; +} + +export const BUN: PackageManager = { + name: "bun", + label: "Bun", + installCommand: "add", + buildCommand: "bun run build", + runScriptCommand: "bun run", + flags: "", + forceInstallFlag: "--force", + detect: () => + ["bun.lockb", "bun.lock"].some((lockFile) => { + try { + return existsSync(path.join(process.cwd(), lockFile)); + } catch (e) { + debug(e); + return false; + } + }), + addOverride: async (pkgName, pkgVersion): Promise => { + const packageDotJson = await getPackageDotJson(); + const overrides = packageDotJson.overrides || {}; + + await updatePackageDotJson({ + ...packageDotJson, + overrides: { + ...overrides, + [pkgName]: pkgVersion, + }, + }); + }, +}; +export const DENO: PackageManager = { + name: "deno", + label: "Deno", + installCommand: "install", + buildCommand: "deno task build", + runScriptCommand: "deno task", + flags: "", + forceInstallFlag: "--force", + registry: "npm", + detect: () => { + try { + return existsSync(path.join(process.cwd(), "deno.lock")); + } catch (e) { + debug(e); + return false; + } + }, + addOverride: async (pkgName, pkgVersion): Promise => { + const packageDotJson = await getPackageDotJson(); + const overrides = packageDotJson.overrides || {}; + + await updatePackageDotJson({ + ...packageDotJson, + overrides: { + ...overrides, + [pkgName]: pkgVersion, + }, + }); + }, +}; +export const YARN_V1: PackageManager = { + name: "yarn", + label: "Yarn V1", + installCommand: "add", + buildCommand: "yarn build", + runScriptCommand: "yarn", + flags: "--ignore-workspace-root-check", + forceInstallFlag: "--force", + detect: () => { + try { + return readFileSync(path.join(process.cwd(), "yarn.lock"), "utf-8") + .slice(0, 500) + .includes("yarn lockfile v1"); + } catch (e) { + debug(e); + return false; + } + }, + addOverride: async (pkgName, pkgVersion): Promise => { + const packageDotJson = await getPackageDotJson(); + const resolutions = packageDotJson.resolutions || {}; + + await updatePackageDotJson({ + ...packageDotJson, + resolutions: { + ...resolutions, + [pkgName]: pkgVersion, + }, + }); + }, +}; +/** YARN V2/3/4 */ +export const YARN_V2: PackageManager = { + name: "yarn", + label: "Yarn V2/3/4", + installCommand: "add", + buildCommand: "yarn build", + runScriptCommand: "yarn", + flags: "", + forceInstallFlag: "--force", + detect: () => { + try { + return readFileSync(path.join(process.cwd(), "yarn.lock"), "utf-8") + .slice(0, 500) + .includes("__metadata"); + } catch (e) { + debug(e); + return false; + } + }, + addOverride: async (pkgName, pkgVersion): Promise => { + const packageDotJson = await getPackageDotJson(); + const resolutions = packageDotJson.resolutions || {}; + + await updatePackageDotJson({ + ...packageDotJson, + resolutions: { + ...resolutions, + [pkgName]: pkgVersion, + }, + }); + }, +}; +export const PNPM: PackageManager = { + name: "pnpm", + label: "PNPM", + installCommand: "add", + buildCommand: "pnpm build", + runScriptCommand: "pnpm", + flags: "--ignore-workspace-root-check", + forceInstallFlag: "--force", + detect: () => { + try { + return existsSync(path.join(process.cwd(), "pnpm-lock.yaml")); + } catch (e) { + debug(e); + return false; + } + }, + addOverride: async (pkgName, pkgVersion): Promise => { + const packageDotJson = await getPackageDotJson(); + const pnpm = packageDotJson.pnpm || {}; + const overrides = pnpm.overrides || {}; + + await updatePackageDotJson({ + ...packageDotJson, + pnpm: { + ...pnpm, + overrides: { + ...overrides, + [pkgName]: pkgVersion, + }, + }, + }); + }, +}; +export const NPM: PackageManager = { + name: "npm", + label: "NPM", + installCommand: "install", + buildCommand: "npm run build", + runScriptCommand: "npm run", + flags: "", + forceInstallFlag: "--force", + detect: () => { + try { + return existsSync(path.join(process.cwd(), "package-lock.json")); + } catch (e) { + debug(e); + return false; + } + }, + addOverride: async (pkgName, pkgVersion): Promise => { + const packageDotJson = await getPackageDotJson(); + const overrides = packageDotJson.overrides || {}; + + await updatePackageDotJson({ + ...packageDotJson, + overrides: { + ...overrides, + [pkgName]: pkgVersion, + }, + }); + }, +}; + +export const packageManagers = [NPM, YARN_V1, YARN_V2, PNPM, BUN, DENO]; + +/** + * Exported only for testing. + * DO NOT call this function directly! + * Use `getPackageManger` instead. + */ +export function _detectPackageManger( + managers?: PackageManager[], +): PackageManager | null { + return traceStep("detect-package-manager", () => { + const foundPackageMangers = (managers ?? packageManagers).filter( + (packageManager) => packageManager.detect(), + ); + + // Only consider a package manager detected if we found exactly one. + // If we find more than one, we should not make any assumptions. + const [found] = foundPackageMangers; + if (found && foundPackageMangers.length === 1) { + Sentry.setTag("package-manager", found.name); + return found; + } + + Sentry.setTag("package-manager", "not-detected"); + return null; + }); +} diff --git a/packages/cli/src/lib/wizard/utils/project-data.ts b/packages/cli/src/lib/wizard/utils/project-data.ts new file mode 100644 index 0000000000..87718dcbb9 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/project-data.ts @@ -0,0 +1,479 @@ +/** + * Pick the Sentry project a setup wizard configures, with the CLI's login. + * + * The old wizard opened `account/settings/wizard//` in a browser and + * polled for the projects and an auth token. This module uses what the rest + * of the CLI uses instead: + * + * - The stored `sentry auth login` account, or a new device-flow login (or an + * agent handoff from `SENTRY_HANDOFF`) when there is none. A new login asks + * for `org:tokens` and `org:ci` too, so the auth token below needs no second + * approval. + * - The org from `--org`, the handoff, or a prompt; then the project from + * `--project` or a prompt that can also create one for the wizard's + * platform, like the old browser page could. + * - The project's DSN from its client keys. + * - A new org auth token for the build plugins and `sentry` commands that + * upload source maps and debug files. When the token can't be created, a + * placeholder goes in its place and the user is told where to make one. + */ + +import chalk from "chalk"; +import { completeAgentHandoff } from "../../agent-handoff.js"; +import { + getProject, + getProjectKeys, + listProjects, +} from "../../api/projects.js"; +import { createOrgAuthToken } from "../../api/org-auth-tokens.js"; +import { listOrganizations } from "../../api/organizations.js"; +import { + createProjectWithAutoTeam, + createProjectWithDsn, + MEMBER_PROJECT_CREATION_DISABLED_DETAIL, +} from "../../api/projects.js"; +import { assertAutoLoginHostTrusted } from "../../auto-auth.js"; +import { DEFAULT_SENTRY_URL } from "../../constants.js"; +import { getAuthConfig } from "../../db/auth.js"; +import { getEnv } from "../../env.js"; +import { ApiError } from "../../errors.js"; +import { runInteractiveLogin } from "../../interactive-login.js"; +import { logger } from "../../logger.js"; +import { OAUTH_SCOPES, resolveOAuthScopeString } from "../../oauth.js"; +import { resolveOrCreateTeam } from "../../resolve-team.js"; +import { ensureScopesForAction } from "../../scope-recovery.js"; +import { getSentryBaseUrl, isSentrySaasUrl } from "../../sentry-urls.js"; +import { registerLoginTrustAnchor } from "../../token-host.js"; +import { slugify } from "../../utils.js"; +import { sentry } from "../../app-identity.js"; +import type { + SentryOrganization, + SentryProject, +} from "../../../types/sentry.js"; +import { Sentry, traceStep } from "../telemetry.js"; +import { abort, abortIfCancelled } from "./clack/index.js"; +import { clack } from "./clack/prompts.js"; +import type { SentryProjectData, WizardOptions } from "./types.js"; + +const log = logger.withTag("wizard"); + +/** Written in place of an auth token that couldn't be created. */ +export const DUMMY_AUTH_TOKEN = "_YOUR_SENTRY_AUTH_TOKEN_"; + +/** Scopes an org auth token request needs from the CLI's OAuth grant. */ +const TOKEN_SCOPES = ["org:tokens", "org:read", "org:ci"] as const; + +/** `value` of the project picker's "create a new project" option. */ +const CREATE_PROJECT = Symbol("create-project"); + +/** Sentry platform identifiers of the wizards, used for new projects. */ +export type WizardPlatform = + | "javascript-angular" + | "javascript-nextjs" + | "javascript-nuxt" + | "javascript-react-router" + | "javascript-remix" + | "javascript-sveltekit" + | "node-cloudflare-workers" + | "apple-ios" + | "android" + | "react-native" + | "flutter"; + +/** The project a wizard sets up, or Spotlight mode, which needs none. */ +export type WizardProjectData = + | { + /** Web URL of the Sentry instance, ending in `/`. */ + sentryUrl: string; + selfHosted: boolean; + selectedProject: SentryProjectData; + /** Org auth token, or {@link DUMMY_AUTH_TOKEN}. */ + authToken: string; + spotlight: false; + } + | { + spotlight: true; + }; + +/** + * Get the Sentry project for a wizard run: the one passed in + * `options.preSelectedProject`, or one the user picks (or creates) after + * logging in. + * + * @param options - Wizard options (`--url`, `--saas`, `--org`, `--project`, …) + * @param platform - Platform for a project the user creates + */ +export async function getOrAskForProjectData( + options: WizardOptions, + platform?: WizardPlatform, +): Promise { + if (options.spotlight) { + clack.log.info( + `Spotlight mode enabled! Setting up for local development without Sentry account needed.\n + Note: Your app will only send data to the local Spotlight debugger, not to Sentry.`, + ); + return { spotlight: true }; + } + + if (options.preSelectedProject) { + return { + selfHosted: options.preSelectedProject.selfHosted, + sentryUrl: withTrailingSlash(options.url ?? DEFAULT_SENTRY_URL), + authToken: options.preSelectedProject.authToken, + selectedProject: options.preSelectedProject.project, + spotlight: false, + }; + } + + await traceStep("ask-self-hosted", () => + selectSentryUrl(options.url, options.saas), + ); + const handoffOrg = await traceStep("login", ensureLoggedIn); + + const sentryUrl = withTrailingSlash(getSentryBaseUrl()); + const selfHosted = !isSentrySaasUrl(sentryUrl); + Sentry.setTag("url", sentryUrl); + Sentry.setTag("self-hosted", selfHosted); + + const org = await traceStep("select-org", () => + selectOrganization(options.orgSlug ?? handoffOrg), + ); + const project = await traceStep("select-project", () => + selectProject(org, options.projectSlug, platform), + ); + Sentry.setTag("project", project.slug); + Sentry.setUser({ id: org.slug }); + + const dsn = await getDsn(org.slug, project.slug); + const authToken = await traceStep("create-auth-token", () => + createAuthToken(org.slug, sentryUrl), + ); + + return { + sentryUrl, + selfHosted, + authToken, + selectedProject: { + id: project.id, + slug: project.slug, + organization: { id: org.id, name: org.name, slug: org.slug }, + keys: [{ dsn: { public: dsn } }], + }, + spotlight: false, + }; +} + +/** + * Point this run at the Sentry instance the user chose: SaaS for `--saas`, + * the `--url` instance, or the answer to a SaaS/self-hosted prompt. Without + * any of them and with a stored login, the login's instance is used. + * + * An instance the user names here (flag or prompt) is trusted for login, the + * same as `sentry auth login --url`. + */ +async function selectSentryUrl( + urlFromArgs: string | undefined, + saas: boolean | undefined, +): Promise { + if (saas) { + useSentryUrl(DEFAULT_SENTRY_URL); + return; + } + if (!urlFromArgs && getAuthConfig()) { + return; + } + + if (!urlFromArgs) { + const choice = await abortIfCancelled( + clack.select({ + message: "Are you using Sentry SaaS or self-hosted Sentry?", + options: [ + { value: "saas", label: "Sentry SaaS (sentry.io)" }, + { + value: "self-hosted", + label: "Self-hosted/on-premise/single-tenant", + }, + ], + }), + ); + if (choice === "saas") { + useSentryUrl(DEFAULT_SENTRY_URL); + return; + } + } + + let pending = urlFromArgs; + for (;;) { + const url = + pending || + (await abortIfCancelled( + clack.text({ + message: `Please enter the URL of your ${ + urlFromArgs ? "" : "self-hosted " + }Sentry instance.`, + placeholder: "https://sentry.io/", + }), + )); + pending = undefined; + const origin = parseOrigin(url); + if (origin) { + useSentryUrl(origin); + return; + } + clack.log.error( + `Please enter a valid URL. (It should look something like "https://sentry.mydomain.com/", got ${url})`, + ); + } +} + +/** The origin of `url`, or `undefined` when it isn't an HTTP(S) URL. */ +function parseOrigin(url: string): string | undefined { + try { + const parsed = new URL(url); + return parsed.protocol === "https:" || parsed.protocol === "http:" + ? parsed.origin + : undefined; + } catch (error) { + log.debug(`Invalid Sentry URL ${url}`, error); + return; + } +} + +/** Send this run's API requests and login to `url`, trusted as user input. */ +function useSentryUrl(url: string): void { + const env = getEnv(); + env["SENTRY_HOST"] = url; + env["SENTRY_URL"] = url; + registerLoginTrustAnchor(url); +} + +/** + * Make sure the CLI has a login for the selected instance: claim the agent + * handoff in `SENTRY_HANDOFF`, keep a stored login, or run the device flow. + * + * @returns The org slug of a claimed handoff + */ +async function ensureLoggedIn(): Promise { + const handoffCode = getEnv()["SENTRY_HANDOFF"]?.trim(); + if (handoffCode) { + const handoff = await completeAgentHandoff(handoffCode); + Sentry.setTag("login-method", "handoff"); + return handoff.organizationSlug; + } + + if (getAuthConfig()) { + Sentry.setTag("login-method", "stored"); + return; + } + + assertAutoLoginHostTrusted(); + clack.log.info( + `${chalk.bold("Log in to Sentry")} to pick the project to set up. No account yet? You can sign up on the page that opens.`, + ); + const login = await runInteractiveLogin({ + scope: resolveOAuthScopeString({ + scopes: [...OAUTH_SCOPES, ...TOKEN_SCOPES], + }), + }); + if (!login) { + Sentry.setTag("login-method", "failed"); + return await abort( + `Please restart the wizard and log in to complete the setup. You can also log in first with ${chalk.cyan(sentry`auth login`)}.`, + ); + } + Sentry.setTag("login-method", "device-flow"); + return; +} + +/** + * The organization to set up: `slug` when given, the only one the user + * belongs to, or the one they pick. + */ +async function selectOrganization( + slug: string | undefined, +): Promise>> { + const orgs = await listOrganizations(); + if (slug) { + const match = orgs.find((org) => org.slug === slug); + if (match) { + clack.log.step(`Selected organization ${chalk.cyan(match.slug)}`); + return match; + } + clack.log.warn( + `Could not find an organization with the slug ${chalk.cyan(slug)}.`, + ); + } + + const [only] = orgs; + if (orgs.length === 1 && only) { + clack.log.step(`Selected organization ${chalk.cyan(only.slug)}`); + return only; + } + if (!only) { + Sentry.setTag("no-orgs-found", true); + return await abort( + "Your Sentry account has no organizations. Create one in Sentry and run the wizard again.", + ); + } + + return await abortIfCancelled( + clack.select({ + maxItems: 12, + message: "Select your Sentry organization.", + options: [...orgs] + .sort((a, b) => a.slug.localeCompare(b.slug)) + .map((org) => ({ value: org, label: org.slug, hint: org.name })), + }), + ); +} + +/** + * The project to set up: `slug` when given and found, else the one the user + * picks from the org's projects or creates. + */ +async function selectProject( + org: { slug: string }, + slug: string | undefined, + platform: WizardPlatform | undefined, +): Promise { + if (slug) { + try { + const project = await getProject(org.slug, slug); + clack.log.step( + `Selected project ${chalk.cyan(`${org.slug}/${project.slug}`)}`, + ); + return project; + } catch (error) { + if (!(error instanceof ApiError && error.status === 404)) { + throw error; + } + clack.log.warn("Could not find a project with the provided slugs."); + } + } + + const projects = (await listProjects(org.slug)).sort((a, b) => + a.slug.localeCompare(b.slug), + ); + const selection = await abortIfCancelled( + clack.select({ + maxItems: 12, + message: "Select your Sentry project.", + options: [ + { value: CREATE_PROJECT, label: "Create a new project" }, + ...projects.map((project) => ({ + value: project, + label: `${org.slug}/${project.slug}`, + ...(project.platform ? { hint: project.platform } : {}), + })), + ], + ...(projects.length > 0 ? { initialValue: projects[0] } : {}), + }), + ); + if (typeof selection !== "symbol") { + return selection; + } + Sentry.setTag("created-project", true); + return await createProject(org.slug, platform); +} + +/** + * Ask for a name and create a project for `platform` in `orgSlug`, on the + * team the CLI's `project create` would pick. Members who can't use that + * team get a project on their personal team. + */ +async function createProject( + orgSlug: string, + platform: WizardPlatform | undefined, +): Promise { + const name = await abortIfCancelled( + clack.text({ + message: "What should the new project be called?", + initialValue: slugify(process.cwd().split(/[\\/]/).pop() ?? ""), + validate: (value) => + value.trim() ? undefined : "Please enter a project name.", + }), + ); + const body = { name: name.trim(), ...(platform ? { platform } : {}) }; + + const spinner = clack.spinner(); + spinner.start("Creating your Sentry project"); + try { + const team = await resolveOrCreateTeam(orgSlug, { + usageHint: sentry`wizard --org `, + autoCreateSlug: slugify(body.name), + }); + const { project } = await createProjectWithDsn(orgSlug, team.slug, body); + spinner.stop(`Created project ${chalk.cyan(`${orgSlug}/${project.slug}`)}`); + return project; + } catch (error) { + if ( + !(error instanceof ApiError && error.status === 403) || + error.detail?.includes(MEMBER_PROJECT_CREATION_DISABLED_DETAIL) + ) { + spinner.stop("Could not create the project."); + throw error; + } + log.debug("403 on the team-based flow, using the org-scoped endpoint"); + const { project } = await createProjectWithAutoTeam(orgSlug, body); + spinner.stop(`Created project ${chalk.cyan(`${orgSlug}/${project.slug}`)}`); + return project; + } +} + +/** The public DSN of the project's first active client key. */ +async function getDsn(orgSlug: string, projectSlug: string): Promise { + const keys = await getProjectKeys(orgSlug, projectSlug); + const key = keys.find((k) => k.isActive) ?? keys[0]; + if (!key) { + return await abort( + `The project ${orgSlug}/${projectSlug} has no client keys (DSNs). Create one in its settings and run the wizard again.`, + ); + } + return key.dsn.public; +} + +/** + * Create an org auth token for uploading source maps and debug files, or + * return {@link DUMMY_AUTH_TOKEN} with instructions when that isn't possible + * (an old login without `org:tokens` in a non-interactive run, no permission, + * or a server that can't create tokens). + */ +async function createAuthToken( + orgSlug: string, + sentryUrl: string, +): Promise { + try { + const elevation = await ensureScopesForAction( + TOKEN_SCOPES, + "Creating an auth token for uploading source maps", + runInteractiveLogin, + ); + if (elevation !== "declined" && elevation !== "unavailable") { + const token = await createOrgAuthToken( + orgSlug, + `Sentry Wizard ${new Date().toISOString().slice(0, 10)}`, + ); + if (token.token) { + return token.token; + } + } + } catch (error) { + log.debug("Could not create an org auth token", error); + } + + Sentry.setTag("auth-token-created", false); + const settingsUrl = isSentrySaasUrl(sentryUrl) + ? `https://${orgSlug}.sentry.io/settings/auth-tokens/` + : `${sentryUrl}organizations/${orgSlug}/settings/auth-tokens/`; + clack.log.warn( + `Could not create an auth token for you. We'll add a placeholder (${chalk.cyan( + `"${DUMMY_AUTH_TOKEN}"`, + )}) for you to replace later.\nCreate your auth token here:\n${chalk.cyan(settingsUrl)}`, + ); + return DUMMY_AUTH_TOKEN; +} + +/** `url` with exactly one trailing `/`, the form the wizards expect. */ +function withTrailingSlash(url: string): string { + return url.endsWith("/") ? url : `${url}/`; +} diff --git a/packages/cli/src/lib/wizard/utils/semver.ts b/packages/cli/src/lib/wizard/utils/semver.ts new file mode 100644 index 0000000000..da0fe41424 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/semver.ts @@ -0,0 +1,65 @@ +/** + * Version range checks for installed SDK and framework versions. + */ + +import { + major, + minVersion, + satisfies, + subset, + valid, + validRange, +} from "semver"; +import { debug } from "./debug.js"; + +/** + * Returns the major version of an exact version or the lowest version that a + * range permits (e.g. `^10` -> 10, `~11.2.0` -> 11). Returns `undefined` for + * missing or unparseable input. + */ +export function getMajorVersion( + version: string | undefined, +): number | undefined { + if (!version) { + return undefined; + } + try { + const minVer = minVersion(version); + return minVer ? major(minVer) : undefined; + } catch (error) { + debug(error); + return undefined; + } +} + +export function fulfillsVersionRange({ + version, + acceptableVersions, + canBeLatest, +}: { + version: string; + acceptableVersions: string; + canBeLatest: boolean; +}): boolean { + if (version === "latest") { + return canBeLatest; + } + + let cleanedUserVersion, isRange; + + if (valid(version)) { + cleanedUserVersion = valid(version); + isRange = false; + } else if (validRange(version)) { + cleanedUserVersion = validRange(version); + isRange = true; + } + + return ( + // If the given version is a bogus format, this will still be undefined and we'll automatically reject it + !!cleanedUserVersion && + (isRange + ? subset(cleanedUserVersion, acceptableVersions) + : satisfies(cleanedUserVersion, acceptableVersions)) + ); +} diff --git a/packages/cli/src/lib/wizard/utils/types.ts b/packages/cli/src/lib/wizard/utils/types.ts new file mode 100644 index 0000000000..b7b267c44e --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/types.ts @@ -0,0 +1,104 @@ +/** + * Types shared by the setup wizards: the options `sentry wizard` passes to a + * flow, the Sentry project a flow sets up, and feature prompts. + */ + +export interface SentryProjectData { + id: string; + slug: string; + organization: { + id: string; + name: string; + slug: string; + }; + keys: [{ dsn: { public: string } }]; +} + +export type PreselectedProject = { + project: SentryProjectData; + authToken: string; + selfHosted: boolean; +}; + +export type WizardOptions = { + /** + * Controls whether the wizard should send telemetry data to Sentry. + */ + telemetryEnabled: boolean; + + /** + * The promo code to use while signing up for Sentry. + * This can be passed via the --promo-code arg. + */ + promoCode?: string | undefined; + + /** + * The url of the Sentry instance to use. + * This can be passed via the `-u` or `--url` arg. + */ + url?: string | undefined; + + /** + * The org to pre-select in the wizard. + * This can be passed via the `--org` arg. + * Example: `--org my-org` + */ + orgSlug?: string | undefined; + + /** + * Project slug to pre-select in the wizard. + * This can be passed via the `--project` arg. + * Example: `--project my-project` + */ + projectSlug?: string | undefined; + + /** + * If this option is set, the wizard will skip the self-hosted or SaaS + * selection step and directly assume that the wizard is used for Sentry SaaS. + */ + saas?: boolean | undefined; + + /** + * If this is set, the wizard will skip the login and project selection step. + */ + preSelectedProject?: PreselectedProject | undefined; + + /** + * Force-install the SDK package to continue with the installation in case + * any package manager checks are failing (e.g. peer dependency versions). + * + * Use with caution and only if you know what you're doing. + * + * Does not apply to all wizard flows (currently NPM only) + */ + forceInstall?: boolean | undefined; + + /** + * Used when the wizard command is copied from partner sites (e.g. Vercel) + * to display login/signup instructions specific to organizations provisioned + * through the partner. + */ + comingFrom?: string | undefined; + + /** + * If this is set, the wizard will ignore any git changes in the project and not prompt for confirmation. + */ + ignoreGitChanges?: boolean | undefined; + + /** + * Enable Spotlight mode for local development without Sentry authentication. + * When enabled: + * - Skips login and project selection + * - Uses empty DSN + * - Skips auth token file creation + * This can be passed via the `--spotlight` arg. + */ + spotlight?: boolean | undefined; +}; + +export interface Feature { + id: string; + prompt: string; + enabledHint?: string | undefined; + disabledHint?: string | undefined; +} diff --git a/packages/cli/src/top-level-briefs.ts b/packages/cli/src/top-level-briefs.ts index e111dd8149..9a4808be84 100644 --- a/packages/cli/src/top-level-briefs.ts +++ b/packages/cli/src/top-level-briefs.ts @@ -52,6 +52,7 @@ export const TOP_LEVEL_BRIEFS = { trace: "View distributed traces", trial: "Manage product trials", init: "Print instructions for a coding agent to set up Sentry", + wizard: "Set up the Sentry SDK in your project interactively", info: "Print configuration and verify authentication", local: "Sentry for local development", api: "Make an authenticated API request", diff --git a/packages/cli/test/commands/wizard.test.ts b/packages/cli/test/commands/wizard.test.ts new file mode 100644 index 0000000000..f320f998b9 --- /dev/null +++ b/packages/cli/test/commands/wizard.test.ts @@ -0,0 +1,131 @@ +/** + * Tests for `sentry wizard`: integration selection, the flags it passes to a + * wizard flow, and how a stopped wizard sets the exit code. + */ + +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +const { runNextjsWizard } = vi.hoisted(() => ({ + runNextjsWizard: vi.fn<(options: unknown) => Promise>(), +})); +vi.mock("../../src/lib/wizard/nextjs/nextjs-wizard.js", () => ({ + runNextjsWizard, +})); + +import { wizardCommand } from "../../src/commands/wizard.js"; +import type { SentryContext } from "../../src/context.js"; +import { ValidationError, WizardExitError } from "../../src/lib/errors.js"; +import type { Writer } from "../../src/types/index.js"; +import { loadCommand, useTestConfigDir } from "../helpers.js"; + +useTestConfigDir("wizard-test-"); + +const DEFAULT_FLAGS = { + saas: false, + debug: false, + spotlight: false, + "disable-telemetry": false, + "force-install": false, + "ignore-git-changes": false, + signup: false, + "skip-connect": false, + quiet: false, + uninstall: false, +}; + +async function runWizardCommand( + flags: Record = {}, +): Promise { + const context = { + process, + env: process.env, + stdout: { write: vi.fn(() => true) }, + stderr: { write: vi.fn(() => true) }, + stdin: process.stdin, + cwd: "/tmp", + homeDir: "/tmp", + configDir: "/tmp", + } as unknown as SentryContext; + const func = await loadCommand(wizardCommand); + await func.call(context, { ...DEFAULT_FLAGS, ...flags }); +} + +beforeEach(() => { + runNextjsWizard.mockReset(); + runNextjsWizard.mockResolvedValue(undefined); + process.exitCode = undefined; +}); + +afterEach(() => { + vi.unstubAllEnvs(); + process.exitCode = undefined; +}); + +describe("sentry wizard", () => { + test("runs the -i integration with the @sentry/wizard flags", async () => { + await runWizardCommand({ + integration: "nextjs", + org: "acme", + project: "web", + url: "https://sentry.example.com", + spotlight: true, + "force-install": true, + "ignore-git-changes": true, + "disable-telemetry": true, + "coming-from": "vercel", + }); + + expect(runNextjsWizard).toHaveBeenCalledWith({ + telemetryEnabled: false, + promoCode: undefined, + url: "https://sentry.example.com", + orgSlug: "acme", + projectSlug: "web", + saas: false, + forceInstall: true, + comingFrom: "vercel", + ignoreGitChanges: true, + spotlight: true, + }); + }); + + test("reads the integration and URL from SENTRY_WIZARD_* variables", async () => { + vi.stubEnv("SENTRY_WIZARD_INTEGRATION", "nextjs"); + vi.stubEnv("SENTRY_WIZARD_URL", "https://self-hosted.example.com"); + + await runWizardCommand(); + + expect(runNextjsWizard).toHaveBeenCalledWith( + expect.objectContaining({ url: "https://self-hosted.example.com" }), + ); + }); + + test("rejects an unknown SENTRY_WIZARD_INTEGRATION", async () => { + vi.stubEnv("SENTRY_WIZARD_INTEGRATION", "cobol"); + + await expect(runWizardCommand()).rejects.toThrow(ValidationError); + expect(runNextjsWizard).not.toHaveBeenCalled(); + }); + + test("reports an integration this version can't set up yet", async () => { + await expect(runWizardCommand({ integration: "remix" })).rejects.toThrow( + "The remix wizard is not available in this version yet.", + ); + }); + + test("exits with the wizard's code when it stops", async () => { + runNextjsWizard.mockRejectedValue(new WizardExitError(0)); + + await runWizardCommand({ integration: "nextjs" }); + + expect(process.exitCode).toBe(0); + }); + + test("exits with code 1 when the wizard can't continue", async () => { + runNextjsWizard.mockRejectedValue(new WizardExitError(1)); + + await runWizardCommand({ integration: "nextjs" }); + + expect(process.exitCode).toBe(1); + }); +}); diff --git a/packages/cli/test/lib/wizard/nextjs/templates.test.ts b/packages/cli/test/lib/wizard/nextjs/templates.test.ts new file mode 100644 index 0000000000..243b50328c --- /dev/null +++ b/packages/cli/test/lib/wizard/nextjs/templates.test.ts @@ -0,0 +1,963 @@ +import { describe, expect, it } from "vitest"; +import { + getNextjsConfigCjsAppendix, + getNextjsConfigCjsTemplate, + getNextjsConfigEsmCopyPasteSnippet, + getNextjsConfigMjsTemplate, + getRootLayout, + getSentryServersideConfigContents, + getInstrumentationClientFileContents, + getWithSentryConfigOptionsTemplate, + getGenerateMetadataSnippet, + getRootLayoutWithGenerateMetadata, + getSentryExamplePageContents, + getSentryExamplePagesDirApiRoute, + getSentryExampleAppDirApiRoute, +} from "../../../../src/lib/wizard/nextjs/templates.js"; + +describe("Next.js code templates", () => { + describe("getInstrumentationClientFileContents", () => { + it("generates client-side Sentry config with all features enabled", () => { + const template = getInstrumentationClientFileContents( + "my-dsn", + { + performance: true, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "// This file configures the initialization of Sentry on the client. + // The added config here will be used whenever a users loads a page in their browser. + // https://docs.sentry.io/platforms/javascript/guides/nextjs/ + + import * as Sentry from "@sentry/nextjs"; + + Sentry.init({ + dsn: "my-dsn", + + // Add optional integrations for additional features + integrations: [Sentry.replayIntegration()], + + // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control. + tracesSampleRate: 1, + + // Define how likely Replay events are sampled. + // 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, + + // Define how likely Replay events are sampled when an error occurs. + replaysOnErrorSampleRate: 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/nextjs/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + + export const onRouterTransitionStart = Sentry.captureRouterTransitionStart; + " + `); + }); + + it("generates client-side Sentry config with performance monitoring disabled", () => { + const template = getInstrumentationClientFileContents( + "my-dsn", + { + performance: false, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "// This file configures the initialization of Sentry on the client. + // The added config here will be used whenever a users loads a page in their browser. + // https://docs.sentry.io/platforms/javascript/guides/nextjs/ + + import * as Sentry from "@sentry/nextjs"; + + Sentry.init({ + dsn: "my-dsn", + + // Add optional integrations for additional features + integrations: [Sentry.replayIntegration()], + + // Define how likely Replay events are sampled. + // 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, + + // Define how likely Replay events are sampled when an error occurs. + replaysOnErrorSampleRate: 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/nextjs/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + + export const onRouterTransitionStart = Sentry.captureRouterTransitionStart; + " + `); + }); + + it("generates client-side Sentry config with session replay disabled", () => { + const template = getInstrumentationClientFileContents( + "my-dsn", + { + performance: true, + replay: false, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "// This file configures the initialization of Sentry on the client. + // The added config here will be used whenever a users loads a page in their browser. + // https://docs.sentry.io/platforms/javascript/guides/nextjs/ + + import * as Sentry from "@sentry/nextjs"; + + Sentry.init({ + dsn: "my-dsn", + + // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control. + tracesSampleRate: 1, + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + + export const onRouterTransitionStart = Sentry.captureRouterTransitionStart; + " + `); + }); + it("writes the active dataCollection preset when reduceDataCollection is true", () => { + const template = getInstrumentationClientFileContents( + "my-dsn", + { + performance: true, + replay: true, + }, + true, + ); + + expect(template).toContain("userInfo: false,"); + expect(template).toContain( + 'httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] },', + ); + expect(template).not.toContain("// userInfo: false,"); + expect(template).not.toContain( + "To disable sending user data and HTTP bodies", + ); + }); + + it("uses empty DSN in spotlight mode", () => { + const template = getInstrumentationClientFileContents( + "", + { + performance: true, + replay: false, + }, + false, + true, // spotlight + ); + + // Verify DSN is empty for spotlight + expect(template).toContain('dsn: ""'); + expect(template).toContain("spotlight: true"); + }); + }); + + describe("getSentryServersideConfigContents", () => { + describe("server-side", () => { + it("generates server-side Sentry config with all features enabled", () => { + const template = getSentryServersideConfigContents( + "my-dsn", + "server", + { + performance: true, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "// This file configures the initialization of Sentry on the server. + // The config you add here will be used whenever the server handles a request. + // https://docs.sentry.io/platforms/javascript/guides/nextjs/ + + import * as Sentry from "@sentry/nextjs"; + + Sentry.init({ + dsn: "my-dsn", + + // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control. + tracesSampleRate: 1, + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + " + `); + }); + + it("generates server-side Sentry config with performance monitoring disabled", () => { + const template = getSentryServersideConfigContents( + "my-dsn", + "server", + { + performance: false, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "// This file configures the initialization of Sentry on the server. + // The config you add here will be used whenever the server handles a request. + // https://docs.sentry.io/platforms/javascript/guides/nextjs/ + + import * as Sentry from "@sentry/nextjs"; + + Sentry.init({ + dsn: "my-dsn", + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + " + `); + }); + + it("generates server-side Sentry config with spotlight disabled", () => { + const template = getSentryServersideConfigContents( + "my-dsn", + "server", + { + performance: true, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "// This file configures the initialization of Sentry on the server. + // The config you add here will be used whenever the server handles a request. + // https://docs.sentry.io/platforms/javascript/guides/nextjs/ + + import * as Sentry from "@sentry/nextjs"; + + Sentry.init({ + dsn: "my-dsn", + + // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control. + tracesSampleRate: 1, + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + " + `); + }); + + it("writes the active dataCollection preset when reduceDataCollection is true", () => { + const template = getSentryServersideConfigContents( + "my-dsn", + "server", + { + performance: true, + replay: true, + }, + true, + ); + + expect(template).toContain("userInfo: false,"); + expect(template).toContain( + 'httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] },', + ); + expect(template).not.toContain("// userInfo: false,"); + expect(template).not.toContain( + "To disable sending user data and HTTP bodies", + ); + }); + + it("uses empty DSN in spotlight mode", () => { + const template = getSentryServersideConfigContents( + "", + "server", + { + performance: true, + replay: false, + }, + false, + true, // spotlight + ); + + // Verify DSN is empty for spotlight + expect(template).toContain('dsn: ""'); + expect(template).toContain("spotlight: true"); + }); + }); + + describe("edge", () => { + it("generates edge Sentry config with all features enabled", () => { + const template = getSentryServersideConfigContents( + "my-dsn", + "edge", + { + performance: true, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "// This file configures the initialization of Sentry for edge features (middleware, edge routes, and so on). + // The config you add here will be used whenever one of the edge features is loaded. + // Note that this config is unrelated to the Vercel Edge Runtime and is also required when running locally. + // https://docs.sentry.io/platforms/javascript/guides/nextjs/ + + import * as Sentry from "@sentry/nextjs"; + + Sentry.init({ + dsn: "my-dsn", + + // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control. + tracesSampleRate: 1, + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + " + `); + }); + + it("generates edge Sentry config with performance monitoring disabled", () => { + const template = getSentryServersideConfigContents( + "my-dsn", + "edge", + { + performance: false, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "// This file configures the initialization of Sentry for edge features (middleware, edge routes, and so on). + // The config you add here will be used whenever one of the edge features is loaded. + // Note that this config is unrelated to the Vercel Edge Runtime and is also required when running locally. + // https://docs.sentry.io/platforms/javascript/guides/nextjs/ + + import * as Sentry from "@sentry/nextjs"; + + Sentry.init({ + dsn: "my-dsn", + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + " + `); + }); + + it("writes the active dataCollection preset when reduceDataCollection is true", () => { + const template = getSentryServersideConfigContents( + "my-dsn", + "edge", + { + performance: true, + replay: true, + }, + true, + ); + + expect(template).toContain("userInfo: false,"); + expect(template).toContain( + 'httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] },', + ); + expect(template).not.toContain("// userInfo: false,"); + expect(template).not.toContain( + "To disable sending user data and HTTP bodies", + ); + }); + }); + }); + + describe("getWithSentryConfigOptionsTemplate", () => { + it("generates options for SaaS", () => { + const template = getWithSentryConfigOptionsTemplate({ + orgSlug: "my-org", + projectSlug: "my-project", + selfHosted: false, + sentryUrl: "https://dont-use-this-url.com", + tunnelRoute: true, + }); + + expect(template).toMatchInlineSnapshot(` + "{ + // For all available options, see: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/sourcemaps/uploading/bundler-plugin-options/ + + org: "my-org", + project: "my-project", + + // Only print logs for uploading source maps in CI + silent: !process.env.CI, + + // For all available options, see: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/ + + // Upload a larger set of source maps for prettier stack traces (increases build time) + widenClientFileUpload: true, + + // Route browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers. + // This can increase your server load as well as your hosting bill. + // Note: Check that the configured route will not match with your Next.js middleware, otherwise reporting of client- + // side errors will fail. + tunnelRoute: "/monitoring", + + webpack: { + // Enables automatic instrumentation of Vercel Cron Monitors. (Does not yet work with App Router route handlers.) + // See the following for more information: + // https://docs.sentry.io/product/crons/ + // https://vercel.com/docs/cron-jobs + automaticVercelMonitors: true, + + // Tree-shaking options for reducing bundle size + treeshake: { + // Automatically tree-shake Sentry logger statements to reduce bundle size + removeDebugLogging: true, + }, + }, + }" + `); + }); + + it("generates options for self-hosted", () => { + const template = getWithSentryConfigOptionsTemplate({ + orgSlug: "my-org", + projectSlug: "my-project", + selfHosted: true, + sentryUrl: "https://my-sentry.com", + tunnelRoute: true, + }); + + expect(template).toMatchInlineSnapshot(` + "{ + // For all available options, see: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/sourcemaps/uploading/bundler-plugin-options/ + + org: "my-org", + project: "my-project", + sentryUrl: "https://my-sentry.com", + + // Only print logs for uploading source maps in CI + silent: !process.env.CI, + + // For all available options, see: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/ + + // Upload a larger set of source maps for prettier stack traces (increases build time) + widenClientFileUpload: true, + + // Route browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers. + // This can increase your server load as well as your hosting bill. + // Note: Check that the configured route will not match with your Next.js middleware, otherwise reporting of client- + // side errors will fail. + tunnelRoute: "/monitoring", + + webpack: { + // Enables automatic instrumentation of Vercel Cron Monitors. (Does not yet work with App Router route handlers.) + // See the following for more information: + // https://docs.sentry.io/product/crons/ + // https://vercel.com/docs/cron-jobs + automaticVercelMonitors: true, + + // Tree-shaking options for reducing bundle size + treeshake: { + // Automatically tree-shake Sentry logger statements to reduce bundle size + removeDebugLogging: true, + }, + }, + }" + `); + }); + + it("comments out tunnelRoute if `tunnelRoute` option is disabled", () => { + const template = getWithSentryConfigOptionsTemplate({ + orgSlug: "my-org", + projectSlug: "my-project", + selfHosted: false, + sentryUrl: "https://dont-use-this-url.com", + tunnelRoute: false, + }); + + expect(template).toMatchInlineSnapshot(` + "{ + // For all available options, see: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/sourcemaps/uploading/bundler-plugin-options/ + + org: "my-org", + project: "my-project", + + // Only print logs for uploading source maps in CI + silent: !process.env.CI, + + // For all available options, see: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/ + + // Upload a larger set of source maps for prettier stack traces (increases build time) + widenClientFileUpload: true, + + // Uncomment to route browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers. + // This can increase your server load as well as your hosting bill. + // Note: Check that the configured route will not match with your Next.js middleware, otherwise reporting of client- + // side errors will fail. + // tunnelRoute: "/monitoring", + + webpack: { + // Enables automatic instrumentation of Vercel Cron Monitors. (Does not yet work with App Router route handlers.) + // See the following for more information: + // https://docs.sentry.io/product/crons/ + // https://vercel.com/docs/cron-jobs + automaticVercelMonitors: true, + + // Tree-shaking options for reducing bundle size + treeshake: { + // Automatically tree-shake Sentry logger statements to reduce bundle size + removeDebugLogging: true, + }, + }, + }" + `); + }); + }); + + describe("getRootLayout", () => { + it("generates a root layout component with types", () => { + expect(getRootLayout(true)).toMatchInlineSnapshot(` + "// This file was generated by the Sentry wizard because we couldn't find a root layout file. + // You can delete this file at any time. + + export const metadata = { + title: 'Sentry NextJS Example', + description: 'Generated by Sentry', + } + + export default function RootLayout({ + children, + }: { + children: React.ReactNode + }) { + return ( + + {children} + + ) + } + " + `); + }); + it("generates a root layout component without types", () => { + expect(getRootLayout(false)).toMatchInlineSnapshot(` + "// This file was generated by the Sentry wizard because we couldn't find a root layout file. + // You can delete this file at any time. + + export const metadata = { + title: 'Sentry NextJS Example', + description: 'Generated by Sentry', + } + + export default function RootLayout({ + children, + }) { + return ( + + {children} + + ) + } + " + `); + }); + }); + + describe("getGenerateMetadataSnippet", () => { + it("generates metadata snippet with TypeScript types", () => { + const template = getGenerateMetadataSnippet(true); + + expect(template).toMatchInlineSnapshot(` +" + import * as Sentry from '@sentry/nextjs'; + import type { Metadata } from 'next'; + + // Add or edit your "generateMetadata" to include the Sentry trace data: + export function generateMetadata(): Metadata { + return { + // ... your existing metadata + other: { + ...Sentry.getTraceData() + } + }; + } +" +`); + }); + + it("generates metadata snippet without TypeScript types", () => { + const template = getGenerateMetadataSnippet(false); + + expect(template).toMatchInlineSnapshot(` + " + import * as Sentry from '@sentry/nextjs'; + + + // Add or edit your "generateMetadata" to include the Sentry trace data: + export function generateMetadata() { + return { + // ... your existing metadata + other: { + ...Sentry.getTraceData() + } + }; + } + " + `); + }); + }); + + describe("getRootLayoutWithGenerateMetadata", () => { + it("generates root layout with TypeScript types", () => { + const template = getRootLayoutWithGenerateMetadata(true); + + expect(template).toMatchInlineSnapshot(` + "// This file was generated by the Sentry wizard because we couldn't find a root layout file. + import * as Sentry from '@sentry/nextjs'; + import type { Metadata } from 'next'; + + export function generateMetadata(): Metadata { + return { + other: { + ...Sentry.getTraceData(), + } + } + }; + + export default function RootLayout({ + children, + }: { + children: React.ReactNode + }) { + return ( + + {children} + + ) + } + " + `); + }); + + it("generates root layout without TypeScript types", () => { + const template = getRootLayoutWithGenerateMetadata(false); + + expect(template).toMatchInlineSnapshot(` + "// This file was generated by the Sentry wizard because we couldn't find a root layout file. + import * as Sentry from '@sentry/nextjs'; + + + export function generateMetadata() { + return { + other: { + ...Sentry.getTraceData(), + } + } + }; + + export default function RootLayout({ + children, + }) { + return ( + + {children} + + ) + } + " + `); + }); + }); + + describe("getSentryExamplePageContents", () => { + it("generates example page with TypeScript types", () => { + const template = getSentryExamplePageContents({ + selfHosted: false, + sentryUrl: "https://sentry.io", + orgSlug: "my-org", + projectId: "123", + useClient: true, + isTypeScript: true, + }); + + expect(template).toContain('"use client";'); + expect(template).toContain("constructor(message: string | undefined)"); + expect(template).toContain( + "class SentryExampleFrontendError extends Error", + ); + }); + + it("generates example page without TypeScript types", () => { + const template = getSentryExamplePageContents({ + selfHosted: false, + sentryUrl: "https://sentry.io", + orgSlug: "my-org", + projectId: "123", + useClient: true, + isTypeScript: false, + }); + + expect(template).toContain('"use client";'); + expect(template).toContain("constructor(message)"); + expect(template).toContain( + "class SentryExampleFrontendError extends Error", + ); + }); + + it("generates example page without useClient directive", () => { + const template = getSentryExamplePageContents({ + selfHosted: false, + sentryUrl: "https://sentry.io", + orgSlug: "my-org", + projectId: "123", + useClient: false, + isTypeScript: true, + }); + + expect(template).not.toContain('"use client";'); + expect(template).toContain( + "https://my-org.sentry.io/issues/?project=123", + ); + }); + + it("generates example page with logger calls", () => { + const template = getSentryExamplePageContents({ + selfHosted: false, + sentryUrl: "https://sentry.io", + orgSlug: "my-org", + projectId: "123", + useClient: true, + isTypeScript: true, + }); + + expect(template).toContain( + 'Sentry.logger.info("Sentry example page loaded")', + ); + expect(template).toContain( + 'Sentry.logger.info("User clicked the button, throwing a sample error")', + ); + }); + }); + + describe("getSentryExamplePagesDirApiRoute", () => { + it("generates Pages Router API route with TypeScript types", () => { + const template = getSentryExamplePagesDirApiRoute({ + isTypeScript: true, + }); + + expect(template).toContain("constructor(message: string | undefined)"); + expect(template).toContain("class SentryExampleAPIError extends Error"); + expect(template).toContain("export default function handler(_req, res)"); + }); + + it("generates Pages Router API route without TypeScript types", () => { + const template = getSentryExamplePagesDirApiRoute({ + isTypeScript: false, + }); + + expect(template).toContain("constructor(message)"); + expect(template).toContain("class SentryExampleAPIError extends Error"); + expect(template).toContain("export default function handler(_req, res)"); + }); + + it("generates Pages Router API route with logger calls", () => { + const template = getSentryExamplePagesDirApiRoute({ + isTypeScript: true, + }); + + expect(template).toContain('import * as Sentry from "@sentry/nextjs";'); + expect(template).toContain( + 'Sentry.logger.info("Sentry example API called")', + ); + }); + }); + + describe("getSentryExampleAppDirApiRoute", () => { + it("generates App Router API route with TypeScript types", () => { + const template = getSentryExampleAppDirApiRoute({ + isTypeScript: true, + dynamicStrategy: "force-dynamic", + }); + + expect(template).toContain("constructor(message: string | undefined)"); + expect(template).toContain("class SentryExampleAPIError extends Error"); + expect(template).toContain("export function GET()"); + expect(template).toContain('export const dynamic = "force-dynamic";'); + }); + + it("generates App Router API route without TypeScript types", () => { + const template = getSentryExampleAppDirApiRoute({ + isTypeScript: false, + dynamicStrategy: "force-dynamic", + }); + + expect(template).toContain("constructor(message)"); + expect(template).toContain("class SentryExampleAPIError extends Error"); + expect(template).toContain("export function GET()"); + expect(template).toContain('export const dynamic = "force-dynamic";'); + }); + + it("generates App Router API route with logger calls", () => { + const template = getSentryExampleAppDirApiRoute({ + isTypeScript: true, + dynamicStrategy: "force-dynamic", + }); + + expect(template).toContain('import * as Sentry from "@sentry/nextjs";'); + expect(template).toContain( + 'Sentry.logger.info("Sentry example API called")', + ); + }); + + it("uses connection() instead of route segment config for the connection strategy", () => { + // Next.js 16 with `cacheComponents` rejects route segment config and + // prerenders route handlers unless they opt into request-time rendering. + const template = getSentryExampleAppDirApiRoute({ + isTypeScript: true, + dynamicStrategy: "connection", + }); + + expect(template).not.toContain("force-dynamic"); + expect(template).not.toContain("export const dynamic"); + expect(template).toContain('import { connection } from "next/server";'); + expect(template).toContain("export async function GET()"); + expect(template).toContain("await connection();"); + expect(template).toContain( + 'Sentry.logger.info("Sentry example API called")', + ); + }); + }); + + describe("next.config templates", () => { + const options = '{ org: "my-org", project: "my-project" }'; + + it("CJS template imports withSentryConfig from @sentry/nextjs/config", () => { + const template = getNextjsConfigCjsTemplate(options); + expect(template).toContain( + 'const { withSentryConfig } = require("@sentry/nextjs/config");', + ); + expect(template).toContain( + `module.exports = withSentryConfig(nextConfig, ${options});`, + ); + }); + + it("MJS template imports withSentryConfig from @sentry/nextjs/config", () => { + const template = getNextjsConfigMjsTemplate(options); + expect(template).toContain( + 'import { withSentryConfig } from "@sentry/nextjs/config";', + ); + expect(template).toContain( + `export default withSentryConfig(nextConfig, ${options});`, + ); + }); + + it("CJS appendix imports withSentryConfig from @sentry/nextjs/config", () => { + const template = getNextjsConfigCjsAppendix(options); + expect(template).toContain( + 'const { withSentryConfig } = require("@sentry/nextjs/config");', + ); + expect(template).toContain( + `module.exports = withSentryConfig(module.exports, ${options});`, + ); + }); + + it("ESM copy-paste snippet imports withSentryConfig from @sentry/nextjs/config", () => { + const template = getNextjsConfigEsmCopyPasteSnippet(options); + expect(template).toContain( + 'import { withSentryConfig } from "@sentry/nextjs/config";', + ); + expect(template).toContain( + `export default withSentryConfig(yourNextConfig, ${options});`, + ); + }); + + it("uses the root export when an older SDK requires it", () => { + const cjs = getNextjsConfigCjsTemplate(options, "@sentry/nextjs"); + const mjs = getNextjsConfigMjsTemplate(options, "@sentry/nextjs"); + const appendix = getNextjsConfigCjsAppendix(options, "@sentry/nextjs"); + const snippet = getNextjsConfigEsmCopyPasteSnippet( + options, + "@sentry/nextjs", + ); + + expect(cjs).toContain( + 'const { withSentryConfig } = require("@sentry/nextjs");', + ); + expect(mjs).toContain( + 'import { withSentryConfig } from "@sentry/nextjs";', + ); + expect(appendix).toContain( + 'const { withSentryConfig } = require("@sentry/nextjs");', + ); + expect(snippet).toContain( + 'import { withSentryConfig } from "@sentry/nextjs";', + ); + for (const template of [cjs, mjs, appendix, snippet]) { + expect(template).not.toContain("@sentry/nextjs/config"); + } + }); + + it("never references the root @sentry/nextjs export for withSentryConfig by default", () => { + for (const template of [ + getNextjsConfigCjsTemplate(options), + getNextjsConfigMjsTemplate(options), + getNextjsConfigCjsAppendix(options), + getNextjsConfigEsmCopyPasteSnippet(options), + ]) { + expect(template).not.toMatch(/["']@sentry\/nextjs["']/); + } + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/nextjs/utils.test.ts b/packages/cli/test/lib/wizard/nextjs/utils.test.ts new file mode 100644 index 0000000000..df026e57ed --- /dev/null +++ b/packages/cli/test/lib/wizard/nextjs/utils.test.ts @@ -0,0 +1,232 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import type { Mock } from "vitest"; +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as fs from "node:fs"; +import { parseModule } from "magicast"; +import { + addWithSentryConfigImport, + getNextJsVersionBucket, + getMaybeAppDirLocation, + hasRootLayoutFile, + getExampleApiRouteDynamicStrategy, + getWithSentryConfigImportPath, + isNextJsVersionSupported, +} from "../../../../src/lib/wizard/nextjs/utils.js"; + +vi.mock("node:fs", async (importOriginal) => ({ + ...(await importOriginal()), + existsSync: vi.fn(), + lstatSync: vi.fn(), +})); + +describe("Next.js Utils", () => { + describe("getNextJsVersionBucket", () => { + it('returns "none" for undefined version', () => { + expect(getNextJsVersionBucket(undefined)).toBe("none"); + }); + + it('returns "<11.0.0" for versions below 11', () => { + expect(getNextJsVersionBucket("10.0.0")).toBe("<11.0.0"); + }); + + it("returns major version for versions 11 and above", () => { + expect(getNextJsVersionBucket("11.0.0")).toBe("11.x"); + expect(getNextJsVersionBucket("11.2.5")).toBe("11.x"); + expect(getNextJsVersionBucket("13.5.2")).toBe("13.x"); + expect(getNextJsVersionBucket("14.0.0")).toBe("14.x"); + }); + }); + + describe("getMaybeAppDirLocation", () => { + const mockCwd = "/mock/cwd"; + let originalCwd: () => string; + + beforeEach(() => { + originalCwd = process.cwd; + process.cwd = vi.fn(() => mockCwd); + vi.clearAllMocks(); + }); + + afterEach(() => { + process.cwd = originalCwd; + }); + + it('returns ["app"] when app directory exists in root', () => { + (fs.existsSync as Mock).mockImplementation((filePath: string) => { + return filePath === "/mock/cwd/app"; + }); + (fs.lstatSync as Mock).mockImplementation((filePath: string) => ({ + isDirectory: () => filePath === "/mock/cwd/app", + })); + + expect(getMaybeAppDirLocation()).toEqual(["app"]); + }); + + it('returns ["src", "app"] when app directory exists in src', () => { + (fs.existsSync as Mock).mockImplementation((filePath: string) => { + return filePath === "/mock/cwd/src/app"; + }); + (fs.lstatSync as Mock).mockImplementation((filePath: string) => ({ + isDirectory: () => filePath === "/mock/cwd/src/app", + })); + + expect(getMaybeAppDirLocation()).toEqual(["src", "app"]); + }); + + it("returns undefined when no app directory exists", () => { + (fs.existsSync as Mock).mockReturnValue(false); + + expect(getMaybeAppDirLocation()).toBeUndefined(); + }); + }); + + describe("hasRootLayoutFile", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("returns true when layout file exists with any supported extension", () => { + const mockAppFolderPath = "/mock/app"; + const supportedExtensions = ["jsx", "tsx", "js"]; + + supportedExtensions.forEach((ext) => { + (fs.existsSync as Mock).mockImplementation((filePath: string) => { + return filePath === `/mock/app/layout.${ext}`; + }); + + expect(hasRootLayoutFile(mockAppFolderPath)).toBe(true); + }); + }); + + it("returns false when no layout file exists", () => { + const mockAppFolderPath = "/mock/app"; + (fs.existsSync as Mock).mockReturnValue(false); + + expect(hasRootLayoutFile(mockAppFolderPath)).toBe(false); + }); + }); + + describe("isNextJsVersionSupported", () => { + it.each(["14.0.0", "^14.2.0", "15.5.21", "~16.2.0", "17.0.0-canary.1"])( + "returns true for %s", + (version) => { + expect(isNextJsVersionSupported(version)).toBe(true); + }, + ); + + it.each(["13.5.6", "^13.0.0", "12.3.4", "11.0.0"])( + "returns false for %s", + (version) => { + expect(isNextJsVersionSupported(version)).toBe(false); + }, + ); + + it.each([undefined, "latest", "not-a-version"])( + "returns true when the version is unknown (%s)", + (version) => { + expect(isNextJsVersionSupported(version)).toBe(true); + }, + ); + }); + + describe("getExampleApiRouteDynamicStrategy", () => { + it.each(["14.2.35", "^14.0.0", "13.5.6"])( + "returns force-dynamic for %s", + (version) => { + expect(getExampleApiRouteDynamicStrategy(version)).toBe( + "force-dynamic", + ); + }, + ); + + it.each(["15.0.0", "^15.5.0", "16.2.11", "~16.0.0", "17.0.0-canary.1"])( + "returns connection for %s", + (version) => { + expect(getExampleApiRouteDynamicStrategy(version)).toBe("connection"); + }, + ); + + it.each([undefined, "latest", "not-a-version"])( + "falls back to force-dynamic when the version is unknown (%s)", + (version) => { + expect(getExampleApiRouteDynamicStrategy(version)).toBe( + "force-dynamic", + ); + }, + ); + }); + + describe("getWithSentryConfigImportPath", () => { + it.each(["10.73.0", "^10.73.0", "10.74.0", "^11.0.0", "11.0.0-beta.2"])( + "returns the /config subpath for %s", + (version) => { + expect(getWithSentryConfigImportPath(version)).toBe( + "@sentry/nextjs/config", + ); + }, + ); + + it.each(["10.72.0", "^10.0.0", "~10.50.0", "9.47.1", "8.55.2"])( + "falls back to the root export for %s", + (version) => { + expect(getWithSentryConfigImportPath(version)).toBe("@sentry/nextjs"); + }, + ); + + it.each([undefined, "latest", "not-a-version", "workspace:*"])( + "returns the /config subpath when the version is unknown (%s)", + (version) => { + expect(getWithSentryConfigImportPath(version)).toBe( + "@sentry/nextjs/config", + ); + }, + ); + }); + + describe("addWithSentryConfigImport", () => { + it("uses the given import path", () => { + const mod = parseModule("export default {};"); + + addWithSentryConfigImport(mod, "@sentry/nextjs"); + + expect(mod.generate().code).toContain( + 'import {withSentryConfig} from "@sentry/nextjs";', + ); + }); + + it("adds the import from @sentry/nextjs/config when none exists", () => { + const mod = parseModule("export default {};"); + + addWithSentryConfigImport(mod); + + expect(mod.generate().code).toContain( + 'import {withSentryConfig} from "@sentry/nextjs/config";', + ); + }); + + it("rewrites an existing import from the root @sentry/nextjs export", () => { + const mod = parseModule( + 'import { withSentryConfig } from "@sentry/nextjs";\nexport default withSentryConfig({});', + ); + + addWithSentryConfigImport(mod); + + const code = mod.generate().code; + expect(code.match(/withSentryConfig.*from/g)).toHaveLength(1); + expect(code).toContain('from "@sentry/nextjs/config"'); + expect(code).not.toContain('from "@sentry/nextjs"'); + }); + + it("leaves an existing import from @sentry/nextjs/config untouched", () => { + const mod = parseModule( + 'import { withSentryConfig } from "@sentry/nextjs/config";\nexport default withSentryConfig({});', + ); + + addWithSentryConfigImport(mod); + + expect(mod.generate().code.match(/withSentryConfig.*from/g)).toHaveLength( + 1, + ); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/nextjs/wizard-double-wrap-prevention.test.ts b/packages/cli/test/lib/wizard/nextjs/wizard-double-wrap-prevention.test.ts new file mode 100644 index 0000000000..fd2a2c67ed --- /dev/null +++ b/packages/cli/test/lib/wizard/nextjs/wizard-double-wrap-prevention.test.ts @@ -0,0 +1,300 @@ +import { describe, it, expect, vi } from "vitest"; +import { generateCode, parseModule } from "magicast"; +import { getWithSentryConfigOptionsTemplate } from "../../../../src/lib/wizard/nextjs/templates.js"; +import { + unwrapSentryConfigAst, + wrapWithSentryConfig, +} from "../../../../src/lib/wizard/nextjs/utils.js"; + +vi.mock("../../../../src/lib/wizard/utils/clack/mcp-config.js", () => ({ + offerProjectScopedMcpConfig: vi.fn().mockResolvedValue(undefined), +})); + +describe("Next.js wizard double wrap prevention", () => { + const mockWithSentryConfigOptionsTemplate = + getWithSentryConfigOptionsTemplate({ + orgSlug: "test-org", + projectSlug: "test-project", + selfHosted: false, + sentryUrl: "https://sentry.io", + tunnelRoute: false, + }); + + describe("unwrapSentryConfigAst utility function", () => { + describe("AST-based expression unwrapping", () => { + it("keeps code without withSentryConfig", () => { + const mod = parseModule("export default nextConfig"); + const originalAST = mod.exports["default"].$ast; + const resultAST = unwrapSentryConfigAst(originalAST); + expect(resultAST).toBe(originalAST); + const { code: exportDefaultCode } = generateCode({ $ast: resultAST }); + expect(exportDefaultCode).toMatchInlineSnapshot(`"nextConfig"`); + }); + + it("should handle plain object literal exports", () => { + const mod = parseModule( + `export default { nextConfig: { randomValue: true } }`, + ); + const originalAST = mod.exports["default"].$ast; + const resultAST = unwrapSentryConfigAst(originalAST); + + expect(resultAST).toBe(originalAST); + expect(resultAST.type).toBe("ObjectExpression"); + expect(resultAST).toHaveProperty("properties.length", 1); + }); + + it("should unwrap withSentryConfig with options", () => { + const mod = parseModule( + 'export default withSentryConfig(nextConfig, { org: "test" })', + ); + const wrappedAst = mod.exports["default"].$ast; + const resultAST = unwrapSentryConfigAst(wrappedAst); + const { code: exportDefaultCode } = generateCode({ $ast: resultAST }); + + expect(exportDefaultCode).toMatchInlineSnapshot(`"nextConfig"`); + }); + + it("should unwrap withSentryConfig without options", () => { + const mod = parseModule("export default withSentryConfig(nextConfig)"); + const wrappedAst = mod.exports["default"].$ast; + const resultAST = unwrapSentryConfigAst(wrappedAst); + const { code: exportDefaultCode } = generateCode({ $ast: resultAST }); + + expect(exportDefaultCode).toMatchInlineSnapshot(`"nextConfig"`); + }); + + it("should handle nested withSentryConfig calls", () => { + const mod = parseModule( + 'export default withSentryConfig(withSentryConfig(nextConfig, { org: "inner" }), { org: "outer" })', + ); + const wrappedAst = mod.exports["default"].$ast; + const resultAST = unwrapSentryConfigAst(wrappedAst); + + // Should unwrap one level and return the inner withSentryConfig call + expect(resultAST.type).toBe("CallExpression"); + expect(resultAST).toHaveProperty("callee.name", "withSentryConfig"); + const { code: exportDefaultCode } = generateCode({ $ast: resultAST }); + + expect(exportDefaultCode).toMatchInlineSnapshot( + `"withSentryConfig(nextConfig, { org: "inner" })"`, + ); + }); + + it("should handle complex expressions", () => { + const mod = parseModule( + "export default withSentryConfig(someComplexExpression.withMethods())", + ); + const wrappedAst = mod.exports["default"].$ast; + const resultAST = unwrapSentryConfigAst(wrappedAst); + const { code: exportDefaultCode } = generateCode({ $ast: resultAST }); + + expect(exportDefaultCode).toMatchInlineSnapshot( + `"someComplexExpression.withMethods()"`, + ); + }); + + it("should handle object literals", () => { + const mod = parseModule( + 'export default withSentryConfig({ next: "config", obj: { next: "nested" } }, { org: "test" })', + ); + const wrappedAst = mod.exports["default"].$ast; + const resultAST = unwrapSentryConfigAst(wrappedAst); + const { code: exportDefaultCode } = generateCode({ $ast: resultAST }); + + expect(exportDefaultCode).toMatchInlineSnapshot( + `"{ next: "config", obj: { next: "nested" } }"`, + ); + }); + + it("should return unchanged if not a withSentryConfig call", () => { + const mod = parseModule("export default someOtherFunction(nextConfig)"); + const originalAST = mod.exports["default"].$ast; + const resultAST = unwrapSentryConfigAst(originalAST); + + expect(resultAST).toBe(originalAST); + }); + }); + }); + + describe("MJS/TS files", () => { + it("should unwrap existing withSentryConfig and re-wrap with new config using AST", () => { + const existingMjsContent = `import { withSentryConfig } from "@sentry/nextjs"; + +const nextConfig = {}; + +export default withSentryConfig(nextConfig, { + org: "old-org", + project: "old-project", +});`; + + const mod = parseModule(existingMjsContent); + const originalAST = mod.exports["default"].$ast; + const unwrappedAst = unwrapSentryConfigAst(originalAST); + // Verify it returns the first argument (nextConfig identifier) + expect(unwrappedAst.type).toBe("Identifier"); + expect(unwrappedAst).toHaveProperty("name", "nextConfig"); + + // Create a fresh module to simulate the re-wrapping process + const freshMod = + parseModule(`import { withSentryConfig } from "@sentry/nextjs"; + +const nextConfig = {}; + +export default nextConfig;`); + + // Apply wrapping + freshMod.exports["default"] = wrapWithSentryConfig( + freshMod.exports["default"], + mockWithSentryConfigOptionsTemplate, + ); + + const newCode = freshMod.generate().code; + + // Verify only one withSentryConfig call exists + const withSentryConfigMatches = newCode.match(/withSentryConfig\s*\(/g); + expect(withSentryConfigMatches).toHaveLength(1); + + expect(newCode).toContain("test-org"); + expect(newCode).toContain("test-project"); + expect(newCode).not.toContain("old-org"); + expect(newCode).not.toContain("old-project"); + }); + + it("should handle complex nested configurations using AST", () => { + const existingMjsContent = `import { withSentryConfig } from "@sentry/nextjs"; + +const nextConfig = { experimental: { appDir: true } }; + +export default withSentryConfig( + withSentryConfig(nextConfig, { org: "nested-org" }), + { org: "outer-org" } +);`; + + const mod = parseModule(existingMjsContent); + + // First unwrap ---- + const firstUnwrapAST = unwrapSentryConfigAst(mod.exports["default"].$ast); + expect(firstUnwrapAST.type).toBe("CallExpression"); + expect(firstUnwrapAST).toHaveProperty("callee.name", "withSentryConfig"); + + const { code: exportDefaultCode1 } = generateCode({ + $ast: firstUnwrapAST, + }); + expect(exportDefaultCode1).toMatchInlineSnapshot( + `"withSentryConfig(nextConfig, { org: "nested-org" })"`, + ); + + // Second unwrap ---- + const secondUnwrapAST = unwrapSentryConfigAst(firstUnwrapAST); + expect(secondUnwrapAST.type).toBe("Identifier"); + expect(secondUnwrapAST).toHaveProperty("name", "nextConfig"); + + const { code: exportDefaultCode2 } = generateCode({ + $ast: secondUnwrapAST, + }); + + expect(exportDefaultCode2).toMatchInlineSnapshot(`"nextConfig"`); + }); + + it("should handle simple export without existing withSentryConfig using AST", () => { + const simpleMjsContent = `const nextConfig = {}; + +export default nextConfig;`; + + const mod = parseModule(simpleMjsContent); + const originalAST = mod.exports["default"].$ast; + const unwrappedAst = unwrapSentryConfigAst(originalAST); + expect(unwrappedAst).toBe(originalAST); + mod.exports["default"] = wrapWithSentryConfig( + mod.exports["default"], + mockWithSentryConfigOptionsTemplate, + ); + + const newCode = mod.generate().code; + + // Should have exactly one withSentryConfig call + const withSentryConfigMatches = newCode.match(/withSentryConfig\s*\(/g); + expect(withSentryConfigMatches).toHaveLength(1); + + // Not an inline snapshot: interpolating a shared constant defeats + // vitest's indentation detection for inline snapshots. + expect(newCode).toBe(`const nextConfig = {}; + +export default withSentryConfig(nextConfig, ${sentryOptionsSnapshot});`); + }); + + it("should handle withSentryConfig(nextConfig) without options using AST", () => { + const existingMjsContent = `import { withSentryConfig } from "@sentry/nextjs"; + +const nextConfig = {}; + +export default withSentryConfig(nextConfig);`; + + const mod = parseModule(existingMjsContent); + const originalAST = mod.exports["default"].$ast; + const unwrappedAst = unwrapSentryConfigAst(originalAST); + // Verify it returns the first argument (nextConfig identifier) + expect(unwrappedAst.type).toBe("Identifier"); + expect(unwrappedAst).toHaveProperty("name", "nextConfig"); + + // Simulate the re-wrapping process + const freshMod = + parseModule(`import { withSentryConfig } from "@sentry/nextjs"; + +const nextConfig = {}; + +export default nextConfig;`); + freshMod.exports["default"] = wrapWithSentryConfig( + freshMod.exports["default"], + mockWithSentryConfigOptionsTemplate, + ); + + const newCode = freshMod.generate().code; + + // Should have exactly one withSentryConfig call + const withSentryConfigMatches = newCode.match(/withSentryConfig\s*\(/g); + expect(withSentryConfigMatches).toHaveLength(1); + + expect(newCode).not.toContain("withSentryConfig(withSentryConfig("); + expect(newCode).toMatch(/withSentryConfig\s*\(\s*nextConfig\s*,/); + }); + }); +}); + +const sentryOptionsSnapshot = `{ + // For all available options, see: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/sourcemaps/uploading/bundler-plugin-options/ + + org: "test-org", + + project: "test-project", + + // Only print logs for uploading source maps in CI + silent: !process.env.CI, + + // For all available options, see: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/ + + // Upload a larger set of source maps for prettier stack traces (increases build time) + widenClientFileUpload: true, + + // Uncomment to route browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers. + // This can increase your server load as well as your hosting bill. + // Note: Check that the configured route will not match with your Next.js middleware, otherwise reporting of client- + // side errors will fail. + // tunnelRoute: "/monitoring", + + webpack: { + // Enables automatic instrumentation of Vercel Cron Monitors. (Does not yet work with App Router route handlers.) + // See the following for more information: + // https://docs.sentry.io/product/crons/ + // https://vercel.com/docs/cron-jobs + automaticVercelMonitors: true, + + // Tree-shaking options for reducing bundle size + treeshake: { + // Automatically tree-shake Sentry logger statements to reduce bundle size + removeDebugLogging: true, + }, + } +}`; diff --git a/packages/cli/test/lib/wizard/utils/clack/index.test.ts b/packages/cli/test/lib/wizard/utils/clack/index.test.ts new file mode 100644 index 0000000000..cf8b7c62b8 --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/clack/index.test.ts @@ -0,0 +1,719 @@ +import { + abort, + askForToolConfigPath, + confirmContinueIfNoOrDirtyGitRepo, + createNewConfigFile, + getPackageManager, + installPackage, + printSdkV11MigrationGuideIfOutdated, +} from "../../../../../src/lib/wizard/utils/clack/index.js"; +import { WizardExitError } from "../../../../../src/lib/errors.js"; + +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as fs from "node:fs"; +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as ChildProcess from "node:child_process"; +import type { PackageManager } from "../../../../../src/lib/wizard/utils/package-manager.js"; +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as PackageManagerUtils from "../../../../../src/lib/wizard/utils/package-manager.js"; +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as GitUtils from "../../../../../src/lib/wizard/utils/git.js"; + +import { + NPM, + PNPM, + YARN_V1, + YARN_V2, +} from "../../../../../src/lib/wizard/utils/package-manager.js"; + +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as clack from "@clack/prompts"; + +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as Sentry from "@sentry/node"; + +import { + vi, + it, + describe, + expect, + beforeEach, + type Mocked, + type Mock, + type MockInstance, + afterEach, +} from "vitest"; + +vi.mock("node:child_process", async () => ({ + __esModule: true, + ...(await vi.importActual("node:child_process")), +})); + +vi.mock("node:fs", async () => ({ + __esModule: true, + ...(await vi.importActual("node:fs")), +})); + +vi.mock("@clack/prompts", () => ({ + log: { + info: vi.fn(), + success: vi.fn(), + warn: vi.fn(), + error: 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(), +})); +const clackMock = clack as Mocked; + +vi.mock("../../../../../src/lib/wizard/utils/git.js", () => ({ + isInGitRepo: vi.fn(), + getUncommittedOrUntrackedFilePaths: vi.fn(), +})); + +vi.mock("@sentry/node", async () => { + const actual = + await vi.importActual("@sentry/node"); + return { + ...actual, + setTag: vi.fn(), + captureException: vi.fn(() => "id"), + }; +}); + +function mockUserResponse(fn: Mock, response: unknown) { + fn.mockReturnValueOnce(response); +} + +describe("askForToolConfigPath", () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + it("returns undefined if users have no config file", async () => { + mockUserResponse(clack.confirm as Mock, false); + + const result = await askForToolConfigPath("Webpack", "webpack.config.js"); + + expect(clack.confirm).toHaveBeenCalledWith( + expect.objectContaining({ + message: expect.stringContaining("have a Webpack config file"), + }), + ); + + expect(result).toBeUndefined(); + }); + + it("returns the path if users have a config file and the entered path is valid", async () => { + mockUserResponse(clack.confirm as Mock, true); + mockUserResponse(clack.text as Mock, "my.webpack.config.js"); + + const result = await askForToolConfigPath("Webpack", "webpack.config.js"); + + expect(clack.confirm).toHaveBeenCalledWith( + expect.objectContaining({ + message: expect.stringContaining("have a Webpack config file"), + }), + ); + + expect(clack.text).toHaveBeenCalledWith( + expect.objectContaining({ + message: expect.stringContaining( + "enter the path to your Webpack config file", + ), + }), + ); + + expect(result).toBe("my.webpack.config.js"); + }); +}); + +describe("createNewConfigFile", () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + it("writes the file to disk and returns true if the file was created successfully", async () => { + const writeFileSpy = vi + .spyOn(fs.promises, "writeFile") + .mockImplementation(vi.fn()); + + const filename = "/webpack.config.js"; + const code = "module.exports = {/*config...*/}"; + + const result = await createNewConfigFile(filename, code); + + expect(result).toBe(true); + expect(writeFileSpy).toHaveBeenCalledWith(filename, code); + }); + + it("logs more information if provided as an argument", async () => { + vi.spyOn(fs.promises, "writeFile").mockImplementation(vi.fn()); + + const filename = "/webpack.config.js"; + const code = "module.exports = {/*config...*/}"; + const moreInfo = "More information..."; + + await createNewConfigFile(filename, code, moreInfo); + + expect(clack.log.info).toHaveBeenCalledTimes(1); + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining(moreInfo), + ); + }); + + it("returns false and logs a warning if the file could not be created", async () => { + const writeFileSpy = vi + .spyOn(fs.promises, "writeFile") + .mockImplementation(() => Promise.reject(new Error("Could not write"))); + + const filename = "/webpack.config.js"; + const code = "module.exports = {/*config...*/}"; + + const result = await createNewConfigFile(filename, code); + + expect(result).toBe(false); + expect(writeFileSpy).toHaveBeenCalledWith(filename, code); + expect(clack.log.warn).toHaveBeenCalledTimes(1); + }); + + it("returns false if the passed path is not absolute", async () => { + const result = await createNewConfigFile( + "./relative/webpack.config.js", + "", + ); + + expect(result).toBe(false); + }); +}); + +describe("installPackage", () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + const spawnSpy = vi.spyOn(ChildProcess, "spawn").mockImplementation(() => ({ + // @ts-expect-error - not passing the full object but directly resolving + // to simulate a successful install + on: vi.fn((evt: string, cb: (args) => void) => { + if (evt === "close") { + cb(0); + } + }), + // @ts-expect-error - this is fine + stdout: { on: vi.fn() }, + // @ts-expect-error - this is fine + stderr: { on: vi.fn() }, + })); + + it("force-installs a package if the forceInstall flag is set", async () => { + const packageManagerMock: PackageManager = { + name: "npm", + label: "NPM", + installCommand: "install", + buildCommand: "npm run build", + runScriptCommand: "npm run", + flags: "", + forceInstallFlag: "--force", + detect: vi.fn(), + addOverride: vi.fn(), + }; + + await installPackage({ + alreadyInstalled: false, + packageName: "@some/package", + packageNameDisplayLabel: "@some/package", + forceInstall: true, + askBeforeUpdating: false, + packageManager: packageManagerMock, + }); + + expect(spawnSpy).toHaveBeenCalledWith( + "npm", + ["install", "@some/package", "--force"], + { shell: true, stdio: ["pipe", "pipe", "pipe"] }, + ); + }); + + it.each([false, undefined])( + "doesn't force-install a package if the forceInstall flag is %s", + async (flag) => { + const packageManagerMock: PackageManager = { + name: "npm", + label: "NPM", + installCommand: "install", + buildCommand: "npm run build", + runScriptCommand: "npm run", + flags: "", + forceInstallFlag: "--force", + detect: vi.fn(), + addOverride: vi.fn(), + }; + + await installPackage({ + alreadyInstalled: false, + packageName: "@sentry/sveltekit", + packageNameDisplayLabel: "@sentry/sveltekit", + forceInstall: flag, + askBeforeUpdating: false, + packageManager: packageManagerMock, + }); + + expect(spawnSpy).toHaveBeenCalledWith( + "npm", + ["install", "@sentry/sveltekit"], + { shell: true, stdio: ["pipe", "pipe", "pipe"] }, + ); + }, + ); + + it("adds install flags if defined", async () => { + const packageManagerMock: PackageManager = { + name: "npm", + label: "NPM", + installCommand: "install", + buildCommand: "npm run build", + runScriptCommand: "npm run", + flags: "--ignore-workspace-root-check", + forceInstallFlag: "--force", + detect: vi.fn(), + addOverride: vi.fn(), + }; + + await installPackage({ + alreadyInstalled: false, + packageName: "@some/package", + packageNameDisplayLabel: "@some/package", + forceInstall: true, + askBeforeUpdating: false, + packageManager: packageManagerMock, + }); + + expect(spawnSpy).toHaveBeenCalledWith( + "npm", + + ["install", "@some/package", "--ignore-workspace-root-check", "--force"], + { shell: true, stdio: ["pipe", "pipe", "pipe"] }, + ); + }); + + it("irgnores stdout when installing with Yarn", async () => { + await installPackage({ + alreadyInstalled: false, + packageName: "@sentry/nextjs", + askBeforeUpdating: false, + packageManager: YARN_V2, + }); + + expect(spawnSpy).toHaveBeenCalledWith("yarn", ["add", "@sentry/nextjs"], { + shell: true, + stdio: ["pipe", "ignore", "pipe"], + }); + }); + + it("shows pnpm 11 build approval guidance before installation", async () => { + await installPackage({ + alreadyInstalled: false, + packageName: "@sentry/nextjs", + askBeforeUpdating: false, + packageManager: PNPM, + }); + + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining("pnpm approve-builds"), + ); + }); + + it("writes package manager stdout to the error log file", async () => { + const output = "ERR_PNPM_IGNORED_BUILDS Ignored build scripts: sharp"; + const writeFileSpy = vi + .spyOn(fs, "writeFileSync") + .mockImplementation(vi.fn()); + const dateSpy = vi.spyOn(Date, "now").mockReturnValue(123); + const cwdSpy = vi.spyOn(process, "cwd").mockReturnValue("/project"); + const exitSpy = vi.spyOn(process, "exit").mockImplementation(() => { + throw new Error("exit"); + }); + spawnSpy.mockImplementationOnce(() => ({ + stdout: { + on: vi.fn( + ( + _event: string, + callback: ((data: string) => void) | (() => void), + ) => { + callback(output); + }, + ), + } as unknown as ChildProcess.ChildProcess["stdout"], + // @ts-expect-error - not passing the full ChildProcess object + stderr: { on: vi.fn() }, + // @ts-expect-error - not passing the full ChildProcess object + on: vi.fn( + (event: "error" | "close", callback: (code: number) => void) => { + if (event === "close") { + callback(1); + } + }, + ), + })); + + await expect( + installPackage({ + alreadyInstalled: false, + packageName: "@sentry/nextjs@^10", + askBeforeUpdating: false, + packageManager: PNPM, + }), + ).rejects.toThrow(WizardExitError); + + expect(writeFileSpy).toHaveBeenCalledWith( + "/project/sentry-wizard-installation-error-123.log", + output, + { encoding: "utf8" }, + ); + expect(clack.log.error).toHaveBeenCalledWith( + expect.not.stringContaining(output), + ); + expect(clack.log.error).toHaveBeenCalledWith( + expect.stringContaining("sentry-wizard-installation-error-*.log"), + ); + + writeFileSpy.mockRestore(); + dateSpy.mockRestore(); + cwdSpy.mockRestore(); + exitSpy.mockRestore(); + }); +}); + +describe("printSdkV11MigrationGuideIfOutdated", () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + it.each(["^10.0.0", "10.5.2", "~9.1.0", ">=8.0.0 <11.0.0"])( + "warns and links the migration guide for the installed range %s", + (version) => { + printSdkV11MigrationGuideIfOutdated("@sentry/nextjs", { + dependencies: { "@sentry/nextjs": version }, + }); + + expect(clackMock.log.warn).toHaveBeenCalledTimes(1); + expect(clackMock.log.warn).toHaveBeenCalledWith( + expect.stringContaining( + "https://docs.sentry.io/platforms/javascript/guides/nextjs/migration/v10-to-v11/", + ), + ); + }, + ); + + it.each([ + ["@sentry/angular", "angular"], + ["@sentry/cloudflare", "cloudflare"], + ["@sentry/nextjs", "nextjs"], + ["@sentry/nuxt", "nuxt"], + ["@sentry/react-router", "react-router"], + ["@sentry/remix", "remix"], + ["@sentry/sveltekit", "sveltekit"], + ])("links the %s migration guide", (packageName, guide) => { + printSdkV11MigrationGuideIfOutdated(packageName, { + dependencies: { [packageName]: "^10.2.0" }, + }); + + expect(clackMock.log.warn).toHaveBeenCalledWith( + expect.stringContaining( + `https://docs.sentry.io/platforms/javascript/guides/${guide}/migration/v10-to-v11/`, + ), + ); + }); + + it("falls back to the generic migration guide for other SDKs", () => { + printSdkV11MigrationGuideIfOutdated("@sentry/browser", { + dependencies: { "@sentry/browser": "^10.0.0" }, + }); + + expect(clackMock.log.warn).toHaveBeenCalledWith( + expect.stringContaining( + "https://docs.sentry.io/platforms/javascript/migration/v10-to-v11/", + ), + ); + }); + + it.each([ + ["the SDK is not installed", {}], + [ + "the SDK is already on v11", + { dependencies: { "@sentry/nextjs": "^11.0.0" } }, + ], + [ + "the installed range is not a valid semver range", + { + dependencies: { "@sentry/nextjs": "workspace:*" }, + }, + ], + ])("stays silent when %s", (_case, packageJson) => { + printSdkV11MigrationGuideIfOutdated("@sentry/nextjs", packageJson); + + expect(clackMock.log.warn).not.toHaveBeenCalled(); + }); +}); + +describe("abort", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("stops the wizard with an error exit code by default", async () => { + const error = await abort().catch((e: unknown) => e); + + expect(error).toBeInstanceOf(WizardExitError); + expect((error as WizardExitError).exitCode).toBe(1); + expect(clackMock.outro).toHaveBeenCalledTimes(1); + expect(clackMock.outro).toHaveBeenCalledWith("Wizard setup cancelled."); + expect(Sentry.setTag).toHaveBeenCalledWith("wizard.outcome", "aborted"); + }); + + it("stops the wizard with a custom exit code and message if provided", async () => { + const error = await abort("Bye", 0).catch((e: unknown) => e); + + expect((error as WizardExitError).exitCode).toBe(0); + expect(clackMock.outro).toHaveBeenCalledTimes(1); + expect(clackMock.outro).toHaveBeenCalledWith("Bye"); + expect(Sentry.setTag).toHaveBeenCalledWith("wizard.outcome", "cancelled"); + }); +}); + +describe("getPackageManager", () => { + afterEach(() => { + vi.clearAllMocks(); + // @ts-expect-error - this variable is set by the wizard + delete global.__sentry_wizard_cached_package_manager; + }); + + it("returns the auto-detected package manager", async () => { + const detectPacManSpy = vi + .spyOn(PackageManagerUtils, "_detectPackageManger") + .mockReturnValueOnce(YARN_V1); + + const packageManager = await getPackageManager(); + + expect(detectPacManSpy).toHaveBeenCalledTimes(1); + + expect(packageManager).toBe(YARN_V1); + }); + + it("caches the auto-detected package manager", async () => { + const detectPacManSpy = vi + .spyOn(PackageManagerUtils, "_detectPackageManger") + .mockReturnValueOnce(YARN_V1); + + const packageManager1 = await getPackageManager(); + const packageManager2 = await getPackageManager(); + + expect(detectPacManSpy).toHaveBeenCalledTimes(1); + + expect(packageManager1).toBe(YARN_V1); + expect(packageManager2).toBe(YARN_V1); + }); + + describe("when auto detection fails", () => { + it("returns a fallback package manager if fallback is specified", async () => { + const detectPacManSpy = vi + .spyOn(PackageManagerUtils, "_detectPackageManger") + .mockReturnValueOnce(null); + + const packageManager = await getPackageManager(YARN_V2); + + expect(detectPacManSpy).toHaveBeenCalledTimes(1); + + expect(packageManager).toBe(YARN_V2); + }); + + it("doesn't cache the fallback package manager", async () => { + const detectPacManSpy = vi + .spyOn(PackageManagerUtils, "_detectPackageManger") + .mockReturnValue(null); + + const packageManager1 = await getPackageManager(YARN_V2); + const packageManager2 = await getPackageManager(NPM); + + expect(detectPacManSpy).toHaveBeenCalledTimes(2); + + expect(packageManager1).toBe(YARN_V2); + expect(packageManager2).toBe(NPM); + }); + + it("returns the user-selected package manager if no fallback is provided", async () => { + const detectPacManSpy = vi + .spyOn(PackageManagerUtils, "_detectPackageManger") + .mockReturnValueOnce(null); + + clackMock.select.mockReturnValueOnce(Promise.resolve(PNPM)); + + const packageManager = await getPackageManager(); + + expect(detectPacManSpy).toHaveBeenCalledTimes(1); + expect(packageManager).toBe(PNPM); + }); + + it("caches the user-selected package manager", async () => { + const detectPacManSpy = vi + .spyOn(PackageManagerUtils, "_detectPackageManger") + .mockReturnValueOnce(null); + + clackMock.select.mockReturnValueOnce(Promise.resolve(PNPM)); + + const packageManager1 = await getPackageManager(); + const packageManager2 = await getPackageManager(); + + expect(detectPacManSpy).toHaveBeenCalledTimes(1); + expect(clackMock.select).toHaveBeenCalledTimes(1); + + expect(packageManager1).toBe(PNPM); + expect(packageManager2).toBe(PNPM); + }); + }); +}); + +describe("confirmContinueIfNoOrDirtyGitRepo", () => { + // process.exit is mocked to throw so that abort() halts execution the same + // way it would terminate the process in production, instead of falling + // through to the interactive prompt. + let exitSpy: MockInstance; + + beforeEach(() => { + vi.clearAllMocks(); + // Drain any leftover `mockReturnValueOnce` values queued by earlier + // suites; `clearAllMocks` clears call history but not the once-queue. + clackMock.confirm.mockReset(); + exitSpy = vi.spyOn(process, "exit").mockImplementation(() => { + throw new Error("exit"); + }); + }); + + afterEach(() => { + exitSpy.mockRestore(); + }); + + describe("non-interactive mode", () => { + it("aborts without prompting when the project is not a git repository", async () => { + (GitUtils.isInGitRepo as Mock).mockReturnValue(false); + + await expect( + confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: undefined, + cwd: undefined, + nonInteractive: true, + }), + ).rejects.toThrow(WizardExitError); + + expect(clack.log.error).toHaveBeenCalledWith( + expect.stringContaining( + "not inside a git repository in non-interactive mode", + ), + ); + expect(Sentry.setTag).toHaveBeenCalledWith("continue-without-git", false); + expect(clack.confirm).not.toHaveBeenCalled(); + }); + + it("aborts without prompting when the repository has uncommitted or untracked files", async () => { + (GitUtils.isInGitRepo as Mock).mockReturnValue(true); + (GitUtils.getUncommittedOrUntrackedFilePaths as Mock).mockReturnValue([ + "src/index.ts", + ]); + + await expect( + confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: false, + cwd: undefined, + nonInteractive: true, + }), + ).rejects.toThrow(WizardExitError); + + expect(clack.log.warn).toHaveBeenCalledWith( + expect.stringContaining("uncommitted or untracked files"), + ); + expect(clack.log.error).toHaveBeenCalledWith( + expect.stringContaining( + "uncommitted or untracked files in non-interactive mode", + ), + ); + expect(Sentry.setTag).toHaveBeenCalledWith( + "continue-with-dirty-repo", + false, + ); + expect(clack.confirm).not.toHaveBeenCalled(); + }); + }); + + describe("interactive mode (default)", () => { + it("prompts to continue when the project is not a git repository", async () => { + (GitUtils.isInGitRepo as Mock).mockReturnValue(false); + mockUserResponse(clack.confirm as Mock, true); + + await confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: undefined, + cwd: undefined, + }); + + expect(clack.confirm).toHaveBeenCalledWith( + expect.objectContaining({ + message: expect.stringContaining("not inside a git repository"), + }), + ); + expect(clack.log.error).not.toHaveBeenCalled(); + expect(exitSpy).not.toHaveBeenCalled(); + expect(Sentry.setTag).toHaveBeenCalledWith("continue-without-git", true); + }); + + it("prompts to continue when the repository has uncommitted or untracked files", async () => { + (GitUtils.isInGitRepo as Mock).mockReturnValue(true); + (GitUtils.getUncommittedOrUntrackedFilePaths as Mock).mockReturnValue([ + "src/index.ts", + ]); + mockUserResponse(clack.confirm as Mock, true); + + await confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: false, + cwd: undefined, + nonInteractive: false, + }); + + expect(clack.log.warn).toHaveBeenCalledWith( + expect.stringContaining("uncommitted or untracked files"), + ); + expect(clack.confirm).toHaveBeenCalledWith( + expect.objectContaining({ + message: expect.stringContaining("continue anyway"), + }), + ); + expect(clack.log.error).not.toHaveBeenCalled(); + expect(exitSpy).not.toHaveBeenCalled(); + expect(Sentry.setTag).toHaveBeenCalledWith( + "continue-with-dirty-repo", + true, + ); + }); + + it("does not prompt or abort for a clean git repository", async () => { + (GitUtils.isInGitRepo as Mock).mockReturnValue(true); + (GitUtils.getUncommittedOrUntrackedFilePaths as Mock).mockReturnValue([]); + + await confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: undefined, + cwd: undefined, + }); + + expect(clack.confirm).not.toHaveBeenCalled(); + expect(clack.log.warn).not.toHaveBeenCalled(); + expect(exitSpy).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/utils/clack/mcp-config.test.ts b/packages/cli/test/lib/wizard/utils/clack/mcp-config.test.ts new file mode 100644 index 0000000000..af614d9793 --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/clack/mcp-config.test.ts @@ -0,0 +1,1049 @@ +import { + describe, + expect, + it, + vi, + beforeEach, + afterEach, + type Mock, +} from "vitest"; +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as fs from "node:fs"; +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as path from "node:path"; +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as childProcess from "node:child_process"; +import { offerProjectScopedMcpConfig } from "../../../../../src/lib/wizard/utils/clack/mcp-config.js"; + +// Mock types for better type safety +type ConfigContent = { + mcpServers?: Record; + servers?: Record; + mcp?: Record; + $schema?: string; + otherProperty?: string; +}; + +// Mock the clack utils which wrap the prompts +vi.mock("../../../../../src/lib/wizard/utils/clack/index.js", () => ({ + abortIfCancelled: vi.fn((value: unknown) => Promise.resolve(value)), + showCopyPasteInstructions: vi.fn(), +})); + +// Mock the external dependencies +vi.mock("@clack/prompts", () => ({ + confirm: vi.fn(), + select: vi.fn(), + multiselect: vi.fn(), + isCancel: vi.fn(() => false), + cancel: vi.fn(), + log: { + success: vi.fn(), + info: vi.fn(), + warn: vi.fn(), + }, +})); + +vi.mock("node:fs"); +vi.mock("node:child_process"); + +describe("mcp-config", () => { + // Helper to get mocked modules with proper typing + type ClackMocks = { + select: ReturnType; + multiselect: ReturnType; + log: { + success: ReturnType; + info: ReturnType; + warn: ReturnType; + }; + }; + + type ClackUtilsMocks = { + abortIfCancelled: Mock<(value: unknown) => Promise>; + showCopyPasteInstructions: ReturnType; + }; + + const getMocks = async () => { + const clack = await vi.importMock("@clack/prompts"); + const clackUtils = await vi.importMock( + "../../../../../src/lib/wizard/utils/clack/index.js", + ); + return { clack, clackUtils }; + }; + + beforeEach(() => { + vi.clearAllMocks(); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + describe("offerProjectScopedMcpConfig", () => { + it("should return early if user declines MCP config", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValue("no"); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + await offerProjectScopedMcpConfig(); + + expect(clack.select).toHaveBeenCalledWith( + expect.objectContaining({ + message: expect.stringContaining( + "Optionally add a project-scoped MCP server configuration", + ) as string, + options: expect.arrayContaining([ + expect.objectContaining({ value: "yes" }), + expect.objectContaining({ value: "no" }), + expect.objectContaining({ value: "explain" }), + ]) as unknown[], + initialValue: "yes", + }), + ); + }); + + it("should configure for Cursor when selected", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["cursor"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + expect(clack.multiselect).toHaveBeenCalledWith( + expect.objectContaining({ + message: "Which editor(s) do you want to configure?", + options: expect.arrayContaining([ + expect.objectContaining({ value: "cursor" }), + expect.objectContaining({ value: "vscode" }), + expect.objectContaining({ value: "claudeCode" }), + ]) as unknown[], + }), + ); + + expect(mockWriteFile).toHaveBeenCalledWith( + expect.stringContaining(".cursor/mcp.json"), + expect.stringContaining('"mcpServers"'), + "utf8", + ); + + expect(clack.log.success).toHaveBeenCalledWith( + expect.stringContaining(".cursor/mcp.json"), + ); + expect(clack.log.success).toHaveBeenCalledWith( + "Added project-scoped Sentry MCP configuration for Cursor.", + ); + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining("reload your editor"), + ); + }); + + it("should configure for VS Code when selected", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["vscode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + expect(mockWriteFile).toHaveBeenCalledWith( + expect.stringContaining(".vscode/mcp.json"), + expect.stringContaining('"servers"'), + "utf8", + ); + + expect(clack.log.success).toHaveBeenCalledWith( + expect.stringContaining(".vscode/mcp.json"), + ); + }); + + it("should configure for Claude Code when selected", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["claudeCode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + expect(mockWriteFile).toHaveBeenCalledWith( + expect.stringContaining(".mcp.json"), + expect.stringContaining('"mcpServers"'), + "utf8", + ); + + expect(clack.log.success).toHaveBeenCalledWith( + expect.stringContaining(".mcp.json"), + ); + }); + + it("should update existing Cursor config file", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["cursor"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const existingConfig = JSON.stringify({ + mcpServers: { + OtherServer: { + url: "https://other.example.com", + }, + }, + }); + + const mockReadFile = vi.fn().mockResolvedValue(existingConfig); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + expect(mockReadFile).toHaveBeenCalled(); + expect(mockWriteFile).toHaveBeenCalledWith( + expect.stringContaining(".cursor/mcp.json"), + expect.stringContaining("Sentry"), + "utf8", + ); + + const writtenContent = JSON.parse( + mockWriteFile.mock.calls[0]?.[1] as string, + ) as ConfigContent; + expect(writtenContent.mcpServers).toHaveProperty("OtherServer"); + expect(writtenContent.mcpServers).toHaveProperty("Sentry"); + + expect(clack.log.success).toHaveBeenCalledWith( + "Updated .cursor/mcp.json", + ); + }); + + it("should update existing VS Code config file", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["vscode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const existingConfig = JSON.stringify({ + servers: { + OtherServer: { + url: "https://other.example.com", + type: "http", + }, + }, + }); + + const mockReadFile = vi.fn().mockResolvedValue(existingConfig); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + const writtenContent = JSON.parse( + mockWriteFile.mock.calls[0]?.[1] as string, + ) as ConfigContent; + expect(writtenContent.servers).toHaveProperty("OtherServer"); + expect(writtenContent.servers).toHaveProperty("Sentry"); + expect(writtenContent.servers?.["Sentry"]).toHaveProperty("type", "http"); + + expect(clack.log.success).toHaveBeenCalledWith( + "Updated .vscode/mcp.json", + ); + }); + + it("should update existing Claude Code config file", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["claudeCode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const existingConfig = JSON.stringify({ + mcpServers: { + OtherServer: { + url: "https://other.example.com", + }, + }, + }); + + const mockReadFile = vi.fn().mockResolvedValue(existingConfig); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + const writtenContent = JSON.parse( + mockWriteFile.mock.calls[0]?.[1] as string, + ) as ConfigContent; + expect(writtenContent.mcpServers).toHaveProperty("OtherServer"); + expect(writtenContent.mcpServers).toHaveProperty("Sentry"); + + expect(clack.log.success).toHaveBeenCalledWith("Updated .mcp.json"); + }); + + it("should configure for OpenCode when selected", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["openCode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + expect(mockWriteFile).toHaveBeenCalledWith( + expect.stringContaining("opencode.json"), + expect.stringContaining('"mcp"'), + "utf8", + ); + + // Verify the written content has the correct structure for OpenCode + const writtenContent = JSON.parse( + mockWriteFile.mock.calls[0]?.[1] as string, + ) as ConfigContent; + expect(writtenContent.$schema).toBe("https://opencode.ai/config.json"); + expect(writtenContent.mcp).toHaveProperty("Sentry"); + expect(writtenContent.mcp?.["Sentry"]).toHaveProperty("type", "remote"); + expect(writtenContent.mcp?.["Sentry"]).toHaveProperty("url"); + expect(writtenContent.mcp?.["Sentry"]?.oauth).toEqual({}); + + expect(clack.log.success).toHaveBeenCalledWith( + expect.stringContaining("opencode.json"), + ); + expect(clack.log.success).toHaveBeenCalledWith( + "Added project-scoped Sentry MCP configuration for OpenCode.", + ); + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining("restart OpenCode"), + ); + }); + + it("should update existing OpenCode config file", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["openCode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const existingConfig = JSON.stringify({ + mcp: { + OtherServer: { + type: "remote", + url: "https://other.example.com", + }, + }, + }); + + const mockReadFile = vi.fn().mockResolvedValue(existingConfig); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + const writtenContent = JSON.parse( + mockWriteFile.mock.calls[0]?.[1] as string, + ) as ConfigContent; + expect(writtenContent.mcp).toHaveProperty("OtherServer"); + expect(writtenContent.mcp).toHaveProperty("Sentry"); + expect(writtenContent.mcp?.["Sentry"]).toHaveProperty("type", "remote"); + + expect(clack.log.success).toHaveBeenCalledWith("Updated opencode.json"); + }); + + it("should handle file write errors gracefully for OpenCode", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["openCode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi + .fn() + .mockRejectedValue(new Error("Permission denied")); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await expect(offerProjectScopedMcpConfig()).resolves.toBeUndefined(); + + expect(clack.log.warn).toHaveBeenCalledWith( + expect.stringContaining("Failed to write MCP config for openCode"), + ); + + expect(clackUtils.showCopyPasteInstructions).toHaveBeenCalledWith( + expect.objectContaining({ + filename: "opencode.json", + codeSnippet: expect.stringContaining('"mcp"') as string, + hint: "create the file if it does not exist", + }), + ); + }); + + it("should handle file write errors gracefully for Cursor", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["cursor"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi + .fn() + .mockRejectedValue(new Error("Permission denied")); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await expect(offerProjectScopedMcpConfig()).resolves.toBeUndefined(); + + expect(clack.log.warn).toHaveBeenCalledWith( + expect.stringContaining("Failed to write MCP config"), + ); + + expect(clackUtils.showCopyPasteInstructions).toHaveBeenCalledWith( + expect.objectContaining({ + filename: path.join(".cursor", "mcp.json"), + codeSnippet: expect.stringContaining("mcpServers") as string, + hint: "create the file if it does not exist", + }), + ); + }); + + it("should handle file write errors gracefully for VS Code", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["vscode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi + .fn() + .mockRejectedValue(new Error("Permission denied")); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await expect(offerProjectScopedMcpConfig()).resolves.toBeUndefined(); + + expect(clackUtils.showCopyPasteInstructions).toHaveBeenCalledWith( + expect.objectContaining({ + filename: path.join(".vscode", "mcp.json"), + codeSnippet: expect.stringContaining("servers") as string, + hint: "create the file if it does not exist", + }), + ); + }); + + it("should handle file write errors gracefully for Claude Code", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["claudeCode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi + .fn() + .mockRejectedValue(new Error("Permission denied")); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await expect(offerProjectScopedMcpConfig()).resolves.toBeUndefined(); + + expect(clackUtils.showCopyPasteInstructions).toHaveBeenCalledWith( + expect.objectContaining({ + filename: ".mcp.json", + codeSnippet: expect.stringContaining("mcpServers") as string, + hint: "create the file if it does not exist", + }), + ); + }); + + it("should handle update errors and show copy-paste instructions", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["cursor"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + // Mock existing file and simulate write error during update + const existingConfig = JSON.stringify({ + mcpServers: { + OtherServer: { + url: "https://other.example.com", + }, + }, + }); + + const mockReadFile = vi.fn().mockResolvedValue(existingConfig); + const mockWriteFile = vi + .fn() + .mockRejectedValue(new Error("Write failed during update")); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await expect(offerProjectScopedMcpConfig()).resolves.toBeUndefined(); + + expect(clack.log.warn).toHaveBeenCalledWith( + expect.stringContaining("Failed to write MCP config"), + ); + + expect(clackUtils.showCopyPasteInstructions).toHaveBeenCalled(); + }); + + it("should handle mkdirSync errors", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["cursor"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn().mockImplementation(() => { + throw new Error("Permission denied"); + }); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await expect(offerProjectScopedMcpConfig()).resolves.toBeUndefined(); + + expect(clack.log.warn).toHaveBeenCalledWith( + expect.stringContaining("Failed to write MCP config"), + ); + + expect(clackUtils.showCopyPasteInstructions).toHaveBeenCalled(); + }); + + it("should create config with empty servers/mcpServers when existing config lacks them", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["vscode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const existingConfig = JSON.stringify({ + otherProperty: "value", + }); + + const mockReadFile = vi.fn().mockResolvedValue(existingConfig); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + const writtenContent = JSON.parse( + mockWriteFile.mock.calls[0]?.[1] as string, + ) as ConfigContent; + expect(writtenContent).toHaveProperty("otherProperty", "value"); + expect(writtenContent).toHaveProperty("servers"); + expect(writtenContent.servers).toHaveProperty("Sentry"); + + expect(clack.log.success).toHaveBeenCalledWith( + "Updated .vscode/mcp.json", + ); + }); + + it("should show config for JetBrains IDEs with clipboard copy", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select) + .mockResolvedValueOnce("yes") + .mockResolvedValueOnce(true); // For the clipboard copy prompt + vi.mocked(clack.multiselect).mockResolvedValueOnce(["jetbrains"]); + + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + // Mock clipboard copy + const mockSpawn = vi.fn().mockReturnValue({ + stdin: { + write: vi.fn(), + end: vi.fn(), + }, + on: vi.fn((event, callback: (code?: number) => void) => { + if (event === "close") callback(0); + }), + }); + vi.spyOn(childProcess, "spawn").mockImplementation(mockSpawn); + + // Mock console.log to capture output + const consoleSpy = vi + .spyOn(process.stdout, "write") + .mockImplementation(() => true); + + await offerProjectScopedMcpConfig(); + + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining("JetBrains IDEs"), + ); + + expect(consoleSpy).toHaveBeenCalledWith( + expect.stringContaining("mcpServers"), + ); + + // Should ask to copy to clipboard + expect(clack.select).toHaveBeenCalledWith( + expect.objectContaining({ + message: "Copy configuration to clipboard?", + }), + ); + + expect(clack.log.success).toHaveBeenCalledWith( + "Configuration copied to clipboard!", + ); + + consoleSpy.mockRestore(); + }); + + it("should show generic config for unsupported IDEs with clipboard copy", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select) + .mockResolvedValueOnce("yes") + .mockResolvedValueOnce(true); // For the clipboard copy prompt + vi.mocked(clack.multiselect).mockResolvedValueOnce(["other"]); + + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + // Mock clipboard copy failure to test fallback + const mockSpawn = vi.fn().mockReturnValue({ + stdin: { + write: vi.fn(), + end: vi.fn(), + }, + on: vi.fn((event, callback: () => void) => { + if (event === "error") callback(); + }), + }); + vi.spyOn(childProcess, "spawn").mockImplementation(mockSpawn); + + // Mock console.log to capture output + const consoleSpy = vi + .spyOn(process.stdout, "write") + .mockImplementation(() => true); + + await offerProjectScopedMcpConfig(); + + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining("Generic MCP configuration"), + ); + + expect(consoleSpy).toHaveBeenCalledWith( + expect.stringContaining("mcpServers"), + ); + + // Should ask to copy to clipboard + expect(clack.select).toHaveBeenCalledWith( + expect.objectContaining({ + message: "Copy configuration to clipboard?", + }), + ); + + // Since clipboard copy failed, should show warning + expect(clack.log.warn).toHaveBeenCalledWith( + expect.stringContaining("Failed to copy to clipboard"), + ); + + consoleSpy.mockRestore(); + }); + + it("should handle clipboard copy failure gracefully for JetBrains", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select) + .mockResolvedValueOnce("yes") + .mockResolvedValueOnce(true); // For clipboard copy prompt + vi.mocked(clack.multiselect).mockResolvedValueOnce(["jetbrains"]); + + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + // Mock clipboard copy to throw error + const mockSpawn = vi.fn().mockImplementation(() => { + throw new Error("Clipboard not available"); + }); + vi.spyOn(childProcess, "spawn").mockImplementation(mockSpawn); + + // Mock console.log to capture output + const consoleSpy = vi + .spyOn(process.stdout, "write") + .mockImplementation(() => true); + + await offerProjectScopedMcpConfig(); + + // Should ask to copy to clipboard + expect(clack.select).toHaveBeenCalledWith( + expect.objectContaining({ + message: "Copy configuration to clipboard?", + }), + ); + + // Should show warning when clipboard fails + expect(clack.log.warn).toHaveBeenCalledWith( + expect.stringContaining("Failed to copy to clipboard"), + ); + + consoleSpy.mockRestore(); + }); + + it('should show MCP explanation when user selects "What is MCP?"', async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select) + .mockResolvedValueOnce("explain") // User selects "What is MCP?" + .mockResolvedValueOnce(true); // User selects "Yes" after explanation + vi.mocked(clack.multiselect).mockResolvedValueOnce(["cursor"]); // User selects Cursor + + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + // Should show MCP explanation + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining("What is MCP"), + ); + + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining("AI assistants"), + ); + + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining("https://docs.sentry.io/product/sentry-mcp/"), + ); + + // Should ask again after explanation + expect(clack.select).toHaveBeenCalledWith( + expect.objectContaining({ + message: "Would you like to configure MCP for your IDE now?", + }), + ); + + // Should proceed with normal flow + expect(mockWriteFile).toHaveBeenCalled(); + }); + + it("should respect user choice not to copy to clipboard", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select) + .mockResolvedValueOnce("yes") + .mockResolvedValueOnce(false); // User declines to copy to clipboard + vi.mocked(clack.multiselect).mockResolvedValueOnce(["jetbrains"]); + + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockSpawn = vi.fn(); + vi.spyOn(childProcess, "spawn").mockImplementation(mockSpawn); + + // Mock console.log to capture output + const consoleSpy = vi + .spyOn(process.stdout, "write") + .mockImplementation(() => true); + + await offerProjectScopedMcpConfig(); + + // Should ask to copy to clipboard + expect(clack.select).toHaveBeenCalledWith( + expect.objectContaining({ + message: "Copy configuration to clipboard?", + }), + ); + + // Should NOT attempt to copy when user declines + expect(mockSpawn).not.toHaveBeenCalled(); + + // Should NOT show success or warning messages + expect(clack.log.success).not.toHaveBeenCalledWith( + "Configuration copied to clipboard!", + ); + expect(clack.log.warn).not.toHaveBeenCalledWith( + expect.stringContaining("Failed to copy to clipboard"), + ); + + consoleSpy.mockRestore(); + }); + + it("should exit if user declines after MCP explanation", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select) + .mockResolvedValueOnce("explain") // User selects "What is MCP?" + .mockResolvedValueOnce(false); // User selects "No" after explanation + + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + await offerProjectScopedMcpConfig(); + + // Should show MCP explanation + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining("What is MCP"), + ); + + // Should ask again after explanation + expect(clack.select).toHaveBeenCalledWith( + expect.objectContaining({ + message: "Would you like to configure MCP for your IDE now?", + }), + ); + + // Should NOT proceed with editor selection + expect(clack.multiselect).not.toHaveBeenCalled(); + }); + + it("should configure multiple editors when selected", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce([ + "cursor", + "vscode", + "claudeCode", + ]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + // Should write config for all three editors + expect(mockWriteFile).toHaveBeenCalledTimes(3); + expect(mockWriteFile).toHaveBeenCalledWith( + expect.stringContaining(".cursor/mcp.json"), + expect.stringContaining('"mcpServers"'), + "utf8", + ); + expect(mockWriteFile).toHaveBeenCalledWith( + expect.stringContaining(".vscode/mcp.json"), + expect.stringContaining('"servers"'), + "utf8", + ); + expect(mockWriteFile).toHaveBeenCalledWith( + expect.stringContaining(".mcp.json"), + expect.stringContaining('"mcpServers"'), + "utf8", + ); + + // Should show success messages for each (twice per editor: filename + editor-specific message) + expect(clack.log.success).toHaveBeenCalledWith( + "Added project-scoped Sentry MCP configuration for Cursor.", + ); + expect(clack.log.success).toHaveBeenCalledWith( + "Added project-scoped Sentry MCP configuration for VS Code.", + ); + expect(clack.log.success).toHaveBeenCalledWith( + "Added project-scoped Sentry MCP configuration for Claude Code.", + ); + }); + + it("should return early when no editors are selected", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce([]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockWriteFile = vi.fn(); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + + await offerProjectScopedMcpConfig(); + + expect(clack.log.info).toHaveBeenCalledWith( + "No editors selected. You can add MCP configuration later.", + ); + expect(mockWriteFile).not.toHaveBeenCalled(); + }); + + it("should handle mixed success and failure for multiple editors", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["cursor", "vscode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi + .fn() + .mockResolvedValueOnce(undefined) // Cursor succeeds + .mockRejectedValueOnce(new Error("Permission denied")); // VS Code fails + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + // Cursor should succeed + expect(clack.log.success).toHaveBeenCalledWith( + expect.stringContaining(".cursor/mcp.json"), + ); + + // VS Code should fail and show fallback + expect(clack.log.warn).toHaveBeenCalledWith( + expect.stringContaining("Failed to write MCP config for vscode"), + ); + expect(clackUtils.showCopyPasteInstructions).toHaveBeenCalledWith( + expect.objectContaining({ + filename: path.join(".vscode", "mcp.json"), + }), + ); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/utils/data-collection.test.ts b/packages/cli/test/lib/wizard/utils/data-collection.test.ts new file mode 100644 index 0000000000..6f68c33bf0 --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/data-collection.test.ts @@ -0,0 +1,92 @@ +import { describe, expect, it } from "vitest"; + +import { + getDataCollectionSnippet, + sdkSupportsDataCollection, +} from "../../../../src/lib/wizard/utils/data-collection.js"; +import { getMajorVersion } from "../../../../src/lib/wizard/utils/semver.js"; + +describe("getMajorVersion", () => { + it.each([ + ["^10", 10], + ["^10.73.0", 10], + ["~11.2.0", 11], + ["11.0.0", 11], + // Prerelease versions keep their major, so v11 rc/beta installs pass the gate + ["11.0.0-rc.1", 11], + ["^11.0.0-rc.0", 11], + ["~11.0.0-beta.2", 11], + [">=10.57.0 <12", 10], + ])("returns the lowest permitted major for %s", (version, expected) => { + expect(getMajorVersion(version)).toBe(expected); + }); + + it.each([undefined, "", "not-a-version", "workspace:*"])( + "returns undefined for %s", + (version) => { + expect(getMajorVersion(version)).toBeUndefined(); + }, + ); +}); + +describe("sdkSupportsDataCollection", () => { + it.each([ + ["^11.0.0", "^10"], + ["11.2.3", "^10"], + ["^12", "^10"], + ["11.0.0-rc.1", "^10"], + ["^11.0.0-beta.0", "^10"], + ])("returns true for installed version %s", (installed, range) => { + expect(sdkSupportsDataCollection(installed, range)).toBe(true); + }); + + it.each([ + ["^10.73.0", "^10"], + ["10.99.0", "^10"], + ["^9", "^10"], + ["10.99.0-rc.1", "^10"], + ])("returns false for installed version %s", (installed, range) => { + expect(sdkSupportsDataCollection(installed, range)).toBe(false); + }); + + it("falls back to the wizard install range when the installed version is missing", () => { + expect(sdkSupportsDataCollection(undefined, "^11")).toBe(true); + expect(sdkSupportsDataCollection(undefined, "^10")).toBe(false); + }); + + it("falls back to the wizard install range when the installed version is unparseable", () => { + expect(sdkSupportsDataCollection("workspace:*", "^11")).toBe(true); + expect(sdkSupportsDataCollection("workspace:*", "^10")).toBe(false); + }); + + it("returns false when neither version is parseable", () => { + expect(sdkSupportsDataCollection(undefined, "not-a-version")).toBe(false); + }); +}); + +describe("getDataCollectionSnippet", () => { + it("renders the preset with the default indentation", () => { + expect(getDataCollectionSnippet()).toMatchInlineSnapshot(` + " // 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"] }, + }," + `); + }); + + it("prefixes every line with the given indent", () => { + const snippet = getDataCollectionSnippet(" "); + for (const line of snippet.split("\n")) { + expect(line.startsWith(" ")).toBe(true); + } + }); +}); diff --git a/packages/cli/test/lib/wizard/utils/git.test.ts b/packages/cli/test/lib/wizard/utils/git.test.ts new file mode 100644 index 0000000000..4daaffda1c --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/git.test.ts @@ -0,0 +1,126 @@ +import { beforeEach, describe, it, vi, expect } from "vitest"; + +import { + getUncommittedOrUntrackedFilePaths, + isInGitRepo, +} from "../../../../src/lib/wizard/utils/git.js"; + +const { mockedExecSync } = vi.hoisted(() => { + return { mockedExecSync: vi.fn() }; +}); + +vi.mock("node:child_process", async () => { + return { + default: {}, + ...(await vi.importActual("node:child_process")), + execSync: mockedExecSync, + }; +}); + +beforeEach(() => { + vi.clearAllMocks(); +}); + +describe("isInGitRepo", () => { + it("returns true if the git command process exits with 0", () => { + mockedExecSync.mockImplementationOnce(() => { + return "true"; + }); + expect(isInGitRepo({ cwd: undefined })).toBe(true); + }); + + it("returns false if the git command process exits with non-zero", () => { + mockedExecSync.mockImplementationOnce(() => { + throw new Error("Command failed"); + }); + expect(isInGitRepo({ cwd: undefined })).toBe(false); + }); + + it("forwards cwd if provided", () => { + mockedExecSync.mockImplementationOnce(() => { + return "true"; + }); + isInGitRepo({ cwd: "/path/to/dir" }); + expect(mockedExecSync).toHaveBeenCalledWith( + "git rev-parse --is-inside-work-tree", + { + stdio: "ignore", + cwd: "/path/to/dir", + }, + ); + }); +}); + +describe("getUncommittedOrUntrackedFilePaths", () => { + it("returns the verbatim paths of uncommitted or untracked files", () => { + mockedExecSync.mockImplementationOnce(() => { + return ( + " M file1.txt\0" + + "?? file2.txt\0" + + "?? file3.txt\0" + + "?? file4.txt\0" + ); + }); + expect(getUncommittedOrUntrackedFilePaths()).toEqual([ + "file1.txt", + "file2.txt", + "file3.txt", + "file4.txt", + ]); + }); + + it("uses the NUL-delimited porcelain format", () => { + mockedExecSync.mockImplementationOnce(() => ""); + + getUncommittedOrUntrackedFilePaths({ cwd: "/path/to/dir" }); + + expect(mockedExecSync).toHaveBeenCalledWith( + "git status --porcelain=v1 -z", + { + stdio: ["ignore", "pipe", "ignore"], + cwd: "/path/to/dir", + }, + ); + }); + + it("preserves file names containing spaces and shell metacharacters", () => { + mockedExecSync.mockImplementationOnce(() => { + return ( + "?? $(touch pwned).js\0" + + "?? a;id;b.js\0" + + "?? with space.txt\0" + + " M `whoami`.ts\0" + ); + }); + expect(getUncommittedOrUntrackedFilePaths()).toEqual([ + "$(touch pwned).js", + "a;id;b.js", + "with space.txt", + "`whoami`.ts", + ]); + }); + + it("returns the destination path of a rename and skips the source field", () => { + mockedExecSync.mockImplementationOnce(() => { + return "R renamed.txt\0orig.txt\0?? other.txt\0"; + }); + expect(getUncommittedOrUntrackedFilePaths()).toEqual([ + "renamed.txt", + "other.txt", + ]); + }); + + it("returns an empty list if there are no uncommitted or untracked files", () => { + mockedExecSync.mockImplementationOnce(() => ""); + + expect(getUncommittedOrUntrackedFilePaths()).toEqual([]); + }); + + it("returns an empty list if the git command fails", () => { + mockedExecSync.mockImplementationOnce(() => { + throw new Error("Command failed"); + }); + + expect(getUncommittedOrUntrackedFilePaths()).toEqual([]); + }); +}); diff --git a/packages/cli/test/lib/wizard/utils/node-version.test.ts b/packages/cli/test/lib/wizard/utils/node-version.test.ts new file mode 100644 index 0000000000..f7084d0253 --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/node-version.test.ts @@ -0,0 +1,69 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const clackMocks = vi.hoisted(() => ({ warn: vi.fn() })); + +vi.mock("@clack/prompts", () => ({ + log: { warn: clackMocks.warn }, +})); + +import { + isNodeVersionSupportedBySdkV11, + warnIfNodeVersionUnsupportedBySdkV11, +} from "../../../../src/lib/wizard/utils/node-version.js"; + +describe("isNodeVersionSupportedBySdkV11", () => { + it.each([ + "v20.19.0", + "v20.20.2", + "20.19.5", + "v22.12.0", + "v22.23.2", + "v23.2.0", + "v24.0.0", + "v26.8.1", + // Node.js 21 is EOL but inside the documented `>=20.19.0 <22.0.0` range + "v21.7.0", + ])("returns true for %s", (version) => { + expect(isNodeVersionSupportedBySdkV11(version)).toBe(true); + }); + + it.each(["v18.20.6", "v20.18.3", "v22.11.0", "v23.1.0", "16.20.2"])( + "returns false for %s", + (version) => { + expect(isNodeVersionSupportedBySdkV11(version)).toBe(false); + }, + ); + + it.each(["", "not-a-version"])( + "treats an unparseable version (%s) as supported", + (version) => { + expect(isNodeVersionSupportedBySdkV11(version)).toBe(true); + }, + ); + + it("defaults to the running Node.js version", () => { + expect(isNodeVersionSupportedBySdkV11()).toBe( + isNodeVersionSupportedBySdkV11(process.version), + ); + }); +}); + +describe("warnIfNodeVersionUnsupportedBySdkV11", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("warns on an unsupported version and names it", () => { + warnIfNodeVersionUnsupportedBySdkV11("v18.20.6"); + + expect(clackMocks.warn).toHaveBeenCalledTimes(1); + expect(clackMocks.warn.mock.calls[0]?.[0]).toContain("v18.20.6"); + expect(clackMocks.warn.mock.calls[0]?.[0]).toContain("20.19.0"); + }); + + it("stays silent on a supported version", () => { + warnIfNodeVersionUnsupportedBySdkV11("v22.18.0"); + + expect(clackMocks.warn).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/cli/test/lib/wizard/utils/package-json.test.ts b/packages/cli/test/lib/wizard/utils/package-json.test.ts new file mode 100644 index 0000000000..f04f2f9fd4 --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/package-json.test.ts @@ -0,0 +1,594 @@ +import { beforeEach, describe, it, vi, expect, afterEach } from "vitest"; +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as path from "node:path"; + +import { + findInstalledPackageFromList, + hasPackageInstalled, + getPackageVersion, + type PackageDotJson, +} from "../../../../src/lib/wizard/utils/package-json.js"; + +const { mockedFs, mockedClack } = vi.hoisted(() => { + return { + mockedFs: { + existsSync: vi.fn(), + readFileSync: vi.fn(), + }, + mockedClack: { + log: { + error: vi.fn(), + }, + }, + }; +}); + +vi.mock(import("node:fs"), async (importOriginal) => ({ + ...(await importOriginal()), + existsSync: mockedFs.existsSync, + readFileSync: mockedFs.readFileSync, +})); + +vi.mock(import("@clack/prompts"), async (importOriginal) => ({ + ...(await importOriginal()), + log: { + ...(await importOriginal()).log, + error: mockedClack.log.error, + }, +})); + +describe("package-json utils", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + describe("getPackageVersion", () => { + it("returns version from dependencies", () => { + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "^7.0.0", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBe("^7.0.0"); + }); + + it("returns version from devDependencies", () => { + const packageJson: PackageDotJson = { + devDependencies: { + "@sentry/cli": "^2.0.0", + }, + }; + + expect(getPackageVersion("@sentry/cli", packageJson)).toBe("^2.0.0"); + }); + + it("prioritizes dependencies over devDependencies", () => { + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "^7.0.0", + }, + devDependencies: { + "@sentry/node": "^6.0.0", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBe("^7.0.0"); + }); + + it("returns undefined if package is not found", () => { + const packageJson: PackageDotJson = { + dependencies: {}, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBeUndefined(); + }); + + it("returns undefined if packageJson has no dependencies", () => { + const packageJson: PackageDotJson = {}; + + expect(getPackageVersion("@sentry/node", packageJson)).toBeUndefined(); + }); + + describe("pnpm catalog resolution", () => { + beforeEach(() => { + vi.spyOn(process, "cwd").mockReturnValue( + "/test/workspace/packages/app", + ); + }); + + afterEach(() => { + vi.clearAllMocks(); + }); + + it("resolves default catalog reference", () => { + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sentry/node': ^7.100.0 + '@sentry/react': ^7.100.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBe("^7.100.0"); + }); + + it("resolves named catalog reference", () => { + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalogs: + sveltekit: + '@sentry/sveltekit': ^7.100.0 + '@sentry/node': ^7.100.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/sveltekit": "catalog:sveltekit", + }, + }; + + expect(getPackageVersion("@sentry/sveltekit", packageJson)).toBe( + "^7.100.0", + ); + }); + + it("searches parent directories for pnpm-workspace.yaml", () => { + const mockCwd = "/test/workspace/packages/app/src"; + vi.spyOn(process, "cwd").mockReturnValue(mockCwd); + + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sentry/node': ^7.100.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBe("^7.100.0"); + }); + + it("returns undefined if catalog does not contain the package", () => { + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sentry/react': ^7.100.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBeUndefined(); + }); + + it("returns undefined if named catalog does not exist", () => { + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sentry/node': ^7.100.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/sveltekit": "catalog:sveltekit", + }, + }; + + expect( + getPackageVersion("@sentry/sveltekit", packageJson), + ).toBeUndefined(); + }); + + it("returns undefined if pnpm-workspace.yaml is not found", () => { + mockedFs.existsSync.mockReturnValue(false); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBeUndefined(); + expect(mockedClack.log.error).toHaveBeenCalledWith( + "Could not find pnpm-workspace.yaml.", + ); + }); + + it("stops searching at root directory", () => { + const mockCwd = "/test"; + vi.spyOn(process, "cwd").mockReturnValue(mockCwd); + + mockedFs.existsSync.mockReturnValue(false); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBeUndefined(); + }); + + it("handles both default catalog and named catalogs together", () => { + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sentry/node': ^7.100.0 +catalogs: + sveltekit: + '@sentry/sveltekit': ^7.200.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + "@sentry/sveltekit": "catalog:sveltekit", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBe("^7.100.0"); + expect(getPackageVersion("@sentry/sveltekit", packageJson)).toBe( + "^7.200.0", + ); + }); + + it("handles the correct catalog namespace", () => { + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sveltejs/kit': ^1.0.0 +catalogs: + sveltekit: + '@sveltejs/kit': ^2.31.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sveltejs/kit": "catalog:sveltekit", + }, + }; + + expect(getPackageVersion("@sveltejs/kit", packageJson)).toBe("^2.31.0"); + }); + + it("ignores pnpm-workspace.yaml content that is not a catalog mapping", () => { + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + + mockedFs.readFileSync.mockReturnValue("invalid: yaml: content: ["); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBeUndefined(); + }); + + it("reads quoted names, inline comments, and catalogs of other packages", () => { + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + + mockedFs.readFileSync.mockReturnValue(`packages: + - 'apps/*' + +# Versions shared across the workspace +catalog: + "@sentry/node": "^8.0.0" # keep in sync + react: ^18.2.0 + +catalogs: + legacy: + '@sentry/node': ~7.120.0 + next: + "@sentry/nextjs": 9.0.0 +onlyBuiltDependencies: + - esbuild +`); + + expect( + getPackageVersion("@sentry/node", { + dependencies: { "@sentry/node": "catalog:" }, + }), + ).toBe("^8.0.0"); + expect( + getPackageVersion("@sentry/node", { + dependencies: { "@sentry/node": "catalog:legacy" }, + }), + ).toBe("~7.120.0"); + expect( + getPackageVersion("@sentry/nextjs", { + dependencies: { "@sentry/nextjs": "catalog:next" }, + }), + ).toBe("9.0.0"); + }); + + it("handles regular version strings without catalog lookup", () => { + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "^7.0.0", + "@sentry/react": "~7.1.0", + "@sentry/cli": "2.0.0", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBe("^7.0.0"); + expect(getPackageVersion("@sentry/react", packageJson)).toBe("~7.1.0"); + expect(getPackageVersion("@sentry/cli", packageJson)).toBe("2.0.0"); + expect(mockedFs.existsSync).not.toHaveBeenCalled(); + }); + }); + }); + + describe("hasPackageInstalled", () => { + it("returns true if package is in dependencies", () => { + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "^7.0.0", + }, + }; + + expect(hasPackageInstalled("@sentry/node", packageJson)).toBe(true); + }); + + it("returns true if package is in devDependencies", () => { + const packageJson: PackageDotJson = { + devDependencies: { + "@sentry/cli": "^2.0.0", + }, + }; + + expect(hasPackageInstalled("@sentry/cli", packageJson)).toBe(true); + }); + + it("returns false if package is not installed", () => { + const packageJson: PackageDotJson = { + dependencies: {}, + }; + + expect(hasPackageInstalled("@sentry/node", packageJson)).toBe(false); + }); + + it("returns true if package uses catalog reference", () => { + const mockCwd = "/test/workspace/packages/app"; + vi.spyOn(process, "cwd").mockReturnValue(mockCwd); + + mockedFs.existsSync.mockImplementation((filepath: string) => { + return filepath === path.join("/test/workspace", "pnpm-workspace.yaml"); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sentry/node': ^7.100.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + }, + }; + + expect(hasPackageInstalled("@sentry/node", packageJson)).toBe(true); + }); + + it("returns false if package uses catalog reference but catalog does not have it", () => { + const mockCwd = "/test/workspace/packages/app"; + vi.spyOn(process, "cwd").mockReturnValue(mockCwd); + + mockedFs.existsSync.mockImplementation((filepath: string) => { + return filepath === path.join("/test/workspace", "pnpm-workspace.yaml"); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sentry/react': ^7.100.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + }, + }; + + expect(hasPackageInstalled("@sentry/node", packageJson)).toBe(false); + }); + }); + + describe("findInstalledPackageFromList", () => { + it("returns the first installed package from the list", () => { + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "^7.0.0", + }, + }; + + const result = findInstalledPackageFromList( + ["@sentry/cli", "@sentry/node", "@sentry/react"], + packageJson, + ); + + expect(result).toEqual({ + name: "@sentry/node", + version: "^7.0.0", + }); + }); + + it("returns undefined if no packages are installed", () => { + const packageJson: PackageDotJson = { + dependencies: {}, + }; + + const result = findInstalledPackageFromList( + ["@sentry/cli", "@sentry/node", "@sentry/react"], + packageJson, + ); + + expect(result).toBeUndefined(); + }); + + it("checks both dependencies and devDependencies", () => { + const packageJson: PackageDotJson = { + devDependencies: { + "@sentry/cli": "^2.0.0", + }, + }; + + const result = findInstalledPackageFromList( + ["@sentry/node", "@sentry/cli"], + packageJson, + ); + + expect(result).toEqual({ + name: "@sentry/cli", + version: "^2.0.0", + }); + }); + + it("returns first match in order provided", () => { + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "^7.0.0", + "@sentry/react": "^7.0.0", + }, + }; + + const result = findInstalledPackageFromList( + ["@sentry/react", "@sentry/node"], + packageJson, + ); + + expect(result).toEqual({ + name: "@sentry/react", + version: "^7.0.0", + }); + }); + + it("works with catalog references", () => { + const mockCwd = "/test/workspace/packages/app"; + vi.spyOn(process, "cwd").mockReturnValue(mockCwd); + + mockedFs.existsSync.mockImplementation((filepath: string) => { + return filepath === path.join("/test/workspace", "pnpm-workspace.yaml"); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sentry/node': ^7.100.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + }, + }; + + const result = findInstalledPackageFromList( + ["@sentry/cli", "@sentry/node"], + packageJson, + ); + + expect(result).toEqual({ + name: "@sentry/node", + version: "^7.100.0", + }); + }); + + it("returns undefined for empty package list", () => { + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "^7.0.0", + }, + }; + + const result = findInstalledPackageFromList([], packageJson); + + expect(result).toBeUndefined(); + }); + + it("skips packages with unresolvable catalog references", () => { + const mockCwd = "/test/workspace/packages/app"; + vi.spyOn(process, "cwd").mockReturnValue(mockCwd); + + mockedFs.existsSync.mockImplementation((filepath: string) => { + return filepath === path.join("/test/workspace", "pnpm-workspace.yaml"); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sentry/react': ^7.100.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + "@sentry/react": "catalog:", + }, + }; + + const result = findInstalledPackageFromList( + ["@sentry/node", "@sentry/react"], + packageJson, + ); + + // Should skip @sentry/node (unresolvable) and return @sentry/react + expect(result).toEqual({ + name: "@sentry/react", + version: "^7.100.0", + }); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/utils/package-manager.test.ts b/packages/cli/test/lib/wizard/utils/package-manager.test.ts new file mode 100644 index 0000000000..2eaec28053 --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/package-manager.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from "vitest"; +import { + _detectPackageManger, + NPM, + PNPM, + YARN_V1, +} from "../../../../src/lib/wizard/utils/package-manager.js"; + +describe("_detectPackageManager", () => { + it("returns the detected package manager if exactly one is found", () => { + const pnpm = { ...PNPM, detect: () => true }; + + const packageManager = _detectPackageManger([ + { ...NPM, detect: () => false }, + { ...YARN_V1, detect: () => false }, + pnpm, + ]); + + expect(packageManager).toBe(pnpm); + }); + + it("returns null if no package manager is found", () => { + const packageManager = _detectPackageManger([ + { ...NPM, detect: () => false }, + { ...YARN_V1, detect: () => false }, + ]); + expect(packageManager).toBeNull(); + }); + + it("returns null if multiple package managers are found", () => { + const packageManager = _detectPackageManger([ + { ...NPM, detect: () => true }, + { ...YARN_V1, detect: () => true }, + ]); + expect(packageManager).toBeNull(); + }); +}); diff --git a/packages/cli/test/lib/wizard/utils/project-data.test.ts b/packages/cli/test/lib/wizard/utils/project-data.test.ts new file mode 100644 index 0000000000..a691410ee2 --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/project-data.test.ts @@ -0,0 +1,252 @@ +/** + * Tests for the wizards' project selection on top of the CLI's login. + */ + +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + getAuthConfig: vi.fn(), + runInteractiveLogin: vi.fn(), + completeAgentHandoff: vi.fn(), + ensureScopesForAction: vi.fn(), + listOrganizations: vi.fn(), + listProjects: vi.fn(), + getProject: vi.fn(), + getProjectKeys: vi.fn(), + createProjectWithDsn: vi.fn(), + createProjectWithAutoTeam: vi.fn(), + resolveOrCreateTeam: vi.fn(), + createOrgAuthToken: vi.fn(), + select: vi.fn(), + text: vi.fn(), +})); + +vi.mock("@clack/prompts", () => ({ + isCancel: vi.fn(() => false), + cancel: vi.fn(), + outro: vi.fn(), + select: mocks.select, + text: mocks.text, + spinner: vi.fn(() => ({ start: vi.fn(), stop: vi.fn() })), + log: { + info: vi.fn(), + step: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + }, +})); +vi.mock("../../../../src/lib/db/auth.js", async (importOriginal) => ({ + ...(await importOriginal()), + getAuthConfig: mocks.getAuthConfig, +})); +vi.mock("../../../../src/lib/interactive-login.js", () => ({ + runInteractiveLogin: mocks.runInteractiveLogin, +})); +vi.mock("../../../../src/lib/agent-handoff.js", () => ({ + completeAgentHandoff: mocks.completeAgentHandoff, +})); +vi.mock("../../../../src/lib/auto-auth.js", () => ({ + assertAutoLoginHostTrusted: vi.fn(), +})); +vi.mock("../../../../src/lib/scope-recovery.js", () => ({ + ensureScopesForAction: mocks.ensureScopesForAction, +})); +vi.mock("../../../../src/lib/api/organizations.js", () => ({ + listOrganizations: mocks.listOrganizations, +})); +vi.mock("../../../../src/lib/api/org-auth-tokens.js", () => ({ + createOrgAuthToken: mocks.createOrgAuthToken, +})); +vi.mock("../../../../src/lib/resolve-team.js", () => ({ + resolveOrCreateTeam: mocks.resolveOrCreateTeam, +})); +vi.mock("../../../../src/lib/api/projects.js", async (importOriginal) => ({ + ...(await importOriginal< + typeof import("../../../../src/lib/api/projects.js") + >()), + listProjects: mocks.listProjects, + getProject: mocks.getProject, + getProjectKeys: mocks.getProjectKeys, + createProjectWithDsn: mocks.createProjectWithDsn, + createProjectWithAutoTeam: mocks.createProjectWithAutoTeam, +})); + +import { ApiError, WizardExitError } from "../../../../src/lib/errors.js"; +import { + DUMMY_AUTH_TOKEN, + getOrAskForProjectData, +} from "../../../../src/lib/wizard/utils/project-data.js"; +import type { SentryProjectData } from "../../../../src/lib/wizard/utils/types.js"; + +const ORG = { id: "1", slug: "acme", name: "Acme" }; +const PROJECT = { id: "42", slug: "web", name: "web", platform: "javascript" }; +const KEY = { + id: "k1", + name: "Default", + isActive: true, + dsn: { public: "https://abc@o1.ingest.sentry.io/42", secret: "" }, +}; + +beforeEach(() => { + vi.clearAllMocks(); + vi.stubEnv("SENTRY_HANDOFF", ""); + mocks.getAuthConfig.mockReturnValue({ token: "stored" }); + mocks.listOrganizations.mockResolvedValue([ORG]); + mocks.getProject.mockResolvedValue(PROJECT); + mocks.getProjectKeys.mockResolvedValue([KEY]); + mocks.ensureScopesForAction.mockResolvedValue("ready"); + mocks.createOrgAuthToken.mockResolvedValue({ token: "sntrys_new" }); +}); + +describe("getOrAskForProjectData", () => { + it("needs no login in Spotlight mode", async () => { + const result = await getOrAskForProjectData({ + telemetryEnabled: false, + spotlight: true, + }); + + expect(result).toEqual({ spotlight: true }); + expect(mocks.listOrganizations).not.toHaveBeenCalled(); + }); + + it("returns a preselected project without asking", async () => { + const project: SentryProjectData = { + id: "7", + slug: "app", + organization: { id: "1", name: "Acme", slug: "acme" }, + keys: [{ dsn: { public: "https://k@sentry.io/7" } }], + }; + + const result = await getOrAskForProjectData({ + telemetryEnabled: false, + preSelectedProject: { project, authToken: "tok", selfHosted: false }, + }); + + expect(result).toEqual({ + spotlight: false, + selfHosted: false, + sentryUrl: "https://sentry.io/", + authToken: "tok", + selectedProject: project, + }); + expect(mocks.listOrganizations).not.toHaveBeenCalled(); + }); + + it("uses the stored login and the --org and --project slugs", async () => { + const result = await getOrAskForProjectData({ + telemetryEnabled: false, + saas: true, + orgSlug: "acme", + projectSlug: "web", + }); + + expect(mocks.runInteractiveLogin).not.toHaveBeenCalled(); + expect(mocks.select).not.toHaveBeenCalled(); + expect(mocks.getProject).toHaveBeenCalledWith("acme", "web"); + expect(result).toEqual({ + spotlight: false, + selfHosted: false, + sentryUrl: "https://sentry.io/", + authToken: "sntrys_new", + selectedProject: { + id: "42", + slug: "web", + organization: ORG, + keys: [{ dsn: { public: KEY.dsn.public } }], + }, + }); + }); + + it("asks for the project when the --project slug is not found", async () => { + mocks.getProject.mockRejectedValue(new ApiError("Not found", 404)); + mocks.listProjects.mockResolvedValue([PROJECT]); + mocks.select.mockResolvedValueOnce(PROJECT); + + const result = await getOrAskForProjectData({ + telemetryEnabled: false, + saas: true, + orgSlug: "acme", + projectSlug: "missing", + }); + + expect(mocks.listProjects).toHaveBeenCalledWith("acme"); + expect(result).toMatchObject({ selectedProject: { slug: "web" } }); + }); + + it("creates a project for the wizard's platform", async () => { + mocks.listProjects.mockResolvedValue([]); + mocks.select.mockImplementationOnce( + (options: { options: { value: unknown }[] }) => + Promise.resolve(options.options[0]?.value), + ); + mocks.text.mockResolvedValueOnce("my app"); + mocks.resolveOrCreateTeam.mockResolvedValue({ slug: "acme" }); + mocks.createProjectWithDsn.mockResolvedValue({ + project: { ...PROJECT, slug: "my-app" }, + }); + + const result = await getOrAskForProjectData( + { telemetryEnabled: false, saas: true, orgSlug: "acme" }, + "javascript-nextjs", + ); + + expect(mocks.createProjectWithDsn).toHaveBeenCalledWith("acme", "acme", { + name: "my app", + platform: "javascript-nextjs", + }); + expect(result).toMatchObject({ selectedProject: { slug: "my-app" } }); + }); + + it("writes a placeholder token when no auth token can be created", async () => { + mocks.ensureScopesForAction.mockResolvedValue("unavailable"); + + const result = await getOrAskForProjectData({ + telemetryEnabled: false, + saas: true, + orgSlug: "acme", + projectSlug: "web", + }); + + expect(mocks.createOrgAuthToken).not.toHaveBeenCalled(); + expect(result).toMatchObject({ authToken: DUMMY_AUTH_TOKEN }); + }); + + it("logs in with the device flow when there is no stored login", async () => { + mocks.getAuthConfig.mockReturnValue(undefined); + mocks.runInteractiveLogin.mockResolvedValue({ method: "oauth" }); + + await getOrAskForProjectData({ + telemetryEnabled: false, + saas: true, + orgSlug: "acme", + projectSlug: "web", + }); + + expect(mocks.runInteractiveLogin).toHaveBeenCalledWith({ + scope: expect.stringContaining("org:tokens"), + }); + }); + + it("stops when the login fails", async () => { + mocks.getAuthConfig.mockReturnValue(undefined); + mocks.runInteractiveLogin.mockResolvedValue(null); + + await expect( + getOrAskForProjectData({ telemetryEnabled: false, saas: true }), + ).rejects.toThrow(WizardExitError); + }); + + it("claims an agent handoff and uses its org", async () => { + vi.stubEnv("SENTRY_HANDOFF", "handoff-code"); + mocks.completeAgentHandoff.mockResolvedValue({ organizationSlug: "acme" }); + + await getOrAskForProjectData({ + telemetryEnabled: false, + saas: true, + projectSlug: "web", + }); + + expect(mocks.completeAgentHandoff).toHaveBeenCalledWith("handoff-code"); + expect(mocks.getProject).toHaveBeenCalledWith("acme", "web"); + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d31e4395bb..363032cd0d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -792,6 +792,9 @@ importers: jpeg-js: specifier: ^0.4.4 version: 0.4.4 + magicast: + specifier: 0.2.11 + version: 0.2.11 marked: specifier: 'catalog:' version: 15.0.12 @@ -5483,6 +5486,10 @@ packages: asciinema-player@3.18.1: resolution: {integrity: sha512-H3blHwZYerDkjUVNABB0zjIzZhZu+JT0/FXT7Skc+4cpa2i7bDab49uOztsIguej4Ppfw6JS0V8J5/6VNqIIkQ==} + ast-types@0.16.3: + resolution: {integrity: sha512-FvWoWYfSCM6kRxCSH+MGLHIKKGRL6A6AW7Zek2O32REPQRdg131428uRTKMBYAeRd3XXAaHDS60Wpri7CdKDrA==} + engines: {node: '>=4'} + ast-v8-to-istanbul@1.0.7: resolution: {integrity: sha512-kFL68AG6ajd8fg248zwM9GQrUWEp79gsmjum34OEXjs4yHuUMZfYKwOLW9GMmB4oNvVrj+EAGxsP7ye2UR9UlA==} @@ -6095,6 +6102,11 @@ packages: resolution: {integrity: sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==} engines: {node: '>=12'} + esprima@4.0.1: + resolution: {integrity: sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==} + engines: {node: '>=4'} + hasBin: true + estree-util-attach-comments@3.0.0: resolution: {integrity: sha512-cKUwm/HUcTDsYh/9FgnuFqpfquUbwIqwKM26BVCGDPVgvaCl/nDCCjUfiLlx6lsEZ3Z4RFxNbOQ60pkaEwFxGw==} @@ -6835,6 +6847,9 @@ packages: magic-string@1.4.5: resolution: {integrity: sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==} + magicast@0.2.11: + resolution: {integrity: sha512-6saXbRDA1HMkqbsvHOU6HBjCVgZT460qheRkLhJQHWAbhXoWESI3Kn/dGGXyKs15FFKR85jsUqFx2sMK0wy/5g==} + magicast@0.5.5: resolution: {integrity: sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==} @@ -7599,6 +7614,10 @@ packages: resolution: {integrity: sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==} engines: {node: '>= 20.19.0'} + recast@0.23.21: + resolution: {integrity: sha512-mFAyJq9vUbSTARLZUvAEf1z3YxlvAwswbmxMx2mPA/MSm4KmpwvwvhsH/NIrZhyOuwD60Lzyw2qh83uCbgTPYw==} + engines: {node: '>= 4'} + recma-build-jsx@1.0.0: resolution: {integrity: sha512-8GtdyqaBcDfva+GUKDr3nev3VpKAhup1+RvkMvUxURHpW7QyIvk9F5wz7Vzo06CEMSilw6uArgRqhpiUcWp8ew==} @@ -7926,6 +7945,10 @@ packages: resolution: {integrity: sha512-LbrmJOMUSdEVxIKvdcJzQC+nQhe8FUZQTXQy6+I75skNgn3OoQ0DZA8YnFa7gp8tqtL3KPf1kmo0R5DoApeSGQ==} engines: {node: '>=0.10.0'} + source-map@0.6.1: + resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==} + engines: {node: '>=0.10.0'} + source-map@0.7.6: resolution: {integrity: sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==} engines: {node: '>= 12'} @@ -8050,6 +8073,9 @@ packages: tiny-inflate@1.0.3: resolution: {integrity: sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==} + tiny-invariant@1.3.3: + resolution: {integrity: sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==} + tinybench@6.2.2: resolution: {integrity: sha512-nIZ2N2dFpjBsg2hgitKu7mA+FvsIJuGJOwysRngmVRRmWgR/UyPjwJj8c/fT/dhm8EkHnF5EOogRf+0Z2qrimA==} engines: {node: '>=20.0.0'} @@ -12410,6 +12436,10 @@ snapshots: dependencies: solid-js: 1.9.19 + ast-types@0.16.3: + dependencies: + tslib: 2.8.1 + ast-v8-to-istanbul@1.0.7: dependencies: '@jridgewell/trace-mapping': 0.3.31 @@ -13092,6 +13122,8 @@ snapshots: escape-string-regexp@5.0.0: {} + esprima@4.0.1: {} + estree-util-attach-comments@3.0.0: dependencies: '@types/estree': 1.0.9 @@ -13944,6 +13976,12 @@ snapshots: dependencies: '@jridgewell/sourcemap-codec': 1.6.0 + magicast@0.2.11: + dependencies: + '@babel/parser': 7.29.14 + '@babel/types': 7.29.14 + recast: 0.23.21 + magicast@0.5.5: dependencies: '@babel/parser': 7.29.14 @@ -15013,6 +15051,14 @@ snapshots: readdirp@5.1.1: {} + recast@0.23.21: + dependencies: + ast-types: 0.16.3 + esprima: 4.0.1 + source-map: 0.6.1 + tiny-invariant: 1.3.3 + tslib: 2.8.1 + recma-build-jsx@1.0.0: dependencies: '@types/estree': 1.0.9 @@ -15575,6 +15621,8 @@ snapshots: source-map@0.5.7: {} + source-map@0.6.1: {} + source-map@0.7.6: {} space-separated-tokens@2.0.2: {} @@ -15710,6 +15758,8 @@ snapshots: tiny-inflate@1.0.3: {} + tiny-invariant@1.3.3: {} + tinybench@6.2.2: {} tinyclip@1.0.3: {} From 76e162b5171220390d3222e30bee02e44b79c6ba Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:52:16 +0000 Subject: [PATCH 02/20] feat(cli): add the wizard's shared AST and URL helpers Port `ast-utils` and `url` from getsentry/sentry-wizard into `src/lib/wizard/utils/`. The SvelteKit, Remix, React Router, Angular, Nuxt, source maps, Cloudflare, React Native and Android wizards all use them, so they land once here and the platform PRs that follow build on them in parallel. `ast-utils` edits recast ASTs, so recast and ast-types become direct dev dependencies; both already came in through magicast. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- packages/cli/package.json | 2 + .../cli/src/lib/wizard/utils/ast-utils.ts | 365 ++++++++++++++++++ packages/cli/src/lib/wizard/utils/url.ts | 29 ++ .../test/lib/wizard/utils/ast-utils.test.ts | 297 ++++++++++++++ pnpm-lock.yaml | 6 + 5 files changed, 699 insertions(+) create mode 100644 packages/cli/src/lib/wizard/utils/ast-utils.ts create mode 100644 packages/cli/src/lib/wizard/utils/url.ts create mode 100644 packages/cli/test/lib/wizard/utils/ast-utils.test.ts diff --git a/packages/cli/package.json b/packages/cli/package.json index ebda846304..0e1e679f24 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -120,6 +120,7 @@ "@types/yauzl": "3.4.0", "@typescript/typescript6": "catalog:", "@vitest/coverage-v8": "catalog:", + "ast-types": "^0.16.3", "binpatch": "^0.4.2", "chalk": "^5.6.2", "cli-highlight": "^2.1.11", @@ -141,6 +142,7 @@ "pngjs": "^7.0.0", "pretty-ms": "^9.3.0", "qrcode-terminal": "^0.12.0", + "recast": "^0.23.21", "semver": "^7.8.5", "shell-quote": "^1.11.0", "string-width": "^8.2.1", diff --git a/packages/cli/src/lib/wizard/utils/ast-utils.ts b/packages/cli/src/lib/wizard/utils/ast-utils.ts new file mode 100644 index 0000000000..05929e5203 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/ast-utils.ts @@ -0,0 +1,365 @@ +/** + * Helpers that find and change nodes in a recast AST, shared by the wizards + * that edit JavaScript and TypeScript config files. + */ + +import { existsSync } from "node:fs"; + +import recast from "recast"; + +import { debug } from "./debug.js"; +import type { namedTypes as t } from "ast-types"; + +const b = recast.types.builders; + +/** + * Checks if a file where we don't know its concrete file type yet exists + * and returns the full path to the file with the correct file type. + */ +export function findFile( + filePath: string, + fileTypes: string[] = [".js", ".ts", ".mjs", ".cjs"], +): string | undefined { + return fileTypes + .map((type) => `${filePath}${type}`) + .find((file) => existsSync(file)); +} + +/** + * checks for require('@sentry/*') syntax + */ +export function hasSentryContent(program: t.Program): boolean { + let foundSentry: boolean | undefined = false; + recast.visit(program, { + visitStringLiteral(path) { + foundSentry = foundSentry || path.node.value.startsWith("@sentry/"); + this.traverse(path); + }, + visitLiteral(path) { + foundSentry = + foundSentry || path.node.value?.toString().startsWith("@sentry/"); + this.traverse(path); + }, + }); + + return !!foundSentry; +} + +/** + * Searches for a property of an ObjectExpression by name + * + * @param object the ObjectExpression to search in + * @param name the name of the property to search for + * + * @returns the property if it exists + */ +export function getObjectProperty( + object: t.ObjectExpression, + name: string, +): t.Property | undefined { + return object.properties.find((p): p is t.Property => { + const isObjectProp = p.type === "Property" || p.type === "ObjectProperty"; + + if (!isObjectProp) { + return false; + } + + const hasMatchingLiteralKey = + (p.key.type === "Literal" || p.key.type === "StringLiteral") && + p.key.value === name; + + if (hasMatchingLiteralKey) { + return true; + } + + // has matching identifier key + return p.key.type === "Identifier" && p.key.name === name; + }); +} + +/** + * Attempts to find a property of an ObjectExpression by name. If it doesn't exist, + * the property will be added to the ObjectExpression with the provided default value. + * + * @param object the parent object expression to search in + * @param name the name of the property to search for + * @param defaultValue the default value to set if the property doesn't exist + * + * @returns the + */ +export function getOrSetObjectProperty( + object: t.ObjectExpression, + name: string, + defaultValue: + | t.Literal + | t.BooleanLiteral + | t.StringLiteral + | t.ObjectExpression, +): t.Property { + const existingProperty = getObjectProperty(object, name); + + if (existingProperty) { + return existingProperty; + } + + const newProperty = b.property.from({ + kind: "init", + key: b.stringLiteral(name), + value: defaultValue, + }); + + object.properties.push(newProperty); + + return newProperty; +} + +/** + * Sets a property of an ObjectExpression if it exists, otherwise adds it + * to the ObjectExpression. Optionally, a comment can be added to the + * property. + * + * @param object the ObjectExpression to set the property on + * @param name the name of the property to set + * @param value the value of the property to set + * @param comment (optional) a comment to add to the property + */ +export function setOrUpdateObjectProperty( + object: t.ObjectExpression, + name: string, + value: + | t.Literal + | t.BooleanLiteral + | t.StringLiteral + | t.ObjectExpression + | t.ArrayExpression, + comment?: string, +): void { + const newComments = comment + ?.split("\n") + .map((c) => b.commentLine(` ${c}`, true, false)); + + const existingProperty = getObjectProperty(object, name); + + if (existingProperty) { + existingProperty.value = value; + if (newComments) { + existingProperty.comments = [ + ...(existingProperty.comments ?? []), + ...newComments, + ]; + } + } else { + object.properties.push( + b.objectProperty.from({ + key: b.stringLiteral(name), + value, + ...(newComments && { + comments: newComments, + }), + }), + ); + } +} + +type JsonCParseResult = + | { + jsonObject: t.ObjectExpression; + ast: t.Program; + } + | { + jsonObject: undefined; + ast: undefined; + }; + +/** + * Parses a JSON string with (potential) comments (JSON-C) and returns the JS AST + * that can be walked and modified with recast like a normal JS AST. + * + * This is done by wrapping the JSON-C string in parentheses, thereby making it + * a JS `Program` with an `ExpressionStatement` as its body. The expression is then + * extracted from the AST and returned alongside the AST. + * + * To preserve as much original formatting as possible, the returned `ast` + * property should be passed to {@link `printJsonC`} to get the JSON-C string back. + * + * If the input is not valid JSON-C, the result will be undefined. + * + * @see {@link JsonCParseResult} + * + * @param jsonString a JSON-C string + * + * @returns a {@link JsonCParseResult}, containing either the JSON-C object and the AST or undefined in both cases + */ +export function parseJsonC(jsonString: string): JsonCParseResult { + try { + const jsTsConfig = `(${jsonString})`; + // no idea why recast returns any here, this is dumb :/ + const ast = recast.parse(jsTsConfig.toString()).program as t.Program; + + const statement = ast.body[0]; + const jsonObject = + statement?.type === "ExpressionStatement" && + statement.expression.type === "ObjectExpression" + ? statement.expression + : undefined; + + if (jsonObject) { + return { jsonObject, ast }; + } + } catch (error) { + // Not valid JSON-C: the caller handles the undefined result. + debug(error); + return { jsonObject: undefined, ast: undefined }; + } + return { jsonObject: undefined, ast: undefined }; +} + +/** + * Takes the AST of a parsed JSON-C "program" and returns the JSON-C string without + * any of the temporary JS wrapper code that was previously applied. + * + * Only use this in conjunction with {@link `parseJsonC`} + * + * @param ast the `ast` returned from {@link `parseJsonC`} + * + * @returns the JSON-C string + */ +export function printJsonC(ast: t.Program): string { + const js = recast.print(ast).code; + return js.substring(1, js.length - 1); +} + +/** + * Walks the program body and returns index of the last variable assignment initialized by require statement. + * Only counts top level require statements. + * + * @returns index of the last `const foo = require('bar');` statement or -1 if none was found. + */ +export function getLastRequireIndex(program: t.Program): number { + let lastRequireIdex = -1; + program.body.forEach((s, i) => { + const declaration = + s.type === "VariableDeclaration" ? s.declarations[0] : undefined; + if ( + declaration?.type === "VariableDeclarator" && + declaration.init?.type === "CallExpression" && + declaration.init.callee.type === "Identifier" && + declaration.init.callee.name === "require" + ) { + lastRequireIdex = i; + } + }); + return lastRequireIdex; +} + +/** + * Safely checks if a callee is an identifier with the given name + * Prevents crashes when accessing callee.name on non-identifier nodes + */ +export function safeCalleeIdentifierMatch( + callee: unknown, + name: string, +): boolean { + return Boolean( + callee && + typeof callee === "object" && + "type" in callee && + (callee as { type: string }).type === "Identifier" && + "name" in callee && + (callee as { name: string }).name === name, + ); +} + +/** + * Safely gets the name of an identifier node + * Returns null if the node is not an identifier or is undefined + */ +export function safeGetIdentifierName(node: unknown): string | null { + return node && + typeof node === "object" && + "type" in node && + node.type === "Identifier" && + "name" in node + ? String(node.name) + : null; +} + +/** + * Safely access function body array with proper validation + * Prevents crashes when accessing body.body on nodes that don't have a body + */ +export function safeGetFunctionBody(node: unknown): t.Statement[] | null { + if (!node || typeof node !== "object" || !("body" in node)) { + return null; + } + + const nodeBody = node.body; + if (!nodeBody || typeof nodeBody !== "object" || !("body" in nodeBody)) { + return null; + } + + const bodyArray = nodeBody.body; + return Array.isArray(bodyArray) ? (bodyArray as t.Statement[]) : null; +} + +/** + * Safely insert statement before last statement in function body + * Typically used to insert code before a return statement + * Returns true if insertion was successful, false otherwise + */ +export function safeInsertBeforeReturn( + body: t.Statement[], + statement: t.Statement, +): boolean { + if (body.length === 0) { + return false; + } + + // Insert before the last statement (typically a return statement) + const insertIndex = Math.max(0, body.length - 1); + body.splice(insertIndex, 0, statement); + return true; +} + +/** + * Finds a property in an ObjectExpression by name. + * Commonly used for traversing Vite/React Router config objects. + * + * @param configObj - The ObjectExpression to search + * @param name - The property name to find + * @returns The matching ObjectProperty, or undefined if not found + */ +export function findProperty( + configObj: t.ObjectExpression, + name: string, +): t.ObjectProperty | undefined { + return configObj.properties.find( + (p) => + p.type === "ObjectProperty" && + p.key.type === "Identifier" && + p.key.name === name, + ) as t.ObjectProperty | undefined; // Safe: predicate guarantees type +} + +/** + * Preserves trailing newline from original content if present. + * Code generators like magicast/recast don't preserve trailing newlines, + * so this ensures we don't unnecessarily modify user files. + * + * @param originalContent - The original file content + * @param generatedCode - The code generated by AST transformation + * @returns The generated code with trailing newline preserved if original had one + */ +export function preserveTrailingNewline( + originalContent: string, + generatedCode: string, +): string { + const hadTrailingNewline = originalContent.endsWith("\n"); + const hasTrailingNewline = generatedCode.endsWith("\n"); + + if (hadTrailingNewline && !hasTrailingNewline) { + return generatedCode + "\n"; + } + + return generatedCode; +} diff --git a/packages/cli/src/lib/wizard/utils/url.ts b/packages/cli/src/lib/wizard/utils/url.ts new file mode 100644 index 0000000000..6d3af99d64 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/url.ts @@ -0,0 +1,29 @@ +/** + * Sentry URLs the wizards print after setup. + */ + +/** + * Returns the url to the Sentry project stream. + * + * Example: https://org-slug.sentry.io/issues/?project=1234567 + */ +export function getIssueStreamUrl({ + url, + orgSlug, + projectId, +}: { + url: string; + orgSlug: string; + projectId: string; +}): string { + const urlObject = new URL(url); + if (urlObject.host === "sentry.io") { + urlObject.host = `${orgSlug}.${urlObject.host}`; + urlObject.pathname = "/issues/"; + } else { + urlObject.pathname = `/organizations/${orgSlug}/issues/`; + } + urlObject.searchParams.set("project", projectId); + + return urlObject.toString(); +} diff --git a/packages/cli/test/lib/wizard/utils/ast-utils.test.ts b/packages/cli/test/lib/wizard/utils/ast-utils.test.ts new file mode 100644 index 0000000000..f42f1de88a --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/ast-utils.test.ts @@ -0,0 +1,297 @@ +import { + getObjectProperty, + getOrSetObjectProperty, + hasSentryContent, + parseJsonC, + preserveTrailingNewline, + printJsonC, + setOrUpdateObjectProperty, +} from "../../../../src/lib/wizard/utils/ast-utils.js"; + +import recast from "recast"; +const b = recast.types.builders; + +import { describe, it, expect } from "vitest"; + +describe("hasSentryContent", () => { + it.each([ + ` + const { sentryVitePlugin } = require("@sentry/bundler-plugins/vite"); + const somethingelse = require('gs'); + `, + ` + import { sentryVitePlugin } from "@sentry/bundler-plugins/vite"; + import * as somethingelse from 'gs'; + + export default { + plugins: [sentryVitePlugin()] + } + `, + ])( + "returns true if a require('@sentry/') call was found in the parsed module", + (code) => { + // recast.parse returns a Program node (or fails) but it's badly typed as any + const program = recast.parse(code) + .program as recast.types.namedTypes.Program; + expect(hasSentryContent(program)).toBe(true); + }, + ); + + it.each([ + `const whatever = require('something')`, + `// const {sentryWebpackPlugin} = require('@sentry/bundler-plugins/webpack')`, + `const {sAntryWebpackPlugin} = require('webpack-plugin-@sentry')`, + ` + import * as somethingelse from 'gs'; + export default { + plugins: [] + } + `, + `import * as somethingelse from 'gs'; + // import { sentryVitePlugin } from "@sentry/bundler-plugins/vite" + export default { + plugins: [] + } + `, + `import * as thirdPartyVitePlugin from "vite-plugin-@sentry" + export default { + plugins: [thirdPartyVitePlugin()] + } + `, + ])( + "returns false if the file doesn't contain any require('@sentry/') calls", + (code) => { + // recast.parse returns a Program node (or fails) but it's badly typed as any + const program = recast.parse(code) + .program as recast.types.namedTypes.Program; + expect(hasSentryContent(program)).toBe(false); + }, + ); +}); + +describe("getObjectProperty", () => { + it.each([ + [ + "literal", + b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + b.objectProperty( + b.stringLiteral("needle"), + b.stringLiteral("haystack"), + ), + ]), + ], + [ + "stringLiteral", + b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + b.objectProperty(b.literal("needle"), b.stringLiteral("haystack")), + ]), + ], + [ + "identifier", + b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + b.objectProperty(b.identifier("needle"), b.stringLiteral("haystack")), + ]), + ], + ])("returns the poperty (%s) if it exists", (_, object) => { + const property = getObjectProperty(object, "needle"); + expect(property).toBeDefined(); + // @ts-expect-error we know it's defined due to the expect above + expect(recast.print(property).code).toEqual( + expect.stringContaining("needle"), + ); + }); + + it("returns undefined if the property does not exist", () => { + const object = b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + ]); + const property = getObjectProperty(object, "needle"); + expect(property).toBeUndefined(); + }); + + it("handles objects without simple properties", () => { + const object = b.objectExpression([b.spreadElement(b.identifier("foo"))]); + const property = getObjectProperty(object, "needle"); + expect(property).toBeUndefined(); + }); +}); + +describe("getOrSetObjectProperty", () => { + it("returns the property if it exists", () => { + const object = b.objectExpression([ + b.objectProperty(b.identifier("needle"), b.stringLiteral("haystack")), + ]); + + const property = getOrSetObjectProperty( + object, + "needle", + b.stringLiteral("nope"), + ); + + expect(property).toBeDefined(); + expect(property.type).toBe("ObjectProperty"); + // @ts-expect-error we know its type + expect(property.key.name).toBe("needle"); + // @ts-expect-error we know its type + expect(property.value.value).toBe("haystack"); + }); + + it("adds the property if it does not exist", () => { + const object = b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + ]); + + const property = getOrSetObjectProperty( + object, + "needle", + b.stringLiteral("haystack"), + ); + + expect(property).toBeDefined(); + expect(property.type).toBe("Property"); + // @ts-expect-error we know its type + expect(property.key.value).toBe("needle"); + // @ts-expect-error we know its type + expect(property.value.value).toBe("haystack"); + }); +}); + +describe("setOrUpdateObjectProperty", () => { + it("sets a new property if it does not exist yet", () => { + const object = b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + ]); + + setOrUpdateObjectProperty(object, "needle", b.stringLiteral("haystack")); + + expect(getObjectProperty(object, "needle")).toBeDefined(); + }); + + it("updates an existing property if it exists", () => { + const object = b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + b.objectProperty(b.identifier("needle"), b.stringLiteral("haystack")), + ]); + + setOrUpdateObjectProperty(object, "needle", b.stringLiteral("haystack2")); + + const property = getObjectProperty(object, "needle"); + // @ts-expect-error it must be defiend, otherwise we fail anyway + expect(property?.value.value).toBe("haystack2"); + }); + + it("adds a comment to the existing property if provided", () => { + const object = b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + ]); + + setOrUpdateObjectProperty( + object, + "needle", + b.stringLiteral("haystack"), + "This is a comment", + ); + + const property = getObjectProperty(object, "needle"); + expect(property?.comments).toHaveLength(1); + // @ts-expect-error it must be defiend, otherwise we fail anyway + expect(property?.comments[0].value).toBe(" This is a comment"); + }); + + it("adds a comment to the new property if provided", () => { + const object = b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + ]); + + setOrUpdateObjectProperty( + object, + "needle", + b.stringLiteral("haystack"), + "This is a comment", + ); + + const property = getObjectProperty(object, "needle"); + expect(property?.comments).toHaveLength(1); + // @ts-expect-error it must be defiend, otherwise we fail anyway + expect(property?.comments[0].value).toBe(" This is a comment"); + }); +}); + +describe("preserveTrailingNewline", () => { + it("adds trailing newline if original had one but generated does not", () => { + const original = "const foo = 1;\n"; + const generated = "const foo = 1;"; + expect(preserveTrailingNewline(original, generated)).toBe( + "const foo = 1;\n", + ); + }); + + it("does not add trailing newline if original did not have one", () => { + const original = "const foo = 1;"; + const generated = "const foo = 1;"; + expect(preserveTrailingNewline(original, generated)).toBe("const foo = 1;"); + }); + + it("does not double trailing newline if both already have one", () => { + const original = "const foo = 1;\n"; + const generated = "const foo = 1;\n"; + expect(preserveTrailingNewline(original, generated)).toBe( + "const foo = 1;\n", + ); + }); + + it("does not remove trailing newline if original did not have one but generated does", () => { + const original = "const foo = 1;"; + const generated = "const foo = 1;\n"; + expect(preserveTrailingNewline(original, generated)).toBe( + "const foo = 1;\n", + ); + }); +}); + +describe("parse and print JSON-C", () => { + it.each([ + ["simple JSON", "{'foo': 'bar'}"], + [ + "JSON-C with inline comment", + ` + { + "foo": "bar" // with an inline comment + } + `, + ], + [ + "JSON-C with multiple comments", + ` + /* + * let's throw in a block comment for good measure + */ + { + // one line comment + "foo": "bar", // another inline comment + /* one more here */ + "dogs": /* and here */ "awesome", + } + /* and here */ + `, + ], + ])(`parses and prints JSON-C (%s)`, (_, json) => { + const { ast, jsonObject } = parseJsonC(json); + expect(ast?.type).toBe("Program"); + expect(jsonObject).toBeDefined(); + expect(jsonObject?.type).toBe("ObjectExpression"); + // @ts-expect-error we know it's defined due to the expect above + expect(printJsonC(ast)).toEqual(json); + }); + + it("returns undefined if the input is not valid JSON-C", () => { + const { ast, jsonObject } = parseJsonC(`{ + "invalid": // "json" + }`); + expect(ast).toBeUndefined(); + expect(jsonObject).toBeUndefined(); + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 363032cd0d..aa38f64862 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -759,6 +759,9 @@ importers: '@vitest/coverage-v8': specifier: 'catalog:' version: 5.0.5(vitest@5.0.5) + ast-types: + specifier: ^0.16.3 + version: 0.16.3 binpatch: specifier: ^0.4.2 version: 0.4.2 @@ -822,6 +825,9 @@ importers: qrcode-terminal: specifier: ^0.12.0 version: 0.12.0 + recast: + specifier: ^0.23.21 + version: 0.23.21 semver: specifier: ^7.8.5 version: 7.8.5 From 0113841962a00723228ae9299ee17ac663191c81 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:11:49 +0000 Subject: [PATCH 03/20] feat(cli): reject the wizard's removed sign-up flags `sentry wizard` logs in with the CLI's login, which has no sign-up or partner step, so `--signup`, `--promo-code` and `--coming-from` no longer do anything. Passing one now fails with a message that points to https://sentry.io/signup/ instead of being accepted silently. `promoCode` and `comingFrom` leave `WizardOptions`, the welcome banner and `setupCI`, which loses its Vercel partner branch. The help text and the docs say which `@sentry/wizard` flags were removed. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .../cli-docs/src/fragments/commands/wizard.md | 9 ++- .../skills/sentry-cli/references/wizard.md | 1 - packages/cli/src/commands/wizard.ts | 58 ++++++++++++++----- .../src/lib/wizard/nextjs/nextjs-wizard.ts | 7 +-- packages/cli/src/lib/wizard/sourcemaps/ci.ts | 14 +---- .../cli/src/lib/wizard/utils/clack/index.ts | 5 -- packages/cli/src/lib/wizard/utils/types.ts | 13 ----- packages/cli/test/commands/wizard.test.ts | 24 +++++++- 8 files changed, 77 insertions(+), 54 deletions(-) diff --git a/apps/cli-docs/src/fragments/commands/wizard.md b/apps/cli-docs/src/fragments/commands/wizard.md index 1e49305bdb..d754b8845b 100644 --- a/apps/cli-docs/src/fragments/commands/wizard.md +++ b/apps/cli-docs/src/fragments/commands/wizard.md @@ -20,5 +20,10 @@ changes nothing. `sentry wizard` takes the same integrations and flags as `npx @sentry/wizard`, so `npx @sentry/wizard -i nextjs` and -`sentry wizard -i nextjs` do the same thing. The Cordova and Electron wizards -were removed; follow their setup guides in the Sentry docs instead. +`sentry wizard -i nextjs` do the same thing. These were removed: + +- The sign-up flags `--signup`, `--promo-code` and `--coming-from`. Passing one + fails with an explanation. Sign up at https://sentry.io/signup/ (and apply a + promo code there), then run the wizard. +- The Cordova and Electron wizards. Follow their setup guides in the Sentry + docs instead. diff --git a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md index 37be843225..7e8405f3e0 100644 --- a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md +++ b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md @@ -26,7 +26,6 @@ Set up the Sentry SDK in your project interactively - `--ignore-git-changes - Don't ask before changing a project with uncommitted changes` - `--disable-telemetry - Don't send telemetry about this run to Sentry` - `--debug - Print the wizard's debug output` -- `--promo-code - Promo code to apply when signing up` **Examples:** diff --git a/packages/cli/src/commands/wizard.ts b/packages/cli/src/commands/wizard.ts index b48e6a6d2e..2b291ef787 100644 --- a/packages/cli/src/commands/wizard.ts +++ b/packages/cli/src/commands/wizard.ts @@ -20,7 +20,7 @@ import { parseUrl, } from "../lib/completion-target.js"; import { getEnv } from "../lib/env.js"; -import { WizardExitError } from "../lib/errors.js"; +import { ValidationError, WizardExitError } from "../lib/errors.js"; import { disableTelemetryForRun, isTelemetryEnabled, @@ -39,14 +39,39 @@ type WizardFlags = { readonly "disable-telemetry": boolean; readonly "force-install": boolean; readonly "ignore-git-changes": boolean; + readonly signup: boolean; readonly "promo-code"?: string; readonly "coming-from"?: string; - readonly signup: boolean; readonly "skip-connect": boolean; readonly quiet: boolean; readonly uninstall: boolean; }; +/** + * Fail on the `@sentry/wizard` sign-up and partner flags, which `sentry + * wizard` dropped: it logs in with the CLI's login, which has no sign-up or + * partner step. + * + * @throws {ValidationError} When one of them is passed + */ +function rejectRemovedFlags(flags: WizardFlags): void { + const removed = [ + flags.signup ? "--signup" : undefined, + flags["promo-code"] === undefined ? undefined : "--promo-code", + flags["coming-from"] === undefined ? undefined : "--coming-from", + ].filter((flag) => flag !== undefined); + if (removed.length === 0) { + return; + } + throw new ValidationError( + `${removed.join(", ")} ${removed.length === 1 ? "is" : "are"} no longer supported. ` + + "Sign up at https://sentry.io/signup/ (and apply any promo code there), " + + "then run the wizard again without " + + `${removed.length === 1 ? "it" : "them"}.`, + removed[0], + ); +} + /** The trimmed value of the environment variable `name`, unless empty. */ function envValue(name: string): string | undefined { return getEnv()[name]?.trim() || undefined; @@ -63,8 +88,10 @@ export const wizardCommand = buildCommand({ "uploads. It logs in with your `sentry auth login` account (or starts " + "a login), and lets you pick or create the Sentry project to send " + "data to.\n\n" + - "Pass `-i` to skip the integration picker. These are the same " + - "integrations and flags `npx @sentry/wizard` takes.\n\n" + + "Pass `-i` to skip the integration picker. It takes the same " + + "integrations and flags as `npx @sentry/wizard`, except the sign-up " + + "flags `--signup`, `--promo-code` and `--coming-from`, which fail: " + + "sign up at https://sentry.io/signup/ first.\n\n" + "The wizard changes files in your project. To have a coding agent set " + "up Sentry instead, run `sentry init`, which prints the agent's setup " + "guide and changes nothing.", @@ -143,29 +170,33 @@ export const wizardCommand = buildCommand({ brief: "Print the wizard's debug output", default: false, }, + // `@sentry/wizard`'s sign-up and partner flags. The wizard logs in + // with the CLI's login, which has no sign-up or partner step, so these + // fail with an explanation instead of being dropped silently. + signup: { + kind: "boolean", + brief: "Removed: sign up at https://sentry.io/signup/ first", + default: false, + hidden: true as const, + }, "promo-code": { kind: "parsed", parse: parseText, - brief: "Promo code to apply when signing up", + brief: "Removed: apply promo codes when you sign up", placeholder: "code", optional: true, + hidden: true as const, }, "coming-from": { kind: "parsed", parse: parseText, - brief: "Partner the command was copied from, such as vercel", + brief: "Removed: partner sign-up is not supported", placeholder: "partner", optional: true, hidden: true as const, }, // Flags `@sentry/wizard` accepted that no flow reads any more. Kept so // copied commands still run. - signup: { - kind: "boolean", - brief: "Ignored: the login page offers sign-up", - default: false, - hidden: true as const, - }, "skip-connect": { kind: "boolean", brief: "Ignored", @@ -189,6 +220,7 @@ export const wizardCommand = buildCommand({ }, // oxlint-disable-next-line require-yield -- The wizard prints its own interactive output; the command yields none. async *func(this: SentryContext, flags: WizardFlags) { + rejectRemovedFlags(flags); if (flags["disable-telemetry"]) { disableTelemetryForRun(); } @@ -199,13 +231,11 @@ export const wizardCommand = buildCommand({ debug: flags.debug || envValue("SENTRY_WIZARD_DEBUG") === "true", wizardOptions: { telemetryEnabled: !flags["disable-telemetry"] && isTelemetryEnabled(), - promoCode: flags["promo-code"], url: flags.url ?? envValue("SENTRY_WIZARD_URL"), orgSlug: flags.org, projectSlug: flags.project, saas: flags.saas, forceInstall: flags["force-install"], - comingFrom: flags["coming-from"], ignoreGitChanges: flags["ignore-git-changes"], spotlight: flags.spotlight, }, diff --git a/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts b/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts index ef8e11b357..fd14f9bb03 100644 --- a/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts +++ b/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts @@ -104,11 +104,10 @@ export function runNextjsWizard(options: WizardOptions) { export async function runNextjsWizardWithTelemetry( options: WizardOptions, ): Promise { - const { promoCode, telemetryEnabled, forceInstall } = options; + const { telemetryEnabled, forceInstall } = options; printWelcome({ wizardName: "Sentry Next.js Wizard", - promoCode, telemetryEnabled, }); @@ -483,13 +482,13 @@ The wizard will import ${chalk.cyan( path.join(process.cwd(), "vercel.json"), ); - if (mightBeUsingVercel && !options.comingFrom) { + if (mightBeUsingVercel) { clack.log.info( "▲ It seems like you're using Vercel. We recommend using the Sentry Vercel \ integration to set up an auth token for Vercel deployments: https://vercel.com/integrations/sentry", ); } else if (!spotlight) { - await setupCI("nextjs", authToken, options.comingFrom); + await setupCI("nextjs", authToken); } const packageManagerForOutro = diff --git a/packages/cli/src/lib/wizard/sourcemaps/ci.ts b/packages/cli/src/lib/wizard/sourcemaps/ci.ts index e725f44a51..ed73aa32c4 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/ci.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/ci.ts @@ -13,7 +13,6 @@ import { SENTRY_DOT_ENV_FILE, } from "../utils/clack/index.js"; import { clack } from "../utils/clack/prompts.js"; -import type { WizardOptions } from "../utils/types.js"; /** Tools that upload with `sentry` commands and read `.sentryclirc`. */ const CLI_BASED_FLOW_TOOLS: readonly string[] = [ @@ -25,25 +24,16 @@ const CLI_BASED_FLOW_TOOLS: readonly string[] = [ /** * Ask whether the user builds in CI and, if so, show the auth token to set - * there. Skipped for partner flows (Vercel) that already set the token. + * there. * * @param selectedTool - The build tool the wizard configured, such as `nextjs` * @param authToken - The token written to the local config file - * @param comingFrom - The partner the command came from (`--coming-from`) */ export async function setupCI( selectedTool: string, authToken: string, - comingFrom: WizardOptions["comingFrom"], ): Promise { - if (comingFrom === "vercel") { - clack.log.info( - "Sentry Vercel integration is already configured. Skipping CI setup.", - ); - Sentry.setTag("using-ci", true); - } else { - await traceStep("configure-ci", () => configureCI(selectedTool, authToken)); - } + await traceStep("configure-ci", () => configureCI(selectedTool, authToken)); } /** Ask about CI and show the auth token to set there. */ diff --git a/packages/cli/src/lib/wizard/utils/clack/index.ts b/packages/cli/src/lib/wizard/utils/clack/index.ts index fd740e4b6e..0bdb01dc8c 100644 --- a/packages/cli/src/lib/wizard/utils/clack/index.ts +++ b/packages/cli/src/lib/wizard/utils/clack/index.ts @@ -151,7 +151,6 @@ export async function abortIfCancelled( /** Print the intro banner and welcome note of a wizard. */ export function printWelcome(options: { wizardName: string; - promoCode?: string | undefined; message?: string | undefined; telemetryEnabled?: boolean | undefined; }): void { @@ -162,10 +161,6 @@ export function printWelcome(options: { options.message || `The ${options.wizardName} will help you set up Sentry for your application.\nThank you for using Sentry :)`; - if (options.promoCode) { - welcomeText = `${welcomeText}\n\nUsing promo-code: ${options.promoCode}`; - } - welcomeText = `${welcomeText}\n\nVersion: ${CLI_VERSION}`; if (options.telemetryEnabled) { diff --git a/packages/cli/src/lib/wizard/utils/types.ts b/packages/cli/src/lib/wizard/utils/types.ts index b7b267c44e..d349678578 100644 --- a/packages/cli/src/lib/wizard/utils/types.ts +++ b/packages/cli/src/lib/wizard/utils/types.ts @@ -26,12 +26,6 @@ export type WizardOptions = { */ telemetryEnabled: boolean; - /** - * The promo code to use while signing up for Sentry. - * This can be passed via the --promo-code arg. - */ - promoCode?: string | undefined; - /** * The url of the Sentry instance to use. * This can be passed via the `-u` or `--url` arg. @@ -73,13 +67,6 @@ export type WizardOptions = { */ forceInstall?: boolean | undefined; - /** - * Used when the wizard command is copied from partner sites (e.g. Vercel) - * to display login/signup instructions specific to organizations provisioned - * through the partner. - */ - comingFrom?: string | undefined; - /** * If this is set, the wizard will ignore any git changes in the project and not prompt for confirmation. */ diff --git a/packages/cli/test/commands/wizard.test.ts b/packages/cli/test/commands/wizard.test.ts index f320f998b9..46be02ce14 100644 --- a/packages/cli/test/commands/wizard.test.ts +++ b/packages/cli/test/commands/wizard.test.ts @@ -72,23 +72,41 @@ describe("sentry wizard", () => { "force-install": true, "ignore-git-changes": true, "disable-telemetry": true, - "coming-from": "vercel", }); expect(runNextjsWizard).toHaveBeenCalledWith({ telemetryEnabled: false, - promoCode: undefined, url: "https://sentry.example.com", orgSlug: "acme", projectSlug: "web", saas: false, forceInstall: true, - comingFrom: "vercel", ignoreGitChanges: true, spotlight: true, }); }); + test.each([ + [{ signup: true }, "--signup is no longer supported."], + [{ "promo-code": "PROMO" }, "--promo-code is no longer supported."], + [{ "coming-from": "vercel" }, "--coming-from is no longer supported."], + [ + { signup: true, "promo-code": "PROMO" }, + "--signup, --promo-code are no longer supported.", + ], + ])("rejects the removed sign-up flags %o", async (flags, message) => { + const error = await runWizardCommand({ integration: "nextjs", ...flags }) + .then(() => undefined) + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(ValidationError); + expect((error as ValidationError).message).toContain(message); + expect((error as ValidationError).message).toContain( + "https://sentry.io/signup/", + ); + expect(runNextjsWizard).not.toHaveBeenCalled(); + }); + test("reads the integration and URL from SENTRY_WIZARD_* variables", async () => { vi.stubEnv("SENTRY_WIZARD_INTEGRATION", "nextjs"); vi.stubEnv("SENTRY_WIZARD_URL", "https://self-hosted.example.com"); From f230698a7c2726a5e7f0b4e923815b2805ceafb9 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:29:59 +0000 Subject: [PATCH 04/20] feat(cli): add source maps and Cloudflare to sentry wizard Port the source maps wizard (all build tools) and the Cloudflare Workers wizard from sentry-wizard 9.1.0 into `sentry wizard`, with their tests, and register `sourcemaps` and `cloudflare` in WIZARD_RUNNERS. The generated projects now use the v4 `sentry` CLI instead of sentry-cli v2: the wizard installs the `sentry` npm package and writes `sentry sourcemap inject/upload` and `sentry release create` scripts. `.sentryclirc` stays, since v4 still reads it. A self-hosted URL is passed in `SENTRY_URL`, which replaced the sentry-cli `--url` flag. `sourcemaps/ci.ts` gains the step that asks to run the `sentry:sourcemaps` script in CI. The Cloudflare test fixtures keep their upstream bytes, so the formatter, linter and test typecheck skip wizard fixtures. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .oxfmtrc.json | 1 + .oxlintrc.json | 1 + .../wizard/cloudflare/cloudflare-wizard.ts | 189 +++++++ .../src/lib/wizard/cloudflare/sdk-setup.ts | 95 ++++ .../src/lib/wizard/cloudflare/templates.ts | 57 ++ .../wrangler/create-wrangler-config.ts | 36 ++ .../wrangler/ensure-wrangler-config.ts | 26 + .../wrangler/find-wrangler-config.ts | 22 + .../get-entry-point-from-wrangler-config.ts | 65 +++ .../wrangler/update-wrangler-config.ts | 251 +++++++++ .../src/lib/wizard/cloudflare/wrap-worker.ts | 172 ++++++ packages/cli/src/lib/wizard/run.ts | 10 + packages/cli/src/lib/wizard/sourcemaps/ci.ts | 14 +- .../wizard/sourcemaps/sourcemaps-wizard.ts | 293 ++++++++++ .../lib/wizard/sourcemaps/tools/angular.ts | 48 ++ .../sourcemaps/tools/create-react-app.ts | 24 + .../lib/wizard/sourcemaps/tools/esbuild.ts | 63 +++ .../src/lib/wizard/sourcemaps/tools/rollup.ts | 63 +++ .../lib/wizard/sourcemaps/tools/sentry-cli.ts | 348 ++++++++++++ .../src/lib/wizard/sourcemaps/tools/tsc.ts | 145 +++++ .../src/lib/wizard/sourcemaps/tools/types.ts | 15 + .../src/lib/wizard/sourcemaps/tools/vite.ts | 306 +++++++++++ .../lib/wizard/sourcemaps/tools/webpack.ts | 382 ++++++++++++++ .../lib/wizard/sourcemaps/tools/wrangler.ts | 499 ++++++++++++++++++ .../wizard/sourcemaps/utils/bundler-plugin.ts | 118 +++++ .../wizard/sourcemaps/utils/detect-tool.ts | 58 ++ .../wizard/sourcemaps/utils/other-wizards.ts | 169 ++++++ .../wizard/sourcemaps/utils/sdk-version.ts | 282 ++++++++++ .../abort-if-sportlight-not-supported.ts | 19 + .../utils/vendor/is-unicorn-supported.ts | 38 ++ .../update-wrangler-config.test.ts.snap | 40 ++ .../__snapshots__/wrap-worker.test.ts.snap | 164 ++++++ .../cloudflare/create-wrangler-config.test.ts | 50 ++ .../cloudflare/ensure-wrangler-config.test.ts | 71 +++ .../cloudflare/find-wrangler-config.test.ts | 74 +++ .../fixtures/worker/already-wrapped.ts | 12 + .../fixtures/worker/complex-handler.ts | 13 + .../worker/external-default-export.ts | 3 + .../fixtures/worker/no-default-export.ts | 2 + .../fixtures/worker/simple-with-satisfies.ts | 5 + .../cloudflare/fixtures/worker/simple.ts | 5 + .../fixtures/worker/with-comment.ts | 6 + .../cloudflare/fixtures/worker/with-import.ts | 7 + .../fixtures/worker/with-sentry-import.ts | 8 + .../wrangler/wrangler-all-comment-types.jsonc | 8 + .../fixtures/wrangler/wrangler-basic.json | 1 + .../wrangler-complex-with-comments.jsonc | 20 + .../fixtures/wrangler/wrangler-empty.json | 2 + .../fixtures/wrangler/wrangler-minimal.json | 1 + .../wrangler/wrangler-multi-line-array.json | 12 + .../wrangler/wrangler-trailing-comma.jsonc | 4 + .../wrangler/wrangler-with-comment.jsonc | 5 + .../wrangler-with-duplicate-flags.json | 1 + .../wrangler/wrangler-with-flags.json | 1 + .../wrangler/wrangler-with-metadata.jsonc | 8 + ...t-entry-point-from-wrangler-config.test.ts | 92 ++++ .../lib/wizard/cloudflare/sdk-setup.test.ts | 223 ++++++++ .../lib/wizard/cloudflare/templates.test.ts | 136 +++++ .../cloudflare/update-wrangler-config.test.ts | 279 ++++++++++ .../lib/wizard/cloudflare/wrap-worker.test.ts | 310 +++++++++++ .../sourcemaps/tools/sentry-cli.test.ts | 106 ++++ .../lib/wizard/sourcemaps/tools/tsc.test.ts | 183 +++++++ .../lib/wizard/sourcemaps/tools/vite.test.ts | 159 ++++++ .../wizard/sourcemaps/tools/webpack.test.ts | 313 +++++++++++ .../wizard/sourcemaps/tools/wrangler.test.ts | 320 +++++++++++ .../sourcemaps/utils/bundler-plugin.test.ts | 166 ++++++ .../sourcemaps/utils/sdk-version.test.ts | 64 +++ packages/cli/test/tsconfig.json | 3 +- 68 files changed, 6683 insertions(+), 3 deletions(-) create mode 100644 packages/cli/src/lib/wizard/cloudflare/cloudflare-wizard.ts create mode 100644 packages/cli/src/lib/wizard/cloudflare/sdk-setup.ts create mode 100644 packages/cli/src/lib/wizard/cloudflare/templates.ts create mode 100644 packages/cli/src/lib/wizard/cloudflare/wrangler/create-wrangler-config.ts create mode 100644 packages/cli/src/lib/wizard/cloudflare/wrangler/ensure-wrangler-config.ts create mode 100644 packages/cli/src/lib/wizard/cloudflare/wrangler/find-wrangler-config.ts create mode 100644 packages/cli/src/lib/wizard/cloudflare/wrangler/get-entry-point-from-wrangler-config.ts create mode 100644 packages/cli/src/lib/wizard/cloudflare/wrangler/update-wrangler-config.ts create mode 100644 packages/cli/src/lib/wizard/cloudflare/wrap-worker.ts create mode 100644 packages/cli/src/lib/wizard/sourcemaps/sourcemaps-wizard.ts create mode 100644 packages/cli/src/lib/wizard/sourcemaps/tools/angular.ts create mode 100644 packages/cli/src/lib/wizard/sourcemaps/tools/create-react-app.ts create mode 100644 packages/cli/src/lib/wizard/sourcemaps/tools/esbuild.ts create mode 100644 packages/cli/src/lib/wizard/sourcemaps/tools/rollup.ts create mode 100644 packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts create mode 100644 packages/cli/src/lib/wizard/sourcemaps/tools/tsc.ts create mode 100644 packages/cli/src/lib/wizard/sourcemaps/tools/types.ts create mode 100644 packages/cli/src/lib/wizard/sourcemaps/tools/vite.ts create mode 100644 packages/cli/src/lib/wizard/sourcemaps/tools/webpack.ts create mode 100644 packages/cli/src/lib/wizard/sourcemaps/tools/wrangler.ts create mode 100644 packages/cli/src/lib/wizard/sourcemaps/utils/bundler-plugin.ts create mode 100644 packages/cli/src/lib/wizard/sourcemaps/utils/detect-tool.ts create mode 100644 packages/cli/src/lib/wizard/sourcemaps/utils/other-wizards.ts create mode 100644 packages/cli/src/lib/wizard/sourcemaps/utils/sdk-version.ts create mode 100644 packages/cli/src/lib/wizard/utils/abort-if-sportlight-not-supported.ts create mode 100644 packages/cli/src/lib/wizard/utils/vendor/is-unicorn-supported.ts create mode 100644 packages/cli/test/lib/wizard/cloudflare/__snapshots__/update-wrangler-config.test.ts.snap create mode 100644 packages/cli/test/lib/wizard/cloudflare/__snapshots__/wrap-worker.test.ts.snap create mode 100644 packages/cli/test/lib/wizard/cloudflare/create-wrangler-config.test.ts create mode 100644 packages/cli/test/lib/wizard/cloudflare/ensure-wrangler-config.test.ts create mode 100644 packages/cli/test/lib/wizard/cloudflare/find-wrangler-config.test.ts create mode 100644 packages/cli/test/lib/wizard/cloudflare/fixtures/worker/already-wrapped.ts create mode 100644 packages/cli/test/lib/wizard/cloudflare/fixtures/worker/complex-handler.ts create mode 100644 packages/cli/test/lib/wizard/cloudflare/fixtures/worker/external-default-export.ts create mode 100644 packages/cli/test/lib/wizard/cloudflare/fixtures/worker/no-default-export.ts create mode 100644 packages/cli/test/lib/wizard/cloudflare/fixtures/worker/simple-with-satisfies.ts create mode 100644 packages/cli/test/lib/wizard/cloudflare/fixtures/worker/simple.ts create mode 100644 packages/cli/test/lib/wizard/cloudflare/fixtures/worker/with-comment.ts create mode 100644 packages/cli/test/lib/wizard/cloudflare/fixtures/worker/with-import.ts create mode 100644 packages/cli/test/lib/wizard/cloudflare/fixtures/worker/with-sentry-import.ts create mode 100644 packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-all-comment-types.jsonc create mode 100644 packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-basic.json create mode 100644 packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-complex-with-comments.jsonc create mode 100644 packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-empty.json create mode 100644 packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-minimal.json create mode 100644 packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-multi-line-array.json create mode 100644 packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-trailing-comma.jsonc create mode 100644 packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-with-comment.jsonc create mode 100644 packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-with-duplicate-flags.json create mode 100644 packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-with-flags.json create mode 100644 packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-with-metadata.jsonc create mode 100644 packages/cli/test/lib/wizard/cloudflare/get-entry-point-from-wrangler-config.test.ts create mode 100644 packages/cli/test/lib/wizard/cloudflare/sdk-setup.test.ts create mode 100644 packages/cli/test/lib/wizard/cloudflare/templates.test.ts create mode 100644 packages/cli/test/lib/wizard/cloudflare/update-wrangler-config.test.ts create mode 100644 packages/cli/test/lib/wizard/cloudflare/wrap-worker.test.ts create mode 100644 packages/cli/test/lib/wizard/sourcemaps/tools/sentry-cli.test.ts create mode 100644 packages/cli/test/lib/wizard/sourcemaps/tools/tsc.test.ts create mode 100644 packages/cli/test/lib/wizard/sourcemaps/tools/vite.test.ts create mode 100644 packages/cli/test/lib/wizard/sourcemaps/tools/webpack.test.ts create mode 100644 packages/cli/test/lib/wizard/sourcemaps/tools/wrangler.test.ts create mode 100644 packages/cli/test/lib/wizard/sourcemaps/utils/bundler-plugin.test.ts create mode 100644 packages/cli/test/lib/wizard/sourcemaps/utils/sdk-version.test.ts diff --git a/.oxfmtrc.json b/.oxfmtrc.json index b27ad9c221..7031c419bc 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -12,6 +12,7 @@ "packages/cli/CHANGELOG.md", "packages/cli/AGENTS.md", "packages/mcp-server-mocks/src/fixtures/**", + "packages/cli/test/lib/wizard/**/fixtures/**", "packages/mcp-core/src/ui/chart-app.generated.ts", "packages/codemod-cli3to4/tests/**", "**/worker-configuration.d.ts", diff --git a/.oxlintrc.json b/.oxlintrc.json index ff2085d067..ee78dd10bf 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -13,6 +13,7 @@ "**/worker-configuration.d.ts", "**/tsconfig*.json", "packages/mcp-server-mocks/src/fixtures/**", + "packages/cli/test/lib/wizard/**/fixtures/**", "packages/mcp-core/src/ui/chart-app.generated.ts", "packages/codemod-cli3to4/tests/**" ], diff --git a/packages/cli/src/lib/wizard/cloudflare/cloudflare-wizard.ts b/packages/cli/src/lib/wizard/cloudflare/cloudflare-wizard.ts new file mode 100644 index 0000000000..67fa8d30b6 --- /dev/null +++ b/packages/cli/src/lib/wizard/cloudflare/cloudflare-wizard.ts @@ -0,0 +1,189 @@ +/** + * The Cloudflare Workers setup wizard: installs `@sentry/cloudflare`, wraps + * the worker with `Sentry.withSentry()`, and adds the compatibility flags + * and version metadata binding the SDK needs to the Wrangler config. + */ + +import chalk from "chalk"; + +import { traceStep, withTelemetry } from "../telemetry.js"; +import { abortIfSpotlightNotSupported } from "../utils/abort-if-sportlight-not-supported.js"; +import { + 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 { debug } from "../utils/debug.js"; +import { warnIfNodeVersionUnsupportedBySdkV11 } from "../utils/node-version.js"; +import { + getPackageVersion, + hasPackageInstalled, +} from "../utils/package-json.js"; +import type { WizardOptions } from "../utils/types.js"; +import { createSentryInitFile } from "./sdk-setup.js"; +import { ensureWranglerConfig } from "./wrangler/ensure-wrangler-config.js"; +import { + defaultEntryPoint, + getEntryPointFromWranglerConfig, +} from "./wrangler/get-entry-point-from-wrangler-config.js"; +import { updateWranglerConfig } from "./wrangler/update-wrangler-config.js"; + +/** Run the Cloudflare wizard (`sentry wizard -i cloudflare`). */ +export async function runCloudflareWizard( + options: WizardOptions, +): Promise { + return await withTelemetry( + { + enabled: options.telemetryEnabled, + integration: "cloudflare", + wizardOptions: options, + }, + () => runCloudflareWizardWithTelemetry(options), + ); +} + +async function runCloudflareWizardWithTelemetry( + options: WizardOptions, +): Promise { + const { promoCode, telemetryEnabled, forceInstall } = options; + + printWelcome({ + wizardName: "Sentry Cloudflare Wizard", + promoCode, + telemetryEnabled, + }); + + warnIfNodeVersionUnsupportedBySdkV11(); + + await confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: options.ignoreGitChanges, + cwd: undefined, + }); + + const packageJson = await getPackageDotJson(); + + await ensurePackageIsInstalled(packageJson, "wrangler", "Cloudflare"); + + traceStep("Ensure Wrangler config", () => { + ensureWranglerConfig(); + }); + + const projectData = await getOrAskForProjectData( + options, + "node-cloudflare-workers", + ); + + if (projectData.spotlight) { + return await abortIfSpotlightNotSupported("Cloudflare"); + } + + const { selectedProject } = projectData; + + printSdkV11MigrationGuideIfOutdated("@sentry/cloudflare", packageJson); + + await installPackage({ + packageName: "@sentry/cloudflare@^11", + packageNameDisplayLabel: "@sentry/cloudflare", + alreadyInstalled: hasPackageInstalled("@sentry/cloudflare", packageJson), + 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/cloudflare", + await getPackageDotJson(), + ); + + const selectedFeatures = await featureSelectionPrompt([ + { + id: "performance", + prompt: `Do you want to enable ${chalk.bold( + "Tracing", + )} to track the performance of your application?`, + enabledHint: "recommended", + }, + ] as const); + + // 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, "^10") && + (await askShouldReduceDataCollection()); + + await traceStep("Create Sentry initialization", async () => { + try { + await createSentryInitFile( + selectedProject.keys[0].dsn.public, + selectedFeatures, + reduceDataCollection, + ); + } catch (e) { + clack.log.warn( + "Could not automatically set up Sentry initialization. Please set it up manually using instructions from https://docs.sentry.io/platforms/javascript/guides/cloudflare/", + ); + debug(e); + } + }); + + const mainFile = getEntryPointFromWranglerConfig(); + + await traceStep("Update Wrangler config with Sentry requirements", () => + updateWranglerConfig( + { + ...(mainFile ? {} : { main: defaultEntryPoint }), + // The SDK needs Node.js compatibility. `nodejs_compat` is a superset of + // the `nodejs_als` flag older setups used, and the only one SDK v11 accepts. + compatibility_flags: ["nodejs_compat"], + compatibility_date: new Date().toISOString().slice(0, 10), + version_metadata: { + binding: "CF_VERSION_METADATA", + }, + }, + { removeCompatibilityFlags: ["nodejs_als"] }, + ), + ); + + 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()); +} + +/** The closing message, with the next steps. */ +function buildOutroMessage(): string { + return ` + ${chalk.green( + "Sentry has been successfully configured for your Cloudflare project.", + )} + + ${chalk.dim("Next steps:")} + ${chalk.dim("1. Wrap your worker with Sentry as instructed above")} + ${chalk.dim("2. Deploy your application with:")} ${chalk.cyan( + "wrangler deploy", + )} + ${chalk.dim("3. Trigger an error to test Sentry integration")} + + ${chalk.cyan( + `To learn more about using Sentry with Cloudflare, visit: + https://docs.sentry.io/platforms/javascript/guides/cloudflare/`, + )} + `; +} diff --git a/packages/cli/src/lib/wizard/cloudflare/sdk-setup.ts b/packages/cli/src/lib/wizard/cloudflare/sdk-setup.ts new file mode 100644 index 0000000000..f1dc97c1cf --- /dev/null +++ b/packages/cli/src/lib/wizard/cloudflare/sdk-setup.ts @@ -0,0 +1,95 @@ +/** + * Write the Sentry initialization into the worker entry point: wrap an + * existing handler, or create an entry point when the Wrangler config names + * none. + */ + +import chalk from "chalk"; +import { existsSync, promises } from "node:fs"; +import path from "node:path"; + +import { clack } from "../utils/clack/prompts.js"; +import { debug } from "../utils/debug.js"; +import { + getCloudflareWorkerTemplate, + getCloudflareWorkerTemplateWithHandler, +} from "./templates.js"; +import { + defaultEntryPoint, + getEntryPointFromWranglerConfig, +} from "./wrangler/get-entry-point-from-wrangler-config.js"; +import { wrapWorkerWithSentry } from "./wrap-worker.js"; + +/** + * Creates or updates the main worker file with Sentry initialization. + * Currently focused on Cloudflare Workers + */ +export async function createSentryInitFile( + dsn: string, + selectedFeatures: { + performance: boolean; + }, + reduceDataCollection: boolean, +): Promise { + const entryPointFromConfig = getEntryPointFromWranglerConfig(); + + if (!entryPointFromConfig) { + clack.log.info( + "No entry point found in wrangler config, creating a new one.", + ); + + const cloudflareWorkerTemplate = getCloudflareWorkerTemplateWithHandler(); + + await promises.mkdir( + path.join(process.cwd(), path.dirname(defaultEntryPoint)), + { + recursive: true, + }, + ); + await promises.writeFile( + path.join(process.cwd(), defaultEntryPoint), + cloudflareWorkerTemplate, + { encoding: "utf-8", flag: "w" }, + ); + + clack.log.success(`Created ${chalk.cyan(defaultEntryPoint)}.`); + + return; + } + + const entryPointPath = path.join(process.cwd(), entryPointFromConfig); + + if (existsSync(entryPointPath)) { + clack.log.info( + `Found existing entry point: ${chalk.cyan(entryPointFromConfig)}`, + ); + + try { + await wrapWorkerWithSentry( + entryPointPath, + dsn, + selectedFeatures, + reduceDataCollection, + ); + clack.log.success( + `Wrapped ${chalk.cyan( + entryPointFromConfig, + )} with Sentry initialization.`, + ); + } catch (error) { + debug(error); + clack.log.warn("Failed to wrap worker automatically."); + clack.log.step("Please wrap your handler with Sentry initialization:"); + + clack.note( + chalk.cyan( + getCloudflareWorkerTemplate( + dsn, + selectedFeatures, + reduceDataCollection, + ), + ), + ); + } + } +} diff --git a/packages/cli/src/lib/wizard/cloudflare/templates.ts b/packages/cli/src/lib/wizard/cloudflare/templates.ts new file mode 100644 index 0000000000..9c36557470 --- /dev/null +++ b/packages/cli/src/lib/wizard/cloudflare/templates.ts @@ -0,0 +1,57 @@ +/** + * Worker source the Cloudflare wizard writes or shows: a worker wrapped with + * `Sentry.withSentry()`, and a starter worker. + */ + +import { getDataCollectionSnippet } from "../utils/data-collection.js"; + +export function getCloudflareWorkerTemplate( + dsn: string, + selectedFeatures: { + performance: boolean; + }, + reduceDataCollection: boolean, +): string { + let performanceOptions = ""; + if (selectedFeatures.performance) { + performanceOptions = ` + // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control. + tracesSampleRate: 1,`; + } + + const dataCollectionOptions = reduceDataCollection + ? `\n${getDataCollectionSnippet("\t\t")}` + : ""; + + return `import * as Sentry from '@sentry/cloudflare'; + +export default Sentry.withSentry( + (env) => ({ + dsn: '${dsn}',${performanceOptions}${dataCollectionOptions} + }), + { + async fetch(request, env, ctx): Promise { + // Your worker logic here + return new Response('Hello World!'); + }, + } satisfies ExportedHandler, +); +`; +} + +export function getCloudflareWorkerTemplateWithHandler(): string { + return `export default { + async fetch(request, env, ctx): Promise { + const url = new URL(request.url); + switch (url.pathname) { + case '/message': + return new Response('Hello, World!'); + case '/random': + return new Response(crypto.randomUUID()); + default: + return new Response('Not Found', { status: 404 }); + } + }, +} satisfies ExportedHandler; +`; +} diff --git a/packages/cli/src/lib/wizard/cloudflare/wrangler/create-wrangler-config.ts b/packages/cli/src/lib/wizard/cloudflare/wrangler/create-wrangler-config.ts new file mode 100644 index 0000000000..e6b8e8ef53 --- /dev/null +++ b/packages/cli/src/lib/wizard/cloudflare/wrangler/create-wrangler-config.ts @@ -0,0 +1,36 @@ +/** + * Create a minimal `wrangler.jsonc` for a project that has no Wrangler + * config yet. + */ + +import chalk from "chalk"; +import { writeFileSync } from "node:fs"; +import path from "node:path"; + +import { clack } from "../../utils/clack/prompts.js"; + +/** + * Creates a basic wrangler.jsonc config file for a Cloudflare Worker + */ +export function createWranglerConfig(): void { + const configPath = path.join(process.cwd(), "wrangler.jsonc"); + + const config = { + $schema: "node_modules/wrangler/config-schema.json", + name: "my-worker", + main: "src/index.ts", + }; + + writeFileSync(configPath, JSON.stringify(config, null, 2), "utf-8"); + + clack.log.success( + `Created ${chalk.cyan("wrangler.jsonc")} configuration file.`, + ); + clack.log.info( + `Please update the ${chalk.cyan("name")} and ${chalk.cyan( + "main", + )} fields in ${chalk.cyan( + "wrangler.jsonc", + )} to match your worker name and entry point.`, + ); +} diff --git a/packages/cli/src/lib/wizard/cloudflare/wrangler/ensure-wrangler-config.ts b/packages/cli/src/lib/wizard/cloudflare/wrangler/ensure-wrangler-config.ts new file mode 100644 index 0000000000..61f4cd6b35 --- /dev/null +++ b/packages/cli/src/lib/wizard/cloudflare/wrangler/ensure-wrangler-config.ts @@ -0,0 +1,26 @@ +/** + * Make sure a Cloudflare Worker project has a Wrangler config. + */ + +import chalk from "chalk"; + +import { clack } from "../../utils/clack/prompts.js"; +import { createWranglerConfig } from "./create-wrangler-config.js"; +import { findWranglerConfig } from "./find-wrangler-config.js"; + +/** + * Ensures a wrangler config exists, creating one if necessary + */ +export function ensureWranglerConfig(): void { + const existingConfig = findWranglerConfig(); + + if (existingConfig) { + clack.log.info( + `Found existing Wrangler config: ${chalk.cyan(existingConfig)}`, + ); + return; + } + + clack.log.step("No Wrangler configuration file found."); + createWranglerConfig(); +} diff --git a/packages/cli/src/lib/wizard/cloudflare/wrangler/find-wrangler-config.ts b/packages/cli/src/lib/wizard/cloudflare/wrangler/find-wrangler-config.ts new file mode 100644 index 0000000000..0272238c03 --- /dev/null +++ b/packages/cli/src/lib/wizard/cloudflare/wrangler/find-wrangler-config.ts @@ -0,0 +1,22 @@ +/** + * Find the Wrangler config file of a Cloudflare Worker project. + */ + +import { existsSync } from "node:fs"; +import path from "node:path"; + +/** + * Checks if a wrangler config file exists in the project + */ +export function findWranglerConfig(): string | undefined { + const possibleConfigs = ["wrangler.jsonc", "wrangler.json", "wrangler.toml"]; + + for (const configFile of possibleConfigs) { + const configPath = path.join(process.cwd(), configFile); + if (existsSync(configPath)) { + return configFile; + } + } + + return undefined; +} diff --git a/packages/cli/src/lib/wizard/cloudflare/wrangler/get-entry-point-from-wrangler-config.ts b/packages/cli/src/lib/wizard/cloudflare/wrangler/get-entry-point-from-wrangler-config.ts new file mode 100644 index 0000000000..07f01347ed --- /dev/null +++ b/packages/cli/src/lib/wizard/cloudflare/wrangler/get-entry-point-from-wrangler-config.ts @@ -0,0 +1,65 @@ +/** + * Read the worker entry point (`main`) from the Wrangler config. + */ + +import { readFileSync } from "node:fs"; +import path from "node:path"; + +import { getObjectProperty, parseJsonC } from "../../utils/ast-utils.js"; +import { debug } from "../../utils/debug.js"; +import { findWranglerConfig } from "./find-wrangler-config.js"; + +export const defaultEntryPoint = "src/index.ts"; + +/** + * Reads the main entry point from the wrangler config file + * Returns undefined if no config exists or if main field is not specified + */ +export function getEntryPointFromWranglerConfig(): string | undefined { + const configFile = findWranglerConfig(); + + if (!configFile) { + return undefined; + } + + const configPath = path.join(process.cwd(), configFile); + const configContent = readFileSync(configPath, "utf-8"); + const extname = path.extname(configFile); + + switch (extname) { + case ".toml": { + const mainMatch = configContent.match(/^main\s*=\s*["'](.+)["']/m); + + return mainMatch?.[1]; + } + + case ".json": + case ".jsonc": + try { + const { jsonObject } = parseJsonC(configContent); + + if (!jsonObject) { + return undefined; + } + + const mainProperty = getObjectProperty(jsonObject, "main"); + + if ( + (mainProperty?.value.type === "StringLiteral" || + mainProperty?.value.type === "Literal") && + typeof mainProperty.value.value === "string" + ) { + return mainProperty.value.value; + } + + return undefined; + } catch (error) { + // An unparseable config has no entry point we can use + debug(error); + return undefined; + } + + default: + return undefined; + } +} diff --git a/packages/cli/src/lib/wizard/cloudflare/wrangler/update-wrangler-config.ts b/packages/cli/src/lib/wizard/cloudflare/wrangler/update-wrangler-config.ts new file mode 100644 index 0000000000..1b2a51f74b --- /dev/null +++ b/packages/cli/src/lib/wizard/cloudflare/wrangler/update-wrangler-config.ts @@ -0,0 +1,251 @@ +/** + * Add the settings the Sentry SDK needs to the Wrangler config: edit a JSON + * or JSONC config in place, or show the change for a TOML one. + */ + +import type { namedTypes as t } from "ast-types"; +import chalk from "chalk"; +import { readFileSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import recast from "recast"; + +import { + getObjectProperty, + parseJsonC, + printJsonC, + setOrUpdateObjectProperty, +} from "../../utils/ast-utils.js"; +import { + makeCodeSnippet, + showCopyPasteInstructions, +} from "../../utils/clack/index.js"; +import { clack } from "../../utils/clack/prompts.js"; +import { findWranglerConfig } from "./find-wrangler-config.js"; + +const b = recast.types.builders; + +type WranglerConfigUpdates = { + compatibility_date?: string; + compatibility_flags?: string[]; + version_metadata?: { + binding: string; + }; + [key: string]: unknown; +}; + +type WranglerConfigUpdateOptions = { + /** + * Compatibility flags to drop from an existing `compatibility_flags` array, + * e.g. flags superseded by one of the flags being added. + */ + removeCompatibilityFlags?: string[] | undefined; +}; + +const getTomlConfigSnippet = (options: WranglerConfigUpdateOptions) => { + const superseded = options.removeCompatibilityFlags ?? []; + + return makeCodeSnippet(true, (_unchanged, plus) => + plus( + `${ + superseded.length + ? `# Remove ${superseded + .map((flag) => `"${flag}"`) + .join(", ")} from compatibility_flags if present\n` + : "" + }compatibility_flags = ["nodejs_compat"] +compatibility_date = "${new Date().toISOString().slice(0, 10)}" + +[version_metadata] +binding = "CF_VERSION_METADATA"`, + ), + ); +}; + +/** + * Updates the wrangler config file with the provided configuration + * Handles .toml (instructions only), .json, and .jsonc formats + * For arrays: merges and deduplicates values + * For objects: deep merges + * For other types: overwrites + */ +export async function updateWranglerConfig( + updates: WranglerConfigUpdates, + options: WranglerConfigUpdateOptions = {}, +): Promise { + const configFile = findWranglerConfig(); + + if (!configFile) { + clack.log.warn("No wrangler config file found."); + + return false; + } + + const configPath = path.join(process.cwd(), configFile); + + try { + const configContent = readFileSync(configPath, "utf-8"); + const extname = path.extname(configFile); + + switch (extname) { + case ".jsonc": + case ".json": + updateJsoncConfig(configPath, configContent, updates, options); + clack.log.success( + `Updated ${chalk.cyan(configFile)} with Sentry configuration.`, + ); + + break; + case ".toml": + await showCopyPasteInstructions({ + filename: configFile, + codeSnippet: getTomlConfigSnippet(options), + }); + break; + } + + return true; + } catch (error) { + clack.log.error( + `Failed to update ${chalk.cyan(configFile)}: ${ + error instanceof Error ? error.message : String(error) + }`, + ); + return false; + } +} + +/** + * Sets a string property in a JSON/JSONC config object. + * Overwrites any existing value. + * + * @param jsonObject The object expression to update + * @param propertyName The name of the string property + * @param value The string value to set + */ +function setStringProperty( + jsonObject: t.ObjectExpression, + propertyName: string, + value: string, +): void { + setOrUpdateObjectProperty(jsonObject, propertyName, b.stringLiteral(value)); +} + +/** + * Merges an array property in a JSON/JSONC config object. + * Extracts existing array values, merges with new values, and deduplicates. + * + * @param jsonObject The object expression to update + * @param propertyName The name of the array property + * @param newValues The new array values to merge in + * @param valuesToRemove Existing values to drop before merging + */ +function mergeArrayProperty( + jsonObject: t.ObjectExpression, + propertyName: string, + newValues: string[], + valuesToRemove: string[] = [], +): void { + const existingProperty = getObjectProperty(jsonObject, propertyName); + const existingValues: string[] = []; + + // Extract existing values from the AST if they exist + if (existingProperty?.value.type === "ArrayExpression") { + existingProperty.value.elements.forEach((element) => { + if ( + element && + (element.type === "StringLiteral" || element.type === "Literal") && + typeof element.value === "string" + ) { + existingValues.push(element.value); + } + }); + } + + // Merge existing and new values, deduplicate + const allValues = [ + ...existingValues.filter((value) => !valuesToRemove.includes(value)), + ...newValues, + ]; + const uniqueValues = [...new Set(allValues)]; + + setOrUpdateObjectProperty( + jsonObject, + propertyName, + b.arrayExpression(uniqueValues.map((value) => b.stringLiteral(value))), + ); +} + +/** + * Merges properties into a nested object property in a JSON/JSONC config object. + * Gets or creates the nested ObjectExpression if it doesn't exist, + * then merges the provided properties into it, preserving existing properties. + * + * @param jsonObject The object expression to update + * @param propertyName The name of the nested object property + * @param updates The properties to merge into the nested object + */ +function setObjectProperty( + jsonObject: t.ObjectExpression, + propertyName: string, + updates: object, +): void { + const existingProperty = getObjectProperty(jsonObject, propertyName); + let nestedObject: t.ObjectExpression; + + if (existingProperty?.value.type === "ObjectExpression") { + nestedObject = existingProperty.value; + } else { + nestedObject = b.objectExpression([]); + setOrUpdateObjectProperty(jsonObject, propertyName, nestedObject); + } + + updateJsoncObject(nestedObject, updates); +} + +function updateJsoncObject( + jsonObject: t.ObjectExpression, + updates: object, + options: WranglerConfigUpdateOptions = {}, +): void { + for (const [key, value] of Object.entries(updates)) { + if (value === null || value === undefined) { + continue; + } + + if (typeof value === "string") { + setStringProperty(jsonObject, key, value); + } else if (Array.isArray(value)) { + mergeArrayProperty( + jsonObject, + key, + value as string[], + key === "compatibility_flags" ? options.removeCompatibilityFlags : [], + ); + } else if (typeof value === "object") { + setObjectProperty(jsonObject, key, value); + } + } +} + +/** + * Updates a JSON/JSONC config file using jsonc-parser + * Preserves comments and formatting while merging values + */ +function updateJsoncConfig( + configPath: string, + content: string, + updates: WranglerConfigUpdates, + options: WranglerConfigUpdateOptions, +): void { + const { jsonObject, ast } = parseJsonC(content); + + if (!jsonObject) { + throw new Error("Failed to parse JSON/JSONC config file"); + } + + updateJsoncObject(jsonObject, updates, options); + + const code = printJsonC(ast); + + writeFileSync(configPath, code, "utf-8"); +} diff --git a/packages/cli/src/lib/wizard/cloudflare/wrap-worker.ts b/packages/cli/src/lib/wizard/cloudflare/wrap-worker.ts new file mode 100644 index 0000000000..6023539c97 --- /dev/null +++ b/packages/cli/src/lib/wizard/cloudflare/wrap-worker.ts @@ -0,0 +1,172 @@ +/** + * Wrap the default export of a Cloudflare Worker with `Sentry.withSentry()`. + */ + +import type { namedTypes as t } from "ast-types"; +import type { ExpressionKind } from "ast-types/lib/gen/kinds.js"; +import chalk from "chalk"; +import { loadFile, writeFile } from "magicast"; +import recast from "recast"; + +import { hasSentryContent } from "../utils/ast-utils.js"; +import { clack } from "../utils/clack/prompts.js"; +import { + DATA_COLLECTION_COMMENT_LINES, + DATA_COLLECTION_PII_PRESET, +} from "../utils/data-collection.js"; + +const b = recast.types.builders; + +/** + * Wraps a Cloudflare Worker's default export with Sentry.withSentry() + * + * Before: + * ``` + * export default { + * async fetch(request, env, ctx) { ... } + * } satisfies ExportedHandler; + * ``` + * + * After: + * ``` + * import * as Sentry from '@sentry/cloudflare'; + * + * export default Sentry.withSentry( + * (env) => ({ + * dsn: 'your-dsn', + * tracesSampleRate: 1, + * }), + * { + * async fetch(request, env, ctx) { ... } + * } satisfies ExportedHandler + * ); + * ``` + * + * @param workerFilePath - Path to the worker file to wrap + * @param dsn - Sentry DSN for initialization + * @param selectedFeatures - Feature flags for optional Sentry features + * @param reduceDataCollection - Whether to add the PII-reducing `dataCollection` preset + */ +export async function wrapWorkerWithSentry( + workerFilePath: string, + dsn: string, + selectedFeatures: { + performance: boolean; + }, + reduceDataCollection: boolean, +): Promise { + const workerAst = await loadFile(workerFilePath); + + if (hasSentryContent(workerAst.$ast as t.Program)) { + clack.log.warn( + `Sentry is already configured in ${chalk.cyan( + workerFilePath, + )}. Skipping wrapping with Sentry.`, + ); + return; + } + + workerAst.imports.$add({ + from: "@sentry/cloudflare", + imported: "*", + local: "Sentry", + }); + + recast.visit(workerAst.$ast, { + visitExportDefaultDeclaration(path) { + const originalDeclaration = path.node.declaration as ExpressionKind; + const sentryConfig = createSentryConfigFunction( + dsn, + selectedFeatures, + reduceDataCollection, + ); + const wrappedExport = b.callExpression( + b.memberExpression(b.identifier("Sentry"), b.identifier("withSentry")), + [sentryConfig, originalDeclaration], + ); + + path.node.declaration = wrappedExport; + + return false; + }, + }); + + await writeFile(workerAst.$ast, workerFilePath); +} + +/** + * Creates the Sentry config function: (env) => ({ dsn: '...', ... }) + */ +function createSentryConfigFunction( + dsn: string, + selectedFeatures: { + performance: boolean; + }, + reduceDataCollection: boolean, +): t.ArrowFunctionExpression { + const configProperties: t.ObjectProperty[] = [ + b.objectProperty(b.identifier("dsn"), b.stringLiteral(dsn)), + ]; + + if (selectedFeatures.performance) { + const tracesSampleRateProperty = b.objectProperty( + b.identifier("tracesSampleRate"), + b.numericLiteral(1), + ); + + tracesSampleRateProperty.comments = [ + b.commentLine( + " Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control.", + true, + false, + ), + ]; + + configProperties.push(tracesSampleRateProperty); + } + + if (reduceDataCollection) { + const dataCollectionProperty = b.objectProperty( + b.identifier("dataCollection"), + literalValueToAst(DATA_COLLECTION_PII_PRESET), + ); + + dataCollectionProperty.comments = DATA_COLLECTION_COMMENT_LINES.map( + (line) => b.commentLine(` ${line}`, true, false), + ); + + configProperties.push(dataCollectionProperty); + } + + const configObject = b.objectExpression(configProperties); + + return b.arrowFunctionExpression([b.identifier("env")], configObject); +} + +/** + * Converts a plain JSON-like value (booleans, strings, arrays, objects) into + * the equivalent AST expression. + */ +function literalValueToAst(value: unknown): ExpressionKind { + if (typeof value === "boolean") { + return b.booleanLiteral(value); + } + if (typeof value === "string") { + return b.stringLiteral(value); + } + if (Array.isArray(value)) { + return b.arrayExpression(value.map(literalValueToAst)); + } + + if (typeof value !== "object" || value === null) { + throw new TypeError( + `Unsupported value in a Sentry option: ${String(value)}`, + ); + } + + return b.objectExpression( + Object.entries(value).map(([key, entryValue]) => + b.objectProperty(b.identifier(key), literalValueToAst(entryValue)), + ), + ); +} diff --git a/packages/cli/src/lib/wizard/run.ts b/packages/cli/src/lib/wizard/run.ts index 8bd377980b..c5166afe30 100644 --- a/packages/cli/src/lib/wizard/run.ts +++ b/packages/cli/src/lib/wizard/run.ts @@ -55,6 +55,16 @@ const WIZARD_RUNNERS: Partial> = { const { runNextjsWizard } = await import("./nextjs/nextjs-wizard.js"); await runNextjsWizard(options); }, + cloudflare: async (options) => { + const { runCloudflareWizard } = + await import("./cloudflare/cloudflare-wizard.js"); + await runCloudflareWizard(options); + }, + sourcemaps: async (options) => { + const { runSourcemapsWizard } = + await import("./sourcemaps/sourcemaps-wizard.js"); + await runSourcemapsWizard(options); + }, }; /** What `sentry wizard` passes to {@link runWizard}. */ diff --git a/packages/cli/src/lib/wizard/sourcemaps/ci.ts b/packages/cli/src/lib/wizard/sourcemaps/ci.ts index e725f44a51..b5d8a558ef 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/ci.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/ci.ts @@ -14,6 +14,7 @@ import { } from "../utils/clack/index.js"; import { clack } from "../utils/clack/prompts.js"; import type { WizardOptions } from "../utils/types.js"; +import { setupNpmScriptInCI } from "./tools/sentry-cli.js"; /** Tools that upload with `sentry` commands and read `.sentryclirc`. */ const CLI_BASED_FLOW_TOOLS: readonly string[] = [ @@ -46,7 +47,10 @@ export async function setupCI( } } -/** Ask about CI and show the auth token to set there. */ +/** + * Ask about CI, ask the user to run the `sentry:sourcemaps` script there + * for the tools that upload with it, and show the auth token to set there. + */ async function configureCI( selectedTool: string, authToken: string, @@ -72,7 +76,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; @@ -85,6 +91,10 @@ async function configureCI( return; } + if (isCliBasedFlowTool) { + await traceStep("ci-npm-script-setup", setupNpmScriptInCI); + } + await traceStep("ci-auth-token-setup", () => setupAuthTokenInCI(authToken)); } diff --git a/packages/cli/src/lib/wizard/sourcemaps/sourcemaps-wizard.ts b/packages/cli/src/lib/wizard/sourcemaps/sourcemaps-wizard.ts new file mode 100644 index 0000000000..f82357a991 --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/sourcemaps-wizard.ts @@ -0,0 +1,293 @@ +/** + * The source maps wizard: configures a project's build tool to upload source + * maps to Sentry, either with a bundler plugin or with `sentry sourcemap` + * commands in an npm script. + */ + +import chalk from "chalk"; +import { sep } from "node:path"; + +import { Sentry, traceStep, withTelemetry } from "../telemetry.js"; +import { + abort, + abortIfCancelled, + confirmContinueIfNoOrDirtyGitRepo, + getOrAskForProjectData, + getPackageManager, + printWelcome, + runPrettierIfInstalled, +} from "../utils/clack/index.js"; +import { clack } from "../utils/clack/prompts.js"; +import { NPM } from "../utils/package-manager.js"; +import type { WizardOptions } from "../utils/types.js"; +import { getIssueStreamUrl } from "../utils/url.js"; +import { isUnicodeSupported } from "../utils/vendor/is-unicorn-supported.js"; +import { setupCI } from "./ci.js"; +import { configureAngularSourcemapGenerationFlow } from "./tools/angular.js"; +import { configureCRASourcemapGenerationFlow } from "./tools/create-react-app.js"; +import { configureEsbuildPlugin } from "./tools/esbuild.js"; +import { configureRollupPlugin } from "./tools/rollup.js"; +import { configureSentryCLI } from "./tools/sentry-cli.js"; +import { configureTscSourcemapGenerationFlow } from "./tools/tsc.js"; +import type { SourceMapUploadToolConfigurationOptions } from "./tools/types.js"; +import { configureVitePlugin } from "./tools/vite.js"; +import { configureWebPackPlugin } from "./tools/webpack.js"; +import { configureWrangler } from "./tools/wrangler.js"; +import type { SupportedTools } from "./utils/detect-tool.js"; +import { detectUsedTool } from "./utils/detect-tool.js"; +import { checkIfMoreSuitableWizardExistsAndAskForRedirect } from "./utils/other-wizards.js"; +import { ensureMinimumSdkVersionIsInstalled } from "./utils/sdk-version.js"; + +/** + * Run the source maps wizard (`sentry wizard -i sourcemaps`). Framework + * wizards pass `preSelectedTool` to run only the tool and CI setup. + */ +export async function runSourcemapsWizard( + options: WizardOptions, + preSelectedTool?: SupportedTools, +): Promise { + return await withTelemetry( + { + enabled: options.telemetryEnabled, + integration: "sourcemaps", + wizardOptions: options, + }, + () => runSourcemapsWizardWithTelemetry(options, preSelectedTool), + ); +} + +async function runSourcemapsWizardWithTelemetry( + options: WizardOptions, + preSelectedTool?: SupportedTools, +): Promise { + if (!preSelectedTool) { + printWelcome({ + wizardName: "Sentry Source Maps Upload Configuration Wizard", + message: `This wizard will help you upload source maps to Sentry as part of your build. +Thank you for using Sentry :)`, + promoCode: options.promoCode, + telemetryEnabled: options.telemetryEnabled, + }); + } + + const moreSuitableWizard = await traceStep( + "check-framework-wizard", + checkIfMoreSuitableWizardExistsAndAskForRedirect, + ); + if (moreSuitableWizard) { + await traceStep("run-framework-wizard", () => moreSuitableWizard(options)); + return; + } + + if (!preSelectedTool) { + await confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: options.ignoreGitChanges, + cwd: undefined, + }); + } + + await traceStep("check-sdk-version", ensureMinimumSdkVersionIsInstalled); + + const projectData = await getOrAskForProjectData({ + ...options, + spotlight: false, + }); + + if (projectData.spotlight) { + // `spotlight: false` above makes this unreachable; it narrows the type + return await abort("Source maps upload needs a Sentry project."); + } + + const { selfHosted, selectedProject, sentryUrl, authToken } = projectData; + + const selectedTool = + preSelectedTool ?? (await traceStep("select-tool", askForUsedBundlerTool)); + + Sentry.setTag("selected-tool", selectedTool); + + if (selectedTool === "no-tool") { + clack.log.info( + "No Problem! But in this case, there's nothing to configure :)", + ); + await abort("Exiting, have a great day!", 0); + } + + await traceStep("tool-setup", () => + startToolSetupFlow( + selectedTool, + { + orgSlug: selectedProject.organization.slug, + projectSlug: selectedProject.slug, + selfHosted, + url: sentryUrl, + authToken, + }, + preSelectedTool, + ), + ); + + await traceStep("ci-setup", () => + setupCI(selectedTool, authToken, options.comingFrom), + ); + + if (!preSelectedTool) { + // running prettier is only necessary if the source maps wizard is the main flow + // skip it, if it's called from another wizard (e.g. angular) + await runPrettierIfInstalled({ cwd: process.cwd() }); + } + + if (!preSelectedTool) { + await traceStep("outro", () => + printOutro( + sentryUrl, + selectedProject.organization.slug, + selectedProject.id, + ), + ); + } +} + +async function askForUsedBundlerTool(): Promise { + const selectedTool = await abortIfCancelled( + clack.select({ + message: "Which framework, bundler or build tool are you using?", + options: [ + { + label: "Angular", + value: "angular", + hint: "Select this option if you are using Angular.", + }, + { + label: "Create React App", + value: "create-react-app", + hint: "Select this option if you set up your app with Create React App.", + }, + { + label: "Cloudflare Wrangler", + value: "wrangler", + hint: "You're using `wrangler deploy` to build and deploy your Cloudflare Worker.", + }, + { + label: "Webpack", + value: "webpack", + hint: "Select this if you are using Webpack and you have access to your Webpack config.", + }, + { + label: "Vite", + value: "vite", + hint: "Select this if you are using Vite and you have access to your Vite config.", + }, + { + label: "esbuild", + value: "esbuild", + hint: "Select this if you are using esbuild and you have access to your esbuild config.", + }, + { + label: "Rollup", + value: "rollup", + hint: "Select this if you are using Rollup and you have access to your Rollup config.", + }, + { + label: "tsc", + value: "tsc", + hint: "Configure source maps when using tsc as build tool", + }, + { + label: "I use another tool", + value: "sentry-cli", + hint: "This will configure source maps upload for you using the Sentry CLI", + }, + { + label: "I don't minify, transpile or bundle my code", + value: "no-tool", + hint: "This will exit the wizard", + }, + ], + initialValue: await detectUsedTool(), + }), + ); + + return selectedTool; +} + +async function startToolSetupFlow( + selectedTool: SupportedTools, + options: SourceMapUploadToolConfigurationOptions, + preSelectedTool?: SupportedTools, +): Promise { + switch (selectedTool) { + case "webpack": + await configureWebPackPlugin(options); + break; + case "vite": + await configureVitePlugin(options); + break; + case "esbuild": + await configureEsbuildPlugin(options); + break; + case "rollup": + await configureRollupPlugin(options); + break; + case "tsc": + await configureSentryCLI(options, configureTscSourcemapGenerationFlow); + break; + case "create-react-app": + await configureSentryCLI( + { ...options, defaultArtifactPath: `.${sep}build` }, + configureCRASourcemapGenerationFlow, + ); + break; + case "wrangler": + await configureWrangler(options); + break; + case "angular": + await configureSentryCLI( + { ...options, defaultArtifactPath: `.${sep}dist` }, + configureAngularSourcemapGenerationFlow, + preSelectedTool === "angular", + ); + break; + default: + await configureSentryCLI(options); + break; + } +} +async function printOutro( + url: string, + orgSlug: string, + projectId: string, +): Promise { + const packageManager = await getPackageManager(NPM); + + const issueStreamUrl = getIssueStreamUrl({ url, orgSlug, projectId }); + + const arrow = isUnicodeSupported() ? "→" : "->"; + + clack.outro(`${chalk.green("That's it - everything is set up!")} + + ${chalk.cyan(`Test and validate your setup locally with the following Steps: + + 1. Build your application in ${chalk.bold("production mode")}. + ${chalk.gray( + `${arrow} For example, run ${chalk.bold(packageManager.buildCommand)}.`, + )} + ${chalk.gray( + `${arrow} You should see source map upload logs in your console.`, + )} + 2. Run your application and throw a test error. + ${chalk.gray(`${arrow} The error should appear in Sentry:`)} + ${chalk.gray(`${arrow} ${issueStreamUrl}`)} + 3. Open the error in Sentry and verify that it's source-mapped. + ${chalk.gray( + `${arrow} The stack trace should show your original source code.`, + )} + `)} + ${chalk.dim( + `If you encounter any issues, please refer to the Troubleshooting Guide: + https://docs.sentry.io/platforms/javascript/sourcemaps/troubleshooting_js + + If the guide doesn't help or you encounter a bug, please let us know: + https://github.com/getsentry/sentry-javascript/issues`, + )} +`); +} 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 0000000000..5e757e02c7 --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/angular.ts @@ -0,0 +1,48 @@ +/** + * Source map generation step for Angular: ask the user to turn on + * `sourceMap` in `angular.json`. + */ + +import chalk from "chalk"; +import { abortIfCancelled, makeCodeSnippet } from "../../utils/clack/index.js"; +import { clack } from "../../utils/clack/prompts.js"; + +const angularJsonTemplate = makeCodeSnippet(true, (unchanged, plus) => + unchanged(`{ + "projects": { + 'your-project': { + "architect": { + "build": { + "options": { + ${plus(`"sourceMap": true`)} + }, + }, + } + } + } +}`), +); + +/** Show the `angular.json` change and wait until the user made 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/create-react-app.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/create-react-app.ts new file mode 100644 index 0000000000..44c6023238 --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/create-react-app.ts @@ -0,0 +1,24 @@ +/** + * Source map generation step for Create React App, which generates source + * maps unless `GENERATE_SOURCEMAP` is off. + */ + +import { abortIfCancelled } from "../../utils/clack/index.js"; +import { clack } from "../../utils/clack/prompts.js"; + +/** Ask the user to confirm that the CRA build generates source maps. */ +export async function configureCRASourcemapGenerationFlow(): Promise { + await abortIfCancelled( + clack.select({ + message: `Verify that you are generating source maps when building your React app.\nGenerally this should already happen unless you set the GENERATE_SOURCEMAPS environment variable to false.`, + 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/esbuild.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/esbuild.ts new file mode 100644 index 0000000000..92a4c2cac2 --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/esbuild.ts @@ -0,0 +1,63 @@ +/** + * Source maps setup for esbuild: install the Sentry esbuild plugin and show + * the config change to make. + */ + +import chalk from "chalk"; +import { + abortIfCancelled, + addDotEnvSentryBuildPluginFile, +} from "../../utils/clack/index.js"; +import { clack } from "../../utils/clack/prompts.js"; +import { ensureBundlerPlugin } from "../utils/bundler-plugin.js"; + +import type { + SourceMapUploadToolConfigurationFunction, + SourceMapUploadToolConfigurationOptions, +} from "./types.js"; + +const getCodeSnippet = ( + options: SourceMapUploadToolConfigurationOptions, + importPath: string, +) => + chalk.gray(` +${chalk.greenBright( + `const { sentryEsbuildPlugin } = require("${importPath}");`, +)} + +require("esbuild").build({ + ${chalk.greenBright( + "sourcemap: true, // Source map generation must be turned on", + )} + plugins: [ + // Put the Sentry esbuild plugin after all other plugins + ${chalk.greenBright(`sentryEsbuildPlugin({ + authToken: process.env.SENTRY_AUTH_TOKEN, + org: "${options.orgSlug}", + project: "${options.projectSlug}",${ + options.selfHosted ? `\n url: "${options.url}",` : "" + } + }),`)} + ], +}); +`); + +export const configureEsbuildPlugin: SourceMapUploadToolConfigurationFunction = + async (options) => { + const importPath = await ensureBundlerPlugin("esbuild"); + + clack.log.step(`Add the following code to your esbuild config:`); + + // Printed outside clack's gutter so that it can be copied/pasted directly + clack.rawOutput(getCodeSnippet(options, importPath)); + + await abortIfCancelled( + clack.select({ + message: "Did you copy the snippet above?", + options: [{ label: "Yes, continue!", value: true }], + initialValue: true, + }), + ); + + await addDotEnvSentryBuildPluginFile(options.authToken); + }; diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/rollup.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/rollup.ts new file mode 100644 index 0000000000..bc581065f2 --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/rollup.ts @@ -0,0 +1,63 @@ +/** + * Source maps setup for Rollup: install the Sentry Rollup plugin and show + * the config change to make. + */ + +import chalk from "chalk"; +import { + abortIfCancelled, + addDotEnvSentryBuildPluginFile, +} from "../../utils/clack/index.js"; +import { clack } from "../../utils/clack/prompts.js"; +import { ensureBundlerPlugin } from "../utils/bundler-plugin.js"; + +import type { + SourceMapUploadToolConfigurationFunction, + SourceMapUploadToolConfigurationOptions, +} from "./types.js"; + +const getCodeSnippet = ( + options: SourceMapUploadToolConfigurationOptions, + importPath: string, +) => + chalk.gray(` +${chalk.greenBright(`import { sentryRollupPlugin } from "${importPath}";`)} + +export default { + output: { + ${chalk.greenBright( + "sourcemap: true, // Source map generation must be turned on", + )} + }, + plugins: [ + // Put the Sentry rollup plugin after all other plugins + ${chalk.greenBright(`sentryRollupPlugin({ + authToken: process.env.SENTRY_AUTH_TOKEN, + org: "${options.orgSlug}", + project: "${options.projectSlug}",${ + options.selfHosted ? `\n url: "${options.url}",` : "" + } + }),`)} + ], +}; +`); + +export const configureRollupPlugin: SourceMapUploadToolConfigurationFunction = + async (options) => { + const importPath = await ensureBundlerPlugin("rollup"); + + clack.log.step(`Add the following code to your rollup config:`); + + // Printed outside clack's gutter so that it can be copied/pasted directly + clack.rawOutput(getCodeSnippet(options, importPath)); + + await abortIfCancelled( + clack.select({ + message: "Did you copy the snippet above?", + options: [{ label: "Yes, continue!", value: true }], + initialValue: true, + }), + ); + + await addDotEnvSentryBuildPluginFile(options.authToken); + }; 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 0000000000..fc56d36a4d --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts @@ -0,0 +1,348 @@ +/** + * Source maps setup for projects without a supported bundler plugin: install + * the `sentry` CLI and add a `sentry:sourcemaps` npm script that injects + * debug IDs into the build output and uploads it. + * + * sentry-wizard installed `@sentry/cli@^2` and wrote `sentry-cli sourcemaps + * inject/upload` scripts. These are the v4 `sentry sourcemap` commands. + */ + +import chalk from "chalk"; +import { promises } from "node:fs"; +import path from "node:path"; + +import { Sentry, traceStep } from "../../telemetry.js"; +import { + abortIfCancelled, + addSentryCliConfig, + artifactsExist, + askToRunBuildOrEnterPathOrProceed, + getPackageDotJson, + getPackageManager, + installPackage, +} from "../../utils/clack/index.js"; +import { clack } from "../../utils/clack/prompts.js"; +import { hasPackageInstalled } from "../../utils/package-json.js"; +import { NPM } from "../../utils/package-manager.js"; +import type { SourceMapUploadToolConfigurationOptions } from "./types.js"; + +/** The npm package of the `sentry` CLI. */ +export const SENTRY_CLI_PACKAGE = "sentry"; + +/** The `sentry` CLI major the generated scripts are written for. */ +export const SENTRY_CLI_PACKAGE_RANGE = `${SENTRY_CLI_PACKAGE}@^4`; + +const SENTRY_NPM_SCRIPT_NAME = "sentry:sourcemaps"; + +let addedToBuildCommand = false; + +type ConfigureSentryCLIOptions = SourceMapUploadToolConfigurationOptions & { + defaultArtifactPath?: string | undefined; +}; + +/** + * Install the `sentry` CLI, ask for the build output directory, and add the + * `sentry:sourcemaps` script (optionally to the production build command). + * + * @param configureSourcemapGenerationFlow - Tool-specific step that makes + * sure the build emits source maps + * @param skipValidation - Skip `configureSourcemapGenerationFlow`, for + * callers (the Angular wizard) that already configured it + */ +export async function configureSentryCLI( + options: ConfigureSentryCLIOptions, + configureSourcemapGenerationFlow: () => Promise = defaultConfigureSourcemapGenerationFlow, + skipValidation = false, +): Promise { + const packageDotJson = await getPackageDotJson(); + + await installPackage({ + packageName: SENTRY_CLI_PACKAGE_RANGE, + packageNameDisplayLabel: SENTRY_CLI_PACKAGE, + alreadyInstalled: hasPackageInstalled(SENTRY_CLI_PACKAGE, packageDotJson), + }); + + 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)) { + 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(options, 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 addSentryCliConfig({ authToken: options.authToken }); +} + +/** + * Ask the user to run the `sentry:sourcemaps` script in CI, unless the + * wizard already added it to the build command. + */ +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: inject debug IDs into the build output, + * then upload it. A self-hosted URL goes in `SENTRY_URL`, which replaced + * the `--url` flag of sentry-cli. + */ +export function getSentryCliNpmScript( + options: SourceMapUploadToolConfigurationOptions, + relativePosixArtifactPath: string, +): string { + const urlEnv = options.selfHosted ? `SENTRY_URL=${options.url} ` : ""; + // oxlint-disable-next-line sentry-cli/no-hardcoded-sentry-command -- runs the project's installed `sentry` package from its package.json scripts, not a hint + return `sentry sourcemap inject ${relativePosixArtifactPath} && ${urlEnv}sentry sourcemap upload --org ${options.orgSlug} --project ${options.projectSlug} ${relativePosixArtifactPath}`; +} + +async function createAndAddNpmScript( + options: SourceMapUploadToolConfigurationOptions, + relativePosixArtifactPath: string, +): Promise { + const packageDotJson = await getPackageDotJson(); + + packageDotJson.scripts = packageDotJson.scripts || {}; + packageDotJson.scripts[SENTRY_NPM_SCRIPT_NAME] = getSentryCliNpmScript( + options, + relativePosixArtifactPath, + ); + + 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 + */ +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 scripts = packageDotJson.scripts; + + const allNpmScripts = Object.keys(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 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 = 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)}`, + ); + + return; + } + + 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/tsc.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/tsc.ts new file mode 100644 index 0000000000..5be895cc3e --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/tsc.ts @@ -0,0 +1,145 @@ +/** + * Source map generation step for tsc: turn on `sourceMap`, `inlineSources`, + * and `sourceRoot` in `tsconfig.json`. + */ + +import chalk from "chalk"; +import { promises } from "node:fs"; +import path from "node:path"; +import recast from "recast"; + +import { Sentry } from "../../telemetry.js"; +import { + findFile, + getOrSetObjectProperty, + parseJsonC, + printJsonC, + setOrUpdateObjectProperty, +} from "../../utils/ast-utils.js"; +import { + askForToolConfigPath, + createNewConfigFile, + makeCodeSnippet, + showCopyPasteInstructions, +} from "../../utils/clack/index.js"; +import { clack } from "../../utils/clack/prompts.js"; +import { debug } from "../../utils/debug.js"; + +const b = recast.types.builders; + +const getCodeSnippet = (colors: boolean) => + makeCodeSnippet(colors, (unchanged, plus, _) => + unchanged( + `{ + "compilerOptions": { + ${plus('"sourceMap": true,')} + ${plus('"inlineSources": true,')} + + // Set \`sourceRoot\` to "/" to strip the build path prefix from + // generated source code references. This will improve issue grouping in Sentry. + ${plus('"sourceRoot": "/"')} + } +}`, + ), + ); + +export async function configureTscSourcemapGenerationFlow(): Promise { + const tsConfigPath = + findFile(path.join(process.cwd(), "tsconfig"), [".json"]) ?? + (await askForToolConfigPath("TypeScript", "tsconfig.json")); + + let successfullyAdded = false; + if (tsConfigPath) { + successfullyAdded = await enableSourcemaps(tsConfigPath); + } else { + successfullyAdded = await createNewConfigFile( + path.join(process.cwd(), "tsconfig.json"), + getCodeSnippet(false), + ); + Sentry.setTag("created-new-config", successfullyAdded ? "success" : "fail"); + } + + if (successfullyAdded) { + Sentry.setTag("ast-mod", "success"); + clack.log.info( + `We recommend checking the ${ + tsConfigPath ? "modified" : "added" + } file after the wizard finished to ensure it works with your build setup.`, + ); + } else { + Sentry.setTag("ast-mod", "fail"); + await showCopyPasteInstructions({ + filename: "tsconfig.json", + codeSnippet: getCodeSnippet(true), + hint: "This ensures that source maps are generated correctly", + }); + } +} + +/** + * Modifies tsconfig.json (@param tsConfigPath) to enable source maps generation. + * + * Exported only for testing + */ +export async function enableSourcemaps(tsConfigPath: string): Promise { + try { + const tsConfig = await promises.readFile(tsConfigPath, "utf-8"); + + const { ast, jsonObject } = parseJsonC(tsConfig.toString()); + + if (!jsonObject) { + // this will only happen if the input file isn't valid JSON-C + Sentry.setTag("ast-mod-fail-reason", "original-file-invalid"); + return false; + } + + const compilerOptionsProp = getOrSetObjectProperty( + jsonObject, + "compilerOptions", + b.objectExpression([]), + ); + + const compilerOptionsObj = compilerOptionsProp.value; + + if (compilerOptionsObj.type !== "ObjectExpression") { + // a valid compilerOptions prop should always be an object expression + Sentry.setTag("ast-mod-fail-reason", "original-file-invalid"); + return false; + } + + setOrUpdateObjectProperty( + compilerOptionsObj, + "sourceMap", + b.booleanLiteral(true), + ); + + setOrUpdateObjectProperty( + compilerOptionsObj, + "inlineSources", + b.booleanLiteral(true), + ); + + setOrUpdateObjectProperty( + compilerOptionsObj, + "sourceRoot", + b.stringLiteral("/"), + 'Set `sourceRoot` to "/" to strip the build path prefix\nfrom generated source code references.\nThis improves issue grouping in Sentry.', + ); + + const code = printJsonC(ast); + + await promises.writeFile(tsConfigPath, code); + + clack.log.success( + `Enabled source maps generation in ${chalk.cyan( + path.basename(tsConfigPath || "tsconfig.json"), + )}.`, + ); + + return true; + } catch (e) { + debug(e); + Sentry.setTag("ast-mod-fail-reason", "insertion-fail"); + return false; + } +} 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 0000000000..e6fe4d4689 --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/types.ts @@ -0,0 +1,15 @@ +/** + * Options every source maps upload tool setup takes. + */ + +export type SourceMapUploadToolConfigurationOptions = { + selfHosted: boolean; + url: string; + authToken: string; + orgSlug: string; + projectSlug: string; +}; + +export type SourceMapUploadToolConfigurationFunction = ( + options: SourceMapUploadToolConfigurationOptions, +) => Promise; diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/vite.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/vite.ts new file mode 100644 index 0000000000..d2a62f70d0 --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/vite.ts @@ -0,0 +1,306 @@ +/** + * Source maps setup for Vite: add the Sentry Vite plugin to the Vite config + * and turn on `build.sourcemap`. + */ + +import type { namedTypes as t } from "ast-types"; +import chalk from "chalk"; +import { generateCode, parseModule } from "magicast"; +import { addVitePlugin } from "magicast/helpers"; +import { promises } from "node:fs"; +import path from "node:path"; +import recast from "recast"; + +import { Sentry } from "../../telemetry.js"; +import { + findFile, + hasSentryContent, + preserveTrailingNewline, +} from "../../utils/ast-utils.js"; +import { + abortIfCancelled, + addDotEnvSentryBuildPluginFile, + askForToolConfigPath, + createNewConfigFile, + makeCodeSnippet, + showCopyPasteInstructions, +} from "../../utils/clack/index.js"; +import { clack } from "../../utils/clack/prompts.js"; +import { debug } from "../../utils/debug.js"; +import { ensureBundlerPlugin } from "../utils/bundler-plugin.js"; +import type { + SourceMapUploadToolConfigurationFunction, + SourceMapUploadToolConfigurationOptions, +} from "./types.js"; + +const getViteConfigSnippet = ( + options: SourceMapUploadToolConfigurationOptions, + colors: boolean, + importPath: string, +) => + makeCodeSnippet(colors, (unchanged, plus, _) => + unchanged(`import { defineConfig } from "vite"; +${plus(`import { sentryVitePlugin } from "${importPath}";`)} + +export default defineConfig({ + build: { + ${plus("sourcemap: true, // Source map generation must be turned on")} + }, + plugins: [ + // Put the Sentry vite plugin after all other plugins + ${plus(`sentryVitePlugin({ + authToken: process.env.SENTRY_AUTH_TOKEN, + org: "${options.orgSlug}", + project: "${options.projectSlug}",${ + options.selfHosted ? `\n url: "${options.url}",` : "" + } + }),`)} + ], +});`), + ); + +export const configureVitePlugin: SourceMapUploadToolConfigurationFunction = + async (options) => { + const importPath = await ensureBundlerPlugin("vite"); + + const viteConfigPath = + findFile(path.resolve(process.cwd(), "vite.config")) ?? + (await askForToolConfigPath("Vite", "vite.config.js")); + + let successfullyAdded = false; + if (viteConfigPath) { + successfullyAdded = await addVitePluginToConfig( + viteConfigPath, + options, + importPath, + ); + } else { + successfullyAdded = await createNewConfigFile( + path.join(process.cwd(), "vite.config.js"), + getViteConfigSnippet(options, false, importPath), + "More information about vite configs: https://vitejs.dev/config/", + ); + Sentry.setTag( + "created-new-config", + successfullyAdded ? "success" : "fail", + ); + } + + if (successfullyAdded) { + clack.log.info( + `We recommend checking the ${ + viteConfigPath ? "modified" : "added" + } file after the wizard finished to ensure it works with your build setup.`, + ); + + Sentry.setTag("ast-mod", "success"); + } else { + Sentry.setTag("ast-mod", "fail"); + await showCopyPasteInstructions({ + filename: path.basename(viteConfigPath || "vite.config.js"), + codeSnippet: getViteConfigSnippet(options, true, importPath), + }); + } + + await addDotEnvSentryBuildPluginFile(options.authToken); + }; + +export async function addVitePluginToConfig( + viteConfigPath: string, + options: SourceMapUploadToolConfigurationOptions, + importPath: string, +): Promise { + try { + const prettyViteConfigFilename = chalk.cyan(path.basename(viteConfigPath)); + + const viteConfigContent = ( + await promises.readFile(viteConfigPath) + ).toString(); + + const mod = parseModule(viteConfigContent); + + if (hasSentryContent(mod.$ast as t.Program)) { + const shouldContinue = await abortIfCancelled( + clack.select({ + message: `${prettyViteConfigFilename} already contains Sentry-related code. Should the wizard modify it anyway?`, + options: [ + { + label: "Yes, add the Sentry Vite plugin", + value: true, + }, + { + label: "No, show me instructions to manually add the plugin", + value: false, + }, + ], + initialValue: true, + }), + ); + + if (!shouldContinue) { + Sentry.setTag("ast-mod-fail-reason", "has-sentry-content"); + return false; + } + } + + const enabledSourcemaps = enableSourcemapGeneration(mod.$ast as t.Program); + if (!enabledSourcemaps) { + Sentry.setTag("ast-mod-fail-reason", "insertion-fail"); + return false; + } + + const { orgSlug: org, projectSlug: project, selfHosted, url } = options; + + addVitePlugin(mod, { + imported: "sentryVitePlugin", + from: importPath, + constructor: "sentryVitePlugin", + options: { + org, + project, + ...(selfHosted && { url }), + }, + }); + + const code = preserveTrailingNewline( + viteConfigContent, + generateCode(mod.$ast).code, + ); + + await promises.writeFile(viteConfigPath, code); + + clack.log.success( + `Added the Sentry Vite plugin to ${prettyViteConfigFilename} and enabled source maps`, + ); + + return true; + } catch (e) { + debug(e); + Sentry.setTag("ast-mod-fail-reason", "insertion-fail"); + return false; + } +} + +function enableSourcemapGeneration(program: t.Program): boolean { + const configObj = getViteConfigObject(program); + + if (!configObj) { + return false; + } + + const b = recast.types.builders; + + const buildProp = findPropertyByName(configObj.properties, "build"); + + // case 1: build property doesn't exist yet, so we can just add it + if (!buildProp) { + configObj.properties.push( + b.objectProperty( + b.identifier("build"), + b.objectExpression([ + b.objectProperty(b.identifier("sourcemap"), b.booleanLiteral(true)), + ]), + ), + ); + return true; + } + + if ( + buildProp.type !== "ObjectProperty" || + buildProp.value.type !== "ObjectExpression" + ) { + return false; + } + + const buildObj = buildProp.value; + const sourceMapsProp = findPropertyByName(buildObj.properties, "sourcemap"); + + // case 2: build.sourcemap property doesn't exist yet, so we just add it + if (!sourceMapsProp) { + buildObj.properties.push( + b.objectProperty(b.identifier("sourcemap"), b.booleanLiteral(true)), + ); + return true; + } + + if (sourceMapsProp.type !== "ObjectProperty") { + return false; + } + + // case 3: build.sourcemap property exists, and it's set to 'hidden' + if ( + sourceMapsProp.value.type === "StringLiteral" && + sourceMapsProp.value.value === "hidden" + ) { + // nothing to do for us + return true; + } + + // case 4: build.sourcemap property exists, but it's not enabled, so we set it to true + // or it is already true in which case this is a noop + sourceMapsProp.value = b.booleanLiteral(true); + return true; +} + +/** The property of `properties` whose identifier key is `name`. */ +function findPropertyByName( + properties: t.ObjectExpression["properties"], + name: string, +): t.ObjectMethod | t.ObjectProperty | t.Property | undefined { + return properties.find( + (p): p is t.ObjectMethod | t.ObjectProperty | t.Property => + "key" in p && p.key.type === "Identifier" && p.key.name === name, + ); +} + +function getViteConfigObject( + program: t.Program, +): t.ObjectExpression | undefined { + const defaultExport = program.body.find( + (s): s is t.ExportDefaultDeclaration => + s.type === "ExportDefaultDeclaration", + ); + + if (!defaultExport) { + return undefined; + } + + if (defaultExport.declaration.type === "ObjectExpression") { + return defaultExport.declaration; + } + + if (defaultExport.declaration.type === "CallExpression") { + const [firstArg] = defaultExport.declaration.arguments; + if (firstArg?.type === "ObjectExpression") { + return firstArg; + } + } + + if (defaultExport.declaration.type === "Identifier") { + const configId = defaultExport.declaration.name; + return findConfigNode(configId, program); + } + + return undefined; +} + +function findConfigNode( + configId: string, + program: t.Program, +): t.ObjectExpression | undefined { + for (const node of program.body) { + if (node.type === "VariableDeclaration") { + for (const declaration of node.declarations) { + if ( + declaration.type === "VariableDeclarator" && + declaration.id.type === "Identifier" && + declaration.id.name === configId && + declaration.init?.type === "ObjectExpression" + ) { + return declaration.init; + } + } + } + } + return undefined; +} diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/webpack.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/webpack.ts new file mode 100644 index 0000000000..0e32d5c529 --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/webpack.ts @@ -0,0 +1,382 @@ +/** + * Source maps setup for webpack: add the Sentry webpack plugin to a CommonJS + * webpack config and turn on `devtool: "source-map"`. + */ + +import type { namedTypes as t } from "ast-types"; +import chalk from "chalk"; +import { promises } from "node:fs"; +import path from "node:path"; +import recast from "recast"; + +import { Sentry } from "../../telemetry.js"; +import { findFile, hasSentryContent } from "../../utils/ast-utils.js"; +import { + abortIfCancelled, + addDotEnvSentryBuildPluginFile, + askForToolConfigPath, + createNewConfigFile, + makeCodeSnippet, + showCopyPasteInstructions, +} from "../../utils/clack/index.js"; +import { clack } from "../../utils/clack/prompts.js"; +import { debug } from "../../utils/debug.js"; +import { ensureBundlerPlugin } from "../utils/bundler-plugin.js"; +import type { + SourceMapUploadToolConfigurationFunction, + SourceMapUploadToolConfigurationOptions, +} from "./types.js"; + +const getCodeSnippet = ( + options: SourceMapUploadToolConfigurationOptions, + colors: boolean, + importPath: string, +) => + makeCodeSnippet(colors, (unchanged, plus) => + unchanged(`${plus( + `const { sentryWebpackPlugin } = require("${importPath}");`, + )} + +module.exports = { + // ... other options + ${plus('devtool: "source-map", // Source map generation must be turned on')} + plugins: [ + // Put the Sentry Webpack plugin after all other plugins + ${plus(`sentryWebpackPlugin({ + authToken: process.env.SENTRY_AUTH_TOKEN, + org: "${options.orgSlug}", + project: "${options.projectSlug}",${ + options.selfHosted ? `\n url: "${options.url}",` : "" + } + }),`)} + ], +}`), + ); + +export const configureWebPackPlugin: SourceMapUploadToolConfigurationFunction = + async (options) => { + const importPath = await ensureBundlerPlugin("webpack"); + + const webpackConfigPath = + findFile(path.resolve(process.cwd(), "webpack.config")) ?? + (await askForToolConfigPath("Webpack", "webpack.config.js")); + + let successfullyAdded = false; + if (webpackConfigPath) { + successfullyAdded = await modifyWebpackConfig( + webpackConfigPath, + options, + importPath, + ); + } else { + successfullyAdded = await createNewConfigFile( + path.join(process.cwd(), "webpack.config.js"), + getCodeSnippet(options, false, importPath), + "More information about Webpack configs: https://vitejs.dev/config/", + ); + Sentry.setTag( + "created-new-config", + successfullyAdded ? "success" : "fail", + ); + } + + if (successfullyAdded) { + clack.log.info( + `We recommend checking the ${ + webpackConfigPath ? "modified" : "added" + } file after the wizard finished to ensure it works with your build setup.`, + ); + + Sentry.setTag("ast-mod", "success"); + } else { + Sentry.setTag("ast-mod", "fail"); + await showCopyPasteInstructions({ + filename: path.basename(webpackConfigPath || "webpack.config.js"), + codeSnippet: getCodeSnippet(options, true, importPath), + }); + } + + await addDotEnvSentryBuildPluginFile(options.authToken); + }; + +/** + * Modifies a webpack config file to enable source map generation and add the Sentry webpack plugin + * exported only for testing + */ +export async function modifyWebpackConfig( + webpackConfigPath: string, + options: SourceMapUploadToolConfigurationOptions, + importPath: string, +): Promise { + try { + const webpackConfig = await promises.readFile(webpackConfigPath, { + encoding: "utf-8", + }); + + const prettyConfigFilename = chalk.cyan(path.basename(webpackConfigPath)); + + // no idea why recast returns any here, this is dumb :/ + const program = recast.parse(webpackConfig.toString()).program as t.Program; + + if (!(await shouldModifyWebpackConfig(program, prettyConfigFilename))) { + // Sentry tag is set in shouldModifyWebpackConfig + return false; + } + + const exportStmt = getCjsModuleExports(program); + if (!exportStmt) { + // We only care about CJS at the moment since it's probably the most widely used format for webpack configs. + debug(`Could not find module.exports = {...} in ${webpackConfigPath}.`); + Sentry.setTag("ast-mod-fail-reason", "config-object-not-found"); + return false; + } + + const configObject = getWebpackConfigObject(exportStmt, program); + + if (!configObject) { + debug(`Couldn't find config object in ${webpackConfigPath}`); + Sentry.setTag("ast-mod-fail-reason", "config-object-not-found"); + return false; + } + + const enabledSourcemaps = enableSourcemapsGeneration(configObject); + + if (enabledSourcemaps) { + clack.log.success( + `Enabled source map generation in ${prettyConfigFilename}.`, + ); + } else { + clack.log.warn( + `Couldn't enable source maps generation in ${prettyConfigFilename} Please follow the instructions below.`, + ); + Sentry.setTag("ast-mod-fail-reason", "insertion-fail"); + return false; + } + + const addedPlugin = addSentryWebpackPlugin( + program, + configObject, + options, + importPath, + ); + if (addedPlugin) { + clack.log.success( + `Added Sentry webpack plugin to ${prettyConfigFilename}.`, + ); + } else { + clack.log.warn( + `Couldn't add Sentry webpack plugin to ${prettyConfigFilename}. Please follow the instructions below.`, + ); + Sentry.setTag("ast-mod-fail-reason", "insertion-fail"); + return false; + } + + const code = recast.print(program).code; + await promises.writeFile(webpackConfigPath, code); + + return true; + } catch (e) { + Sentry.setTag("ast-mod-fail-reason", "insertion-fail"); + debug(e); + return false; + } +} + +async function shouldModifyWebpackConfig( + program: t.Program, + prettyConfigFilename: string, +) { + if (hasSentryContent(program)) { + const shouldContinue = await abortIfCancelled( + clack.select({ + message: `Seems like ${prettyConfigFilename} already contains Sentry-related code. Should the wizard modify it anyway?`, + options: [ + { + label: "Yes, add the Sentry Webpack plugin", + value: true, + }, + { + label: "No, show me instructions to manually add the plugin", + value: false, + }, + ], + initialValue: true, + }), + ); + + if (!shouldContinue) { + Sentry.setTag("ast-mod-fail-reason", "has-sentry-content"); + return false; + } + } + + return true; +} + +function addSentryWebpackPlugin( + program: t.Program, + configObj: t.ObjectExpression, + options: SourceMapUploadToolConfigurationOptions, + importPath: string, +) { + const b = addSentryWebpackPluginImport(program, importPath); + + const sentryPluginCall = b.callExpression( + b.identifier("sentryWebpackPlugin"), + [ + b.objectExpression([ + b.objectProperty( + b.identifier("authToken"), + b.identifier("process.env.SENTRY_AUTH_TOKEN"), + ), + b.objectProperty(b.identifier("org"), b.stringLiteral(options.orgSlug)), + b.objectProperty( + b.identifier("project"), + b.stringLiteral(options.projectSlug), + ), + ...(options.selfHosted + ? [ + b.objectProperty( + b.identifier("url"), + b.stringLiteral(options.url), + ), + ] + : []), + ]), + ], + ); + + const pluginsProp = configObj.properties.find( + (p): p is t.Property => + p.type === "Property" && + p.key.type === "Identifier" && + p.key.name === "plugins", + ); + + if (pluginsProp) { + if (pluginsProp.value.type === "ArrayExpression") { + pluginsProp.value.elements.push(sentryPluginCall); + } else { + pluginsProp.value = b.arrayExpression([sentryPluginCall]); + } + return true; + } + + configObj.properties.push( + b.objectProperty( + b.identifier("plugins"), + b.arrayExpression([sentryPluginCall]), + ), + ); + + return true; +} + +function addSentryWebpackPluginImport(program: t.Program, importPath: string) { + const b = recast.types.builders; + + const sentryPluginRequireStmt = b.variableDeclaration("const", [ + b.variableDeclarator( + b.objectPattern([ + b.objectProperty.from({ + key: b.identifier("sentryWebpackPlugin"), + value: b.identifier("sentryWebpackPlugin"), + shorthand: true, + }), + ]), + b.callExpression(b.identifier("require"), [b.stringLiteral(importPath)]), + ), + ]); + + program.body.unshift(sentryPluginRequireStmt); + return b; +} + +function enableSourcemapsGeneration(configObj: t.ObjectExpression): boolean { + const b = recast.types.builders; + + const devtoolProp = configObj.properties.find( + (p): p is t.Property => + p.type === "Property" && + p.key.type === "Identifier" && + p.key.name === "devtool", + ); + + if (devtoolProp) { + // devtool can have quite a lot of source maps values. + // see: https://webpack.js.org/configuration/devtool/#devtool + // For Sentry to work best, we should set it to "source-map" or "hidden-source-map" + // Heuristic: + // - all values that contain "hidden" will be set to "hidden-source-map" + // - all other values will be set to "source-map" + if ( + (devtoolProp.value.type === "Literal" || + devtoolProp.value.type === "StringLiteral") && + devtoolProp.value.value?.toString().startsWith("hidden-") + ) { + devtoolProp.value = b.stringLiteral("hidden-source-map"); + } else { + devtoolProp.value = b.stringLiteral("source-map"); + } + return true; + } + + configObj.properties.push( + b.objectProperty(b.identifier("devtool"), b.stringLiteral("source-map")), + ); + + return true; +} + +function getWebpackConfigObject( + moduleExports: t.AssignmentExpression, + program: t.Program, +): t.ObjectExpression | undefined { + const rhs = moduleExports.right; + if (rhs.type === "ObjectExpression") { + return rhs; + } + if (rhs.type === "Identifier") { + const configId = rhs.name; + + const configDeclaration = program.body.find( + (s): s is t.VariableDeclaration => + s.type === "VariableDeclaration" && + !!s.declarations.find( + (d) => + d.type === "VariableDeclarator" && + d.id.type === "Identifier" && + d.id.name === configId, + ), + ); + + const declarator = configDeclaration?.declarations.find( + (d): d is t.VariableDeclarator => + d.type === "VariableDeclarator" && + d.id.type === "Identifier" && + d.id.name === configId, + ); + + return declarator?.init?.type === "ObjectExpression" + ? declarator.init + : undefined; + } + + return undefined; +} + +function getCjsModuleExports( + program: t.Program, +): t.AssignmentExpression | undefined { + const moduleExports = program.body.find( + (s): s is t.ExpressionStatement => + s.type === "ExpressionStatement" && + s.expression.type === "AssignmentExpression" && + s.expression.left.type === "MemberExpression" && + s.expression.left.object.type === "Identifier" && + s.expression.left.object.name === "module" && + s.expression.left.property.type === "Identifier" && + s.expression.left.property.name === "exports", + ); + return moduleExports?.expression as t.AssignmentExpression; +} diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/wrangler.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/wrangler.ts new file mode 100644 index 0000000000..8cd439ebd6 --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/wrangler.ts @@ -0,0 +1,499 @@ +/** + * Source maps setup for Cloudflare Wrangler: make `wrangler deploy` keep + * its output and source maps, tag the worker with a release, and upload the + * output with the `sentry` CLI after each deploy. + * + * sentry-wizard installed `@sentry/cli@^2` and called `sentry-cli releases + * propose-version/new` and `sentry-cli sourcemaps upload`. These are the v4 + * `sentry release` and `sentry sourcemap` commands. + */ + +import chalk from "chalk"; +import { promises } from "node:fs"; +import path from "node:path"; + +import { + abort, + abortIfCancelled, + addSentryCliConfig, + getPackageDotJson, + getPackageManager, + installPackage, + showCopyPasteInstructions, +} from "../../utils/clack/index.js"; +import { clack } from "../../utils/clack/prompts.js"; +import { hasPackageInstalled } from "../../utils/package-json.js"; +import { NPM } from "../../utils/package-manager.js"; +import { SENTRY_CLI_PACKAGE, SENTRY_CLI_PACKAGE_RANGE } from "./sentry-cli.js"; +import type { SourceMapUploadToolConfigurationOptions } from "./types.js"; + +const SENTRY_NPM_SCRIPT_NAME = "sentry:sourcemaps"; + +/** + * only exported for testing + */ +export const DIST_DIR = path.join(".", "dist"); + +export async function configureWrangler( + options: SourceMapUploadToolConfigurationOptions, +) { + clack.note( + chalk.whiteBright( + `Configuring source maps upload with Cloudflare Wrangler requires the wizard to: +- Modify your deploy command to access source maps +- Set the SENTRY_RELEASE env var to identify source maps + +Note: This setup may need additional configuration. +We recommend using Vite to build your worker instead, for an easier and more reliable setup. + +Learn more about CloudFlare's Vite setup here: +${chalk.underline( + chalk.cyan( + "https://developers.cloudflare.com/workers/vite-plugin/get-started/", + ), +)} + +You can switch to Vite and re-run this wizard later. +Otherwise, let's proceed with the Wrangler setup.`, + ), + "Before we get started", + ); + + const proceed = await abortIfCancelled( + clack.confirm({ + message: "Do you want to proceed with the Wrangler setup?", + }), + ); + + if (!proceed) { + await abort( + "Got it! You can switch to Vite and re-run this wizard later.", + 0, + ); + return; + } + + await installPackage({ + packageName: SENTRY_CLI_PACKAGE_RANGE, + packageNameDisplayLabel: SENTRY_CLI_PACKAGE, + alreadyInstalled: hasPackageInstalled( + SENTRY_CLI_PACKAGE, + await getPackageDotJson(), + ), + devDependency: true, + }); + + if (!(await askContinueIfHasSentrySourcemapsScript())) { + return; + } + + const deployCommand = await getDeployCommand(); + if (!deployCommand) { + return; + } + + const outDir = await getWranglerOutDir(deployCommand); + + await createAndAddSentrySourcemapsScript({ ...options, outDir }); + + await writePostDeployCommand(deployCommand); + + await modifyDeployCommand(deployCommand, outDir); + + await addSentryCliConfig({ authToken: options.authToken }); +} + +async function createAndAddSentrySourcemapsScript( + options: SourceMapUploadToolConfigurationOptions & { outDir: string }, +) { + const pkgJson = await getPackageDotJson(); + pkgJson.scripts = pkgJson.scripts ?? {}; + pkgJson.scripts[SENTRY_NPM_SCRIPT_NAME] = getSentryCliCommand(options); + + await promises.writeFile( + path.join(process.cwd(), "package.json"), + JSON.stringify(pkgJson, null, 2), + ); + + clack.log.success( + `Added a ${chalk.cyan(SENTRY_NPM_SCRIPT_NAME)} script to your ${chalk.cyan( + "package.json", + )}.`, + ); +} + +/** + * Prints the proposed release version. `sentry release propose-version` + * prints a hint after the version when its output is piped, so only the + * first line is kept. + */ +// oxlint-disable-next-line sentry-cli/no-hardcoded-sentry-command -- runs the project's installed `sentry` package from its package.json scripts, not a hint +const PROPOSE_VERSION = "$(sentry release propose-version | head -n 1)"; + +/** + * The `sentry:sourcemaps` script: create the release and upload the deploy + * output for it. The output is uploaded as deployed (`--no-rewrite`): the + * worker was already deployed without debug IDs, so the files are matched + * by release and URL, as with sentry-cli. + * + * only exported for testing + */ +export function getSentryCliCommand( + options: SourceMapUploadToolConfigurationOptions & { outDir: string }, +): string { + // `SENTRY_URL` replaced the `--url` flag of sentry-cli + const urlEnv = options.selfHosted + ? `SENTRY_URL=${quoteShellArg(options.url)} ` + : ""; + const orgAndProjectArgs = `--org=${quoteShellArg( + options.orgSlug, + )} --project=${quoteShellArg(options.projectSlug)}`; + + return [ + `_SENTRY_RELEASE=${PROPOSE_VERSION}`, + `${urlEnv}sentry release create "$_SENTRY_RELEASE" ${orgAndProjectArgs}`, + `${urlEnv}sentry sourcemap upload ${orgAndProjectArgs} --release="$_SENTRY_RELEASE" --no-rewrite ${quoteShellArg( + options.outDir, + )}`, + ].join(" && "); +} + +// Package scripts run through a shell. Quote values as literal arguments, +// including embedded single quotes, before inserting them into shell source. +function quoteShellArg(value: string): string { + return `'${value.replace(/'/g, "'\\''")}'`; +} + +async function askContinueIfHasSentrySourcemapsScript(): Promise { + const pkgJson = await getPackageDotJson(); + + pkgJson.scripts = pkgJson.scripts ?? {}; + + if (pkgJson.scripts[SENTRY_NPM_SCRIPT_NAME]) { + clack.log.warn( + `The ${chalk.cyan( + SENTRY_NPM_SCRIPT_NAME, + )} script already exists in your ${chalk.cyan("package.json")}. +This likely means that you already ran this wizard once. +If things don't work yet, try overwriting the script and continue with the wizard.`, + ); + + const overwrite = await abortIfCancelled( + clack.select({ + message: "Do you want to overwrite it?", + options: [ + { label: "Yes", value: true, hint: "Overwrite the existing script" }, + { label: "No", value: false, hint: "This will exit the wizard" }, + ], + }), + ); + + if (!overwrite) { + return false; + } + } + + return true; +} + +async function getDeployCommand(): Promise { + const pkgJson = await getPackageDotJson(); + const scripts = pkgJson.scripts ?? {}; + + let deployCommand = Object.keys(scripts).find((key) => + /wrangler\s+deploy/.test(scripts[key] ?? ""), + ); + + const packageManager = await getPackageManager(NPM); + const isDeployCommand = + !!deployCommand && + (await abortIfCancelled( + clack.confirm({ + message: `Is ${chalk.cyan( + `${packageManager.runScriptCommand} ${deployCommand}`, + )} your build and deploy command?`, + }), + )); + + if (Object.keys(scripts).length && (!deployCommand || !isDeployCommand)) { + deployCommand = await abortIfCancelled( + clack.select({ + message: `Which ${packageManager.name} command in your ${chalk.cyan( + "package.json", + )} builds your worker and deploys it?`, + options: [ + ...Object.keys(scripts).map((script) => ({ + label: script, + value: script, + })), + { label: "None of the above", value: "none" }, + ], + }), + ); + } + + if (!deployCommand || deployCommand === "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 undefined; + } + + return deployCommand; +} + +async function writePostDeployCommand(deployCommand: string): Promise { + const pkgJson = await getPackageDotJson(); + const packageManager = await getPackageManager(NPM); + pkgJson.scripts = pkgJson.scripts ?? {}; + pkgJson.scripts[`post${deployCommand}`] = + `${packageManager.runScriptCommand} ${SENTRY_NPM_SCRIPT_NAME}`; + + await promises.writeFile( + path.join(process.cwd(), "package.json"), + JSON.stringify(pkgJson, null, 2), + ); + + clack.log.success( + `Added a ${chalk.cyan(`post${deployCommand}`)} script to your ${chalk.cyan( + "package.json", + )}.`, + ); +} + +async function modifyDeployCommand( + deployCommand: string, + outDir: string, +): Promise { + const pkgJson = await getPackageDotJson(); + pkgJson.scripts = pkgJson.scripts ?? {}; + const oldDeployCommand = pkgJson.scripts[deployCommand]; + + if (!oldDeployCommand) { + clack.log.warn( + `The ${chalk.cyan( + deployCommand, + )} script doesn't seem to be part of your package.json scripts anymore. Cannot modify it. Please modify it manually:`, + ); + + await showCopyPasteInstructions({ + codeSnippet: `wrangler deploy --outdir ${quoteShellArg( + outDir, + )} --var SENTRY_RELEASE:${PROPOSE_VERSION} --upload-source-maps`, + filename: "package.json", + }); + + return; + } + + const newDeployCommand = safeInsertArgsToWranglerDeployCommand( + oldDeployCommand, + outDir, + ); + + if (!newDeployCommand) { + clack.log.warn( + `The ${chalk.cyan( + deployCommand, + )} script doesn't seem to be a valid ${chalk.cyan( + "wrangler deploy", + )} command. Cannot modify it. Please modify it manually:`, + ); + + await showCopyPasteInstructions({ + codeSnippet: oldDeployCommand, + filename: "package.json", + }); + + return; + } + + pkgJson.scripts[deployCommand] = newDeployCommand; + + await promises.writeFile( + path.join(process.cwd(), "package.json"), + JSON.stringify(pkgJson, null, 2), + ); + + clack.log.success( + `Modified your ${chalk.cyan( + deployCommand, + )} script to enable uploading source maps.`, + ); +} + +/** + * Takes care of inserting the necessary arguments into the deploy command. + * Ensures that existing arguments and values are kept and that the + * wrangler deploy command is valid. + * + * only exported for testing + */ +export function safeInsertArgsToWranglerDeployCommand( + deployCommand: string, + outDir: string, +): string | undefined { + // split deployCommand into individual bash commands (potentially separated by &&, ||, >> etc.) + const originalWranglerDeployCommand = getWranglerDeployCommand(deployCommand); + + if (!originalWranglerDeployCommand) { + return undefined; + } + + const existingArgs = originalWranglerDeployCommand + .split(" ") + .map((arg) => arg.trim()) + .filter(Boolean); + + const newArgs: string[] = []; + + if (!hasArg(existingArgs, "--outdir")) { + newArgs.push("--outdir", quoteShellArg(outDir)); + } + + // Adding --upload-source-maps saves us from having to + // modify the `wrangler.toml` or `wrangler.jsonc` files. + // Not ideal because this forces source maps to be uploaded + // but we'll live with it for now. + if (!hasArg(existingArgs, "--upload-source-maps")) { + newArgs.push("--upload-source-maps"); + } + + // This is how we inject the SENTRY_RELEASE variable, + // which is picked up by the CloudFlare SDK. + // multiple --var arguments are allowed, so no need to check for existing --var arguments. + newArgs.push("--var", `SENTRY_RELEASE:${PROPOSE_VERSION}`); + + return deployCommand + .replace( + originalWranglerDeployCommand, + `${originalWranglerDeployCommand} ${newArgs.join(" ")} `, + ) + .trim(); +} + +/** + * Look up an already specified --outdir argument and return it if found. + * Otherwise, we defined `dist` as the default outdir. + */ +async function getWranglerOutDir(deployScript: string): Promise { + const pkgJson = await getPackageDotJson(); + const scripts = pkgJson.scripts ?? {}; + const deployCommand = scripts[deployScript]; + + if (!deployCommand) { + return DIST_DIR; + } + + return findOutDir(deployCommand); +} + +/** + * only exported for testing + */ +export function findOutDir(deployCommand: string): string { + const args = getWranglerDeployCommand(deployCommand) + ?.split(" ") + .map((arg) => arg.trim()); + + if (!args) { + return DIST_DIR; + } + + const outDirArgIndex = args.findIndex((arg) => arg.startsWith("--outdir")); + const outDirArg = args[outDirArgIndex]; + if (outDirArg === undefined) { + return DIST_DIR; + } + + if (outDirArg.startsWith("--outdir=")) { + return outDirArg.slice("--outdir=".length).trim().replace(/['"]/g, ""); + } + + const maybeOutDir = args[outDirArgIndex + 1]; + + if (maybeOutDir && !maybeOutDir.startsWith("--")) { + return maybeOutDir.replace(/['"]/g, ""); + } + + return DIST_DIR; +} + +/** Whether `args` sets the `--name` flag, as `--name`, `--name value`, or `--name=value`. */ +function hasArg(args: string[], name: string): boolean { + return args.some((arg) => arg === name || arg.startsWith(`${name}=`)); +} + +/** Shell operators that separate the commands of a script. */ +const COMMAND_SEPARATORS = ["&&", "||", ">>", ">", "<", "|", ";"]; + +/** + * Split a package script into its individual commands at the operators in + * {@link COMMAND_SEPARATORS}. Operators inside quotes or a `$(…)` command + * substitution (such as the `| head -n 1` of the release version this + * wizard adds) don't split. The commands are substrings of `script`. + */ +function splitShellCommands(script: string): string[] { + const commands: string[] = []; + let start = 0; + let depth = 0; + let quote: string | undefined; + let i = 0; + while (i < script.length) { + const char = script.charAt(i); + if (quote) { + if (char === quote) { + quote = undefined; + } + i += 1; + continue; + } + if (char === "'" || char === '"') { + quote = char; + i += 1; + continue; + } + if (char === "$" && script.charAt(i + 1) === "(") { + depth += 1; + i += 2; + continue; + } + if (char === ")" && depth > 0) { + depth -= 1; + i += 1; + continue; + } + const separator = + depth === 0 + ? COMMAND_SEPARATORS.find((op) => script.startsWith(op, i)) + : undefined; + if (separator) { + commands.push(script.slice(start, i)); + i += separator.length; + start = i; + continue; + } + i += 1; + } + commands.push(script.slice(start)); + return commands; +} + +/** + * Exported for testing + */ +export function getWranglerDeployCommand( + deployCommand: string, +): string | undefined { + return splitShellCommands(deployCommand).find((cmd) => { + const argv = cmd + .split(" ") + .map((arg) => arg.trim()) + .filter(Boolean); + + return argv[0] === "wrangler" && argv.includes("deploy"); + }); +} diff --git a/packages/cli/src/lib/wizard/sourcemaps/utils/bundler-plugin.ts b/packages/cli/src/lib/wizard/sourcemaps/utils/bundler-plugin.ts new file mode 100644 index 0000000000..14d8ae73d0 --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/utils/bundler-plugin.ts @@ -0,0 +1,118 @@ +/** + * Make the Sentry bundler plugin for a bundler available in the project, + * from an installed SDK that ships it or from `@sentry/bundler-plugins`. + */ + +import { minVersion, satisfies } from "semver"; + +import { Sentry } from "../../telemetry.js"; +import { + getPackageDotJson, + installPackage, + printSdkV11MigrationGuideIfOutdated, +} from "../../utils/clack/index.js"; +import { debug } from "../../utils/debug.js"; +import { + getPackageVersion, + hasPackageInstalled, +} from "../../utils/package-json.js"; + +export type Bundler = "vite" | "webpack" | "rollup" | "esbuild"; + +const BUNDLER_PLUGINS_PACKAGE = "@sentry/bundler-plugins"; + +type SdkWithBundlerPlugins = { + name: string; + bundlers: Bundler[]; + // First SDK version that exports the plugin subpaths. + minVersion: string; +}; + +// SDKs that depend on @sentry/node come first so that we pick the +// top-level SDK when both are listed in package.json. +const SDKS_WITH_BUNDLER_PLUGINS: SdkWithBundlerPlugins[] = [ + { name: "@sentry/nestjs", bundlers: ["webpack"], minVersion: "11.10.0" }, + { + name: "@sentry/aws-serverless", + bundlers: ["esbuild"], + minVersion: "11.10.0", + }, + { + name: "@sentry/node", + bundlers: ["vite", "webpack", "rollup", "esbuild"], + minVersion: "11.0.0", + }, +]; + +/** + * Makes sure the Sentry bundler plugin for @param bundler is available in + * the user's project and returns the module path to import it from. + * + * If an installed SDK ships the plugin, the SDK is updated to v11 and the + * plugin is imported from the SDK. Otherwise, or if the user declines the + * SDK update, `@sentry/bundler-plugins` is installed as a dev dependency. + */ +export async function ensureBundlerPlugin(bundler: Bundler): Promise { + const packageJson = await getPackageDotJson(); + + const sdk = SDKS_WITH_BUNDLER_PLUGINS.find( + (candidate) => + candidate.bundlers.includes(bundler) && + hasPackageInstalled(candidate.name, packageJson), + ); + + if (sdk) { + printSdkV11MigrationGuideIfOutdated(sdk.name, packageJson); + + await installPackage({ + packageName: `${sdk.name}@^11`, + packageNameDisplayLabel: sdk.name, + alreadyInstalled: true, + }); + + // The user may have declined the update, so re-read package.json to + // learn which version is actually installed. + const installedRange = getPackageVersion( + sdk.name, + await getPackageDotJson(), + ); + + if (sdkShipsBundlerPlugins(installedRange, sdk.minVersion)) { + Sentry.setTag("bundler-plugin-source", "sdk"); + return `${sdk.name}/${bundler}`; + } + } + + await installPackage({ + packageName: `${BUNDLER_PLUGINS_PACKAGE}@^11`, + packageNameDisplayLabel: BUNDLER_PLUGINS_PACKAGE, + alreadyInstalled: hasPackageInstalled(BUNDLER_PLUGINS_PACKAGE, packageJson), + devDependency: true, + }); + + Sentry.setTag("bundler-plugin-source", "bundler-plugins"); + return `${BUNDLER_PLUGINS_PACKAGE}/${bundler}`; +} + +function sdkShipsBundlerPlugins( + installedRange: string | undefined, + requiredVersion: string, +): boolean { + if (!installedRange) { + return false; + } + + try { + const installedVersion = minVersion(installedRange)?.version; + return ( + !!installedVersion && + satisfies(installedVersion, `>=${requiredVersion}`, { + includePrerelease: true, + }) + ); + } catch (error) { + // An unparseable range can't be checked; fall back to the plugins package + debug(error); + return false; + } +} diff --git a/packages/cli/src/lib/wizard/sourcemaps/utils/detect-tool.ts b/packages/cli/src/lib/wizard/sourcemaps/utils/detect-tool.ts new file mode 100644 index 0000000000..7c0657ab38 --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/utils/detect-tool.ts @@ -0,0 +1,58 @@ +/** + * Detect the build tool of a project from its `package.json`, to preselect + * it in the source maps wizard. + */ + +import { getPackageDotJson } from "../../utils/clack/index.js"; +import { findInstalledPackageFromList } from "../../utils/package-json.js"; + +/** + * The tools the source maps wizard can configure. `sentry-cli` is the + * generic flow that uploads with the `sentry` CLI (kept as the id so the + * `selected-tool` telemetry tag stays comparable). + */ +export type SupportedTools = + | "webpack" + | "vite" + | "rollup" + | "esbuild" + | "tsc" + | "sentry-cli" + | "create-react-app" + | "angular" + | "wrangler" + | "no-tool"; + +/** + * Package names pointing to the tool they indicate. The order matters: the + * most specific tool comes first. For instance, webpack comes before tsc + * because webpack projects often depend on `typescript` too. + */ +const TOOL_PACKAGE_MAP: Record = { + "@angular/core": "angular", + "create-react-app": "create-react-app", + wrangler: "wrangler", + webpack: "webpack", + vite: "vite", + esbuild: "esbuild", + rollup: "rollup", + typescript: "tsc", +}; + +/** + * The tool of the first package in {@link TOOL_PACKAGE_MAP} the project + * depends on, or the generic `sentry-cli` flow. + */ +export async function detectUsedTool(): Promise { + const packageJson = await getPackageDotJson(); + + const foundToolPackage = findInstalledPackageFromList( + Object.keys(TOOL_PACKAGE_MAP), + packageJson, + ); + + return ( + (foundToolPackage && TOOL_PACKAGE_MAP[foundToolPackage.name]) || + "sentry-cli" + ); +} diff --git a/packages/cli/src/lib/wizard/sourcemaps/utils/other-wizards.ts b/packages/cli/src/lib/wizard/sourcemaps/utils/other-wizards.ts new file mode 100644 index 0000000000..59d39e082b --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/utils/other-wizards.ts @@ -0,0 +1,169 @@ +/** + * Point users of a framework that has its own wizard (SvelteKit, React + * Native) to that wizard instead of the generic source maps one. + */ + +import chalk from "chalk"; + +import { Sentry } from "../../telemetry.js"; +import { + abort, + abortIfCancelled, + getPackageDotJson, +} from "../../utils/clack/index.js"; +import { clack } from "../../utils/clack/prompts.js"; +import { + findInstalledPackageFromList, + hasPackageInstalled, +} from "../../utils/package-json.js"; +import type { WizardOptions } from "../../utils/types.js"; + +type WizardFunction = (options: WizardOptions) => Promise; + +type FrameworkInfo = { + frameworkName: string; + frameworkPackage: string; + troubleshootingDocsLink: string; + sourcemapsDocsLink: string; + wizard: WizardFunction; +}; + +/** + * The `sentry wizard -i ` flow. `run.ts` is imported on demand + * because it imports this flow. + */ +function runOtherWizard( + integration: "sveltekit" | "reactNative", +): WizardFunction { + return async (options) => { + const { runWizard } = await import("../../run.js"); + await runWizard({ integration, debug: false, wizardOptions: options }); + }; +} + +const sdkMap: Record = { + "@sentry/sveltekit": { + frameworkName: "SvelteKit", + frameworkPackage: "@sveltejs/kit", + sourcemapsDocsLink: + "https://docs.sentry.io/platforms/javascript/guides/sveltekit/manual-setup/#configure-source-maps-upload", + troubleshootingDocsLink: + "https://docs.sentry.io/platforms/javascript/guides/sveltekit/sourcemaps/troubleshooting_js/", + wizard: runOtherWizard("sveltekit"), + }, + "@sentry/react-native": { + frameworkName: "React Native", + frameworkPackage: "react-native", + sourcemapsDocsLink: + "https://docs.sentry.io/platforms/react-native/sourcemaps/", + troubleshootingDocsLink: + "https://docs.sentry.io/platforms/react-native/troubleshooting/#source-maps", + wizard: runOtherWizard("reactNative"), + }, +}; + +/** + * When the project uses a framework with its own wizard, ask whether to run + * that wizard instead, and return it if so. + */ +export async function checkIfMoreSuitableWizardExistsAndAskForRedirect(): Promise< + WizardFunction | undefined +> { + const framework = await checkIfMoreSuitableWizardExists(); + + if (!framework) { + return undefined; + } + + return await askForRedirect(framework.sdkName, framework.info); +} + +async function checkIfMoreSuitableWizardExists(): Promise< + { sdkName: string; info: FrameworkInfo } | undefined +> { + Sentry.setTag("using-wrong-wizard", false); + + const packageJson = await getPackageDotJson(); + + const installedSdkPackage = findInstalledPackageFromList( + Object.keys(sdkMap), + packageJson, + ); + + const info = installedSdkPackage && sdkMap[installedSdkPackage.name]; + if (!installedSdkPackage || !info) { + return undefined; + } + + if (!hasPackageInstalled(info.frameworkPackage, packageJson)) { + // The user has installed the SDK but not the framework. + // Maybe it's a false positive and the user is using a different framework. + // Let's not redirect them to the framework wizard in that case. + return undefined; + } + + Sentry.setTag("using-wrong-wizard", true); + + return { sdkName: installedSdkPackage.name, info }; +} + +async function askForRedirect( + sdkName: string, + { + frameworkName, + sourcemapsDocsLink, + troubleshootingDocsLink, + wizard, + }: FrameworkInfo, +): Promise { + clack.log.warn( + `${chalk.yellow( + `It seems like you're using this wizard in a ${frameworkName} project.`, + )} + +We recommend using our dedicated ${frameworkName} wizard instead of this wizard. +The ${frameworkName} wizard will set up our ${sdkName} SDK and also configure uploading source maps for you. + +If you already tried the ${frameworkName} wizard and it didn't work for you, check out the following guides: + +Manual source maps configuration for ${frameworkName}: +${sourcemapsDocsLink} + +Troubleshooting Source Maps: +${troubleshootingDocsLink} +`, + ); + + const nextStep = await abortIfCancelled( + clack.select<"redirect" | "continue" | "stop">({ + message: `Do you want to run the ${frameworkName} wizard now?`, + options: [ + { + label: "Yes", + value: "redirect", + hint: chalk.green("Recommended"), + }, + { + label: "No, continue with this wizard", + value: "continue", + }, + { + label: "No, I'll check out the guides ", + value: "stop", + hint: "Exit this wizard", + }, + ], + }), + ); + + Sentry.setTag("wrong-wizard-decision", nextStep); + + switch (nextStep) { + case "redirect": + return wizard; + case "stop": + return await abort("Exiting Wizard", 0); + default: + return undefined; + } +} diff --git a/packages/cli/src/lib/wizard/sourcemaps/utils/sdk-version.ts b/packages/cli/src/lib/wizard/sourcemaps/utils/sdk-version.ts new file mode 100644 index 0000000000..84ecbda36c --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/utils/sdk-version.ts @@ -0,0 +1,282 @@ +/** + * Check that the project's Sentry SDK is new enough for debug ID based source + * maps (7.47.0), and help the user update it if not. + */ + +import chalk from "chalk"; +import { minVersion, satisfies } from "semver"; + +import { Sentry } from "../../telemetry.js"; +import { + abortIfCancelled, + getPackageDotJson, + installPackage, +} from "../../utils/clack/index.js"; +import { clack } from "../../utils/clack/prompts.js"; +import { debug } from "../../utils/debug.js"; +import { findInstalledPackageFromList } from "../../utils/package-json.js"; + +const MINIMUM_DEBUG_ID_SDK_VERSION = "7.47.0"; + +// This array is orderd by the SDKs we want to check for first. +// The reason is that some SDKs depend on others and some users might +// have added the dependencies to their package.json. We want to make sure +// that we actually detect the "top-level" SDK first. +const SENTRY_SDK_PACKAGE_NAMES = [ + // SDKs using other framework SDKs need to be checked first + "@sentry/astro", + "@sentry/gatsby", + "@sentry/nextjs", + "@sentry/nuxt", + "@sentry/react-router", + "@sentry/remix", + "@sentry/solidstart", + "@sentry/sveltekit", + "@sentry/tanstackstart-react", + + // Framework SDKs + "@sentry/angular", + "@sentry/angular-ivy", + "@sentry/aws-serverless", + "@sentry/bun", + "@sentry/ember", + "@sentry/google-cloud-serverless", + "@sentry/nestjs", + "@sentry/react", + "@sentry/solid", + "@sentry/svelte", + "@sentry/vue", + "@sentry/serverless", + + // Base SDKs + "@sentry/browser", + "@sentry/cloudflare", + "@sentry/node", + "@sentry/deno", +]; + +/** + * Check for a minimum SDK version and prompt the user to upgrade if necessary. + * We distinguish between 4 cases here: + * + * 1. Users didn't install any SDK yet + * -> We tell them to install an SDK and then continue with the wizard + * 2. Users installed an SDK in the range >=7.47.0 + * -> All good, no need to do anything! + * 3. Users installed an SDK in the range >=7.0.0 <= 7.46.0 + * -> We ask if they want to auto-update to the latest version + * 4. Users installed an SDK in the range <7.x + * -> We tell users to manually upgrade (migrate between majors) + */ +export async function ensureMinimumSdkVersionIsInstalled(): Promise { + const installedSdkPackage = findInstalledPackageFromList( + SENTRY_SDK_PACKAGE_NAMES, + await getPackageDotJson(), + ); + + // Case 1: + if (!installedSdkPackage) { + return await handleNoSdkInstalled(); + } + + const { name: installedSdkName, version: installedSdkVersionOrRange } = + installedSdkPackage; + + Sentry.setTag("installed-sdk", installedSdkName); + + const minInstalledVersion = getMinInstalledVersion( + installedSdkVersionOrRange, + installedSdkName, + ); + + if (!minInstalledVersion) { + // This is handled in the getMinInstalledVersion function + return; + } + + const hasDebugIdCompatibleSdkVersion = satisfies( + minInstalledVersion, + `>=${MINIMUM_DEBUG_ID_SDK_VERSION}`, + { includePrerelease: true }, + ); + + // Case 2: + if (hasDebugIdCompatibleSdkVersion) { + Sentry.setTag("initial-sdk-version", ">=7.47.0"); + return; + } + + const hasV7SdkVersion = satisfies(minInstalledVersion, ">=7.0.0", { + includePrerelease: true, + }); + + clack.log.warn( + `${chalk.yellowBright( + `It seems like you're using an outdated version (${installedSdkVersionOrRange}) of the ${chalk.bold( + installedSdkName, + )} SDK.`, + )} +Uploading source maps is easiest with an SDK from version ${chalk.bold( + MINIMUM_DEBUG_ID_SDK_VERSION, + )} or newer. +`, + ); + + // Case 3: + if (hasV7SdkVersion) { + await handleAutoUpdateSdk(installedSdkName); + return; + } + + // Case 4: + await handleManuallyUpdateSdk(minInstalledVersion); +} + +async function handleManuallyUpdateSdk( + minInstalledVersion: string, +): Promise { + Sentry.setTag( + "initial-sdk-version", + satisfies(minInstalledVersion, ">=6.0.0", { includePrerelease: true }) + ? "6.x" + : "<6.0.0", + ); + + clack.log + .info(`When upgrading from a version older than 7.0.0, make sure to follow the migration guide: +https://github.com/getsentry/sentry-javascript/blob/develop/MIGRATION.md#upgrading-from-6x-to-7x +`); + + const didUpdate = await abortIfCancelled( + clack.select({ + message: "Did you update your SDK to the latest version?", + options: [ + { + label: "Yes!", + value: true, + }, + { + label: "No, I'll do it later...", + value: false, + hint: chalk.yellow( + `Remember to update your SDK to at least ${MINIMUM_DEBUG_ID_SDK_VERSION}.`, + ), + }, + ], + initialValue: true, + }), + ); + + Sentry.setTag( + "resolved-sdk-status", + didUpdate ? "updated-manually" : "update-later", + ); +} + +async function handleAutoUpdateSdk(packageName: string): Promise { + Sentry.setTag("initial-sdk-version", ">=7.0.0 <7.47.0"); + + const shouldUpdate = await abortIfCancelled( + clack.select({ + message: + "Do you want to automatically update your SDK to the latest version?", + options: [ + { + label: "Yes!", + value: true, + hint: chalk.green("Recommended"), + }, + { + label: "No, I'll do it later...", + value: false, + hint: chalk.yellow( + `Remember to update your SDK to at least ${MINIMUM_DEBUG_ID_SDK_VERSION}.`, + ), + }, + ], + initialValue: true, + }), + ); + + if (shouldUpdate) { + await installPackage({ + packageName, + alreadyInstalled: true, + askBeforeUpdating: false, // we already did this above + }); + } + + Sentry.setTag( + "resolved-sdk-status", + shouldUpdate ? "updated-automatically" : "update-later", + ); +} + +async function handleNoSdkInstalled(): Promise { + Sentry.setTag("initial-sdk-version", "none"); + Sentry.setTag("installed-sdk", "none"); + + clack.log.warn( + `${chalk.yellowBright( + `It seems like you didn't yet install a Sentry SDK in your project.`, + )} +We recommend setting up the SDK before continuing with the source maps wizard. + +${chalk.dim(`Take a look at our docs to get started: +https://docs.sentry.io/`)}`, + ); + + const installedSDK = await abortIfCancelled( + clack.select({ + message: "Did you set up your Sentry SDK?", + options: [ + { label: "Yes, continue!", value: true }, + { + label: "I'll do it later...", + value: false, + hint: chalk.yellow( + "You need to set up an SDK before you can use Sentry", + ), + }, + ], + initialValue: true, + }), + ); + + Sentry.setTag( + "resolved-sdk-status", + installedSDK ? "installed-manually" : "install-later", + ); +} + +function getMinInstalledVersion( + installedSdkVersionOrRange: string, + installedSdkName: string, +): string | undefined { + try { + // If `minVersion` is unable to parse the version it will throw an error + // However, it will also return `null` if the parameter is undefined, which + // we explicitly checked before but the typing doesn't know that. + const minInstalledVersion = minVersion(installedSdkVersionOrRange)?.version; + if (minInstalledVersion) { + return minInstalledVersion; + } + } catch (error) { + // An unparseable version is handled with the `null` case below + debug(error); + } + + Sentry.setTag("initial-sdk-version", "unknown"); + clack.log.warn( + `${chalk.yellow( + `Could not parse the version of your installed SDK ("${installedSdkName}": "${installedSdkVersionOrRange}")`, + )} + +Please make sure that your Sentry SDK is updated to version ${chalk.bold( + MINIMUM_DEBUG_ID_SDK_VERSION, + )} or newer. + `, + ); + + return undefined; +} diff --git a/packages/cli/src/lib/wizard/utils/abort-if-sportlight-not-supported.ts b/packages/cli/src/lib/wizard/utils/abort-if-sportlight-not-supported.ts new file mode 100644 index 0000000000..3f612e0f0b --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/abort-if-sportlight-not-supported.ts @@ -0,0 +1,19 @@ +/** + * Stop a wizard that has no Spotlight (`--spotlight`) mode yet. + */ + +import { abort } from "./clack/index.js"; +import { clack } from "./clack/prompts.js"; + +/** + * Aborts the wizard with a message that Spotlight mode is not yet supported + * for the given platform. + */ +export async function abortIfSpotlightNotSupported( + platform: string, +): Promise { + clack.log.warn(`Spotlight mode is not yet supported for ${platform}.`); + clack.log.info("Spotlight is currently only available for Next.js."); + + return await abort("Exiting wizard", 0); +} diff --git a/packages/cli/src/lib/wizard/utils/vendor/is-unicorn-supported.ts b/packages/cli/src/lib/wizard/utils/vendor/is-unicorn-supported.ts new file mode 100644 index 0000000000..311dfbcba7 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/vendor/is-unicorn-supported.ts @@ -0,0 +1,38 @@ +/** + * Whether the terminal can print Unicode symbols such as `→`. + * + * Vendored from + * https://github.com/sindresorhus/is-unicode-supported/blob/c80c691dde9e2fcfe3996810858c6672c8f35ad9/index.js#L3 + * + * MIT License + * + * Copyright (c) Sindre Sorhus (https://sindresorhus.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +import { getEnv } from "../../../env.js"; + +/** Whether the current terminal can render Unicode symbols. */ +export function isUnicodeSupported(): boolean { + const env = getEnv(); + if (process.platform !== "win32") { + return env["TERM"] !== "linux"; // Linux console (kernel) + } + + return ( + Boolean(env["CI"]) || + Boolean(env["WT_SESSION"]) || // Windows Terminal + Boolean(env["TERMINUS_SUBLIME"]) || // Terminus (<0.2.27) + env["ConEmuTask"] === "{cmd::Cmder}" || // ConEmu and cmder + env["TERM_PROGRAM"] === "Terminus-Sublime" || + env["TERM_PROGRAM"] === "vscode" || + env["TERM"] === "xterm-256color" || + env["TERM"] === "alacritty" || + env["TERMINAL_EMULATOR"] === "JetBrains-JediTerm" + ); +} diff --git a/packages/cli/test/lib/wizard/cloudflare/__snapshots__/update-wrangler-config.test.ts.snap b/packages/cli/test/lib/wizard/cloudflare/__snapshots__/update-wrangler-config.test.ts.snap new file mode 100644 index 0000000000..e686701afc --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/__snapshots__/update-wrangler-config.test.ts.snap @@ -0,0 +1,40 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`updateWranglerConfig > JSON/JSONC format > adds new fields to JSONC in object 1`] = ` +"{ + // This is a comment + "name": "my-worker", + "main": "src/index.ts", + "version_metadata": { + "existing_field": "existing_value", + "binding": "CF_VERSION_METADATA" + } +}" +`; + +exports[`updateWranglerConfig > JSON/JSONC format > preserves all comment types in JSONC 1`] = ` +"{ + // Worker configuration + "name": "my-worker", + + // Entry point + "main": "src/index.ts", + + /* Block comment */ + "compatibility_date": "2024-01-01", + + "version_metadata": { + "binding": "CF_VERSION_METADATA" + } +}" +`; + +exports[`updateWranglerConfig > JSON/JSONC format > preserves comments in JSONC config 1`] = ` +"{ + // This is a comment + "name": "my-worker", + + "main": "src/index.ts", + "compatibility_flags": ["nodejs_als"] +}" +`; diff --git a/packages/cli/test/lib/wizard/cloudflare/__snapshots__/wrap-worker.test.ts.snap b/packages/cli/test/lib/wizard/cloudflare/__snapshots__/wrap-worker.test.ts.snap new file mode 100644 index 0000000000..1db8c13978 --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/__snapshots__/wrap-worker.test.ts.snap @@ -0,0 +1,164 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`wrapWorkerWithSentry > DSN handling > uses the provided DSN 1`] = ` +"import * as Sentry from "@sentry/cloudflare"; +export default Sentry.withSentry(env => ({ + dsn: "https://d7a9abbecd95ed7d0f5b6c965f5fb6ba@o447951.ingest.us.sentry.io/4510147615391744" +}), { + async fetch(request, env, ctx): Promise { + return new Response('Hello'); + } +});" +`; + +exports[`wrapWorkerWithSentry > basic wrapping > preserves complex handler logic 1`] = ` +"import * as Sentry from "@sentry/cloudflare"; +export default Sentry.withSentry(env => ({ + dsn: "my-dsn" +}), { + async fetch(request, env, ctx): Promise { + const url = new URL(request.url); + switch (url.pathname) { + case '/message': + return new Response('Hello, World!'); + case '/random': + return new Response(crypto.randomUUID()); + default: + return new Response('Not Found', { status: 404 }); + } + }, +} satisfies ExportedHandler);" +`; + +exports[`wrapWorkerWithSentry > basic wrapping > wraps a simple worker export with Sentry 1`] = ` +"import * as Sentry from "@sentry/cloudflare"; +export default Sentry.withSentry(env => ({ + dsn: "my-test-dsn" +}), { + async fetch(request, env, ctx): Promise { + return new Response('Hello World!'); + }, +} satisfies ExportedHandler);" +`; + +exports[`wrapWorkerWithSentry > data collection > includes the dataCollection preset when reduceDataCollection is enabled 1`] = ` +"import * as Sentry from "@sentry/cloudflare"; +export default Sentry.withSentry(env => ({ + dsn: "my-dsn", + + // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control. + tracesSampleRate: 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"] + } + } +}), { + async fetch(request, env, ctx): Promise { + return new Response('Hello'); + } +});" +`; + +exports[`wrapWorkerWithSentry > edge cases > handles files with no default export gracefully 1`] = ` +"import * as Sentry from "@sentry/cloudflare"; +const helper = () => 'test'; +export { helper };" +`; + +exports[`wrapWorkerWithSentry > edge cases > handles worker without satisfies clause 1`] = ` +"import * as Sentry from "@sentry/cloudflare"; +export default Sentry.withSentry(env => ({ + dsn: "my-dsn" +}), { + async fetch(request, env, ctx): Promise { + return new Response('Hello'); + } +});" +`; + +exports[`wrapWorkerWithSentry > import handling > adds Sentry import at the beginning of the file 1`] = ` +"import * as Sentry from "@sentry/cloudflare"; +// Worker comment +export default Sentry.withSentry(env => ({ + dsn: "my-dsn" +}), { + async fetch(request, env, ctx): Promise { + return new Response('Test'); + } +});" +`; + +exports[`wrapWorkerWithSentry > import handling > preserves an external default export 1`] = ` +"import * as Sentry from "@sentry/cloudflare"; +import myWorker from './simple'; + +export default Sentry.withSentry(env => ({ + dsn: "my-dsn" +}), myWorker);" +`; + +exports[`wrapWorkerWithSentry > import handling > preserves existing imports 1`] = ` +"import * as Sentry from "@sentry/cloudflare"; +import { someHelper } from './helpers'; + +export default Sentry.withSentry(env => ({ + dsn: "my-dsn" +}), { + async fetch(request, env, ctx): Promise { + return new Response(someHelper()); + } +});" +`; + +exports[`wrapWorkerWithSentry > performance monitoring > includes tracesSampleRate when performance is enabled 1`] = ` +"import * as Sentry from "@sentry/cloudflare"; +export default Sentry.withSentry(env => ({ + dsn: "my-dsn", + + // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control. + tracesSampleRate: 1 +}), { + async fetch(request, env, ctx): Promise { + return new Response('Hello'); + } +});" +`; + +exports[`wrapWorkerWithSentry > performance monitoring > omits tracesSampleRate when performance is disabled 1`] = ` +"import * as Sentry from "@sentry/cloudflare"; +export default Sentry.withSentry(env => ({ + dsn: "my-dsn" +}), { + async fetch(request, env, ctx): Promise { + return new Response('Hello'); + } +});" +`; diff --git a/packages/cli/test/lib/wizard/cloudflare/create-wrangler-config.test.ts b/packages/cli/test/lib/wizard/cloudflare/create-wrangler-config.test.ts new file mode 100644 index 0000000000..5fc68d7624 --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/create-wrangler-config.test.ts @@ -0,0 +1,50 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { createWranglerConfig } from "../../../../src/lib/wizard/cloudflare/wrangler/create-wrangler-config.js"; + +const { clackMocks } = vi.hoisted(() => { + const info = vi.fn(); + const success = vi.fn(); + + return { + clackMocks: { + info, + success, + }, + }; +}); + +vi.mock("@clack/prompts", () => { + return { + log: { + info: clackMocks.info, + success: clackMocks.success, + }, + }; +}); + +describe("createWranglerConfig", () => { + let tmpDir: string; + + beforeEach(() => { + vi.clearAllMocks(); + tmpDir = mkdtempSync(path.join(tmpdir(), "create-wrangler-config-")); + vi.spyOn(process, "cwd").mockReturnValue(tmpDir); + }); + + afterEach(() => { + vi.restoreAllMocks(); + rmSync(tmpDir, { recursive: true, force: true }); + }); + + it("creates a wrangler.jsonc file with basic configuration", () => { + createWranglerConfig(); + + const content = readFileSync(path.join(tmpDir, "wrangler.jsonc"), "utf-8"); + expect(content).toContain('"name": "my-worker"'); + expect(content).toContain('"main": "src/index.ts"'); + expect(clackMocks.success).toHaveBeenCalledOnce(); + }); +}); diff --git a/packages/cli/test/lib/wizard/cloudflare/ensure-wrangler-config.test.ts b/packages/cli/test/lib/wizard/cloudflare/ensure-wrangler-config.test.ts new file mode 100644 index 0000000000..d34239ed1d --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/ensure-wrangler-config.test.ts @@ -0,0 +1,71 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { ensureWranglerConfig } from "../../../../src/lib/wizard/cloudflare/wrangler/ensure-wrangler-config.js"; +import fs from "node:fs"; +import path from "node:path"; +import os from "node:os"; + +const { clackMocks } = vi.hoisted(() => { + const info = vi.fn(); + const step = vi.fn(); + const success = vi.fn(); + + return { + clackMocks: { + info, + step, + success, + }, + }; +}); + +vi.mock("@clack/prompts", () => { + return { + log: { + info: clackMocks.info, + step: clackMocks.step, + success: clackMocks.success, + }, + }; +}); + +describe("ensure-wrangler-config", () => { + let tmpDir: string; + + beforeEach(() => { + vi.clearAllMocks(); + + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "ensure-wrangler-config-")); + + vi.spyOn(process, "cwd").mockReturnValue(tmpDir); + }); + + afterEach(() => { + if (fs.existsSync(tmpDir)) { + fs.rmSync(tmpDir, { recursive: true }); + } + + vi.restoreAllMocks(); + }); + + it("does nothing if config already exists", () => { + fs.writeFileSync(path.join(tmpDir, "wrangler.jsonc"), "{}"); + + ensureWranglerConfig(); + + expect(clackMocks.info).toHaveBeenCalledWith( + expect.stringContaining("Found existing Wrangler config"), + ); + expect(fs.existsSync(path.join(tmpDir, "wrangler.jsonc"))).toBe(true); + }); + + it("creates config if none exists", () => { + expect(fs.existsSync(path.join(tmpDir, "wrangler.jsonc"))).toBe(false); + + ensureWranglerConfig(); + + expect(clackMocks.info).not.toHaveBeenCalledWith( + expect.stringContaining("Found existing Wrangler config"), + ); + expect(fs.existsSync(path.join(tmpDir, "wrangler.jsonc"))).toBe(true); + }); +}); diff --git a/packages/cli/test/lib/wizard/cloudflare/find-wrangler-config.test.ts b/packages/cli/test/lib/wizard/cloudflare/find-wrangler-config.test.ts new file mode 100644 index 0000000000..db72ad3af9 --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/find-wrangler-config.test.ts @@ -0,0 +1,74 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import fs from "node:fs"; +import path from "node:path"; +import os from "node:os"; +import { findWranglerConfig } from "../../../../src/lib/wizard/cloudflare/wrangler/find-wrangler-config.js"; + +describe("findWranglerConfig", () => { + let tmpDir: string; + + beforeEach(() => { + vi.clearAllMocks(); + + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "find-wrangler-config-")); + + vi.spyOn(process, "cwd").mockReturnValue(tmpDir); + }); + + afterEach(() => { + if (fs.existsSync(tmpDir)) { + fs.rmSync(tmpDir, { recursive: true }); + } + + vi.restoreAllMocks(); + }); + + it("returns wrangler.toml if it exists", () => { + fs.writeFileSync(path.join(tmpDir, "wrangler.toml"), ""); + + const result = findWranglerConfig(); + + expect(result).toBe("wrangler.toml"); + }); + + it("returns wrangler.jsonc if it exists", () => { + fs.writeFileSync(path.join(tmpDir, "wrangler.jsonc"), "{}"); + + const result = findWranglerConfig(); + + expect(result).toBe("wrangler.jsonc"); + }); + + it("returns wrangler.json if it exists", () => { + fs.writeFileSync(path.join(tmpDir, "wrangler.json"), "{}"); + + const result = findWranglerConfig(); + + expect(result).toBe("wrangler.json"); + }); + + it("returns wrangler.jsonc when multiple config files exist (priority order)", () => { + fs.writeFileSync(path.join(tmpDir, "wrangler.toml"), ""); + fs.writeFileSync(path.join(tmpDir, "wrangler.jsonc"), "{}"); + fs.writeFileSync(path.join(tmpDir, "wrangler.json"), "{}"); + + const result = findWranglerConfig(); + + expect(result).toBe("wrangler.jsonc"); + }); + + it("returns wrangler.json when jsonc and json do exist but toml does not", () => { + fs.writeFileSync(path.join(tmpDir, "wrangler.toml"), "{}"); + fs.writeFileSync(path.join(tmpDir, "wrangler.json"), "{}"); + + const result = findWranglerConfig(); + + expect(result).toBe("wrangler.json"); + }); + + it("returns undefined if no config file exists", () => { + const result = findWranglerConfig(); + + expect(result).toBeUndefined(); + }); +}); diff --git a/packages/cli/test/lib/wizard/cloudflare/fixtures/worker/already-wrapped.ts b/packages/cli/test/lib/wizard/cloudflare/fixtures/worker/already-wrapped.ts new file mode 100644 index 0000000000..7f298ade79 --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/fixtures/worker/already-wrapped.ts @@ -0,0 +1,12 @@ +import * as Sentry from '@sentry/cloudflare'; + +export default Sentry.withSentry( + (env) => ({ + dsn: 'existing-dsn', + }), + { + async fetch(request, env, ctx): Promise { + return new Response('Already wrapped'); + }, + }, +); diff --git a/packages/cli/test/lib/wizard/cloudflare/fixtures/worker/complex-handler.ts b/packages/cli/test/lib/wizard/cloudflare/fixtures/worker/complex-handler.ts new file mode 100644 index 0000000000..a8854ce161 --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/fixtures/worker/complex-handler.ts @@ -0,0 +1,13 @@ +export default { + async fetch(request, env, ctx): Promise { + const url = new URL(request.url); + switch (url.pathname) { + case '/message': + return new Response('Hello, World!'); + case '/random': + return new Response(crypto.randomUUID()); + default: + return new Response('Not Found', { status: 404 }); + } + }, +} satisfies ExportedHandler; diff --git a/packages/cli/test/lib/wizard/cloudflare/fixtures/worker/external-default-export.ts b/packages/cli/test/lib/wizard/cloudflare/fixtures/worker/external-default-export.ts new file mode 100644 index 0000000000..e4e0f2bc4b --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/fixtures/worker/external-default-export.ts @@ -0,0 +1,3 @@ +import myWorker from './simple'; + +export default myWorker; diff --git a/packages/cli/test/lib/wizard/cloudflare/fixtures/worker/no-default-export.ts b/packages/cli/test/lib/wizard/cloudflare/fixtures/worker/no-default-export.ts new file mode 100644 index 0000000000..ca16979642 --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/fixtures/worker/no-default-export.ts @@ -0,0 +1,2 @@ +const helper = () => 'test'; +export { helper }; diff --git a/packages/cli/test/lib/wizard/cloudflare/fixtures/worker/simple-with-satisfies.ts b/packages/cli/test/lib/wizard/cloudflare/fixtures/worker/simple-with-satisfies.ts new file mode 100644 index 0000000000..01d21af421 --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/fixtures/worker/simple-with-satisfies.ts @@ -0,0 +1,5 @@ +export default { + async fetch(request, env, ctx): Promise { + return new Response('Hello World!'); + }, +} satisfies ExportedHandler; diff --git a/packages/cli/test/lib/wizard/cloudflare/fixtures/worker/simple.ts b/packages/cli/test/lib/wizard/cloudflare/fixtures/worker/simple.ts new file mode 100644 index 0000000000..ae35cc5698 --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/fixtures/worker/simple.ts @@ -0,0 +1,5 @@ +export default { + async fetch(request, env, ctx): Promise { + return new Response('Hello'); + }, +}; diff --git a/packages/cli/test/lib/wizard/cloudflare/fixtures/worker/with-comment.ts b/packages/cli/test/lib/wizard/cloudflare/fixtures/worker/with-comment.ts new file mode 100644 index 0000000000..bf2c620618 --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/fixtures/worker/with-comment.ts @@ -0,0 +1,6 @@ +// Worker comment +export default { + async fetch(request, env, ctx): Promise { + return new Response('Test'); + }, +}; diff --git a/packages/cli/test/lib/wizard/cloudflare/fixtures/worker/with-import.ts b/packages/cli/test/lib/wizard/cloudflare/fixtures/worker/with-import.ts new file mode 100644 index 0000000000..3eb7287e2d --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/fixtures/worker/with-import.ts @@ -0,0 +1,7 @@ +import { someHelper } from './helpers'; + +export default { + async fetch(request, env, ctx): Promise { + return new Response(someHelper()); + }, +}; diff --git a/packages/cli/test/lib/wizard/cloudflare/fixtures/worker/with-sentry-import.ts b/packages/cli/test/lib/wizard/cloudflare/fixtures/worker/with-sentry-import.ts new file mode 100644 index 0000000000..822a73bd1a --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/fixtures/worker/with-sentry-import.ts @@ -0,0 +1,8 @@ +import * as Sentry from '@sentry/cloudflare'; + +export default { + async fetch(request, env, ctx): Promise { + Sentry.captureMessage('test'); + return new Response('Test'); + }, +}; diff --git a/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-all-comment-types.jsonc b/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-all-comment-types.jsonc new file mode 100644 index 0000000000..3e5556174e --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-all-comment-types.jsonc @@ -0,0 +1,8 @@ +{ + // Worker configuration + "name": "my-worker", + // Entry point + "main": "src/index.ts", + /* Block comment */ + "compatibility_date": "2024-01-01" +} \ No newline at end of file diff --git a/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-basic.json b/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-basic.json new file mode 100644 index 0000000000..50e102247e --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-basic.json @@ -0,0 +1 @@ +{"name":"my-worker","main":"src/index.ts","compatibility_date":"2024-01-01"} \ No newline at end of file diff --git a/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-complex-with-comments.jsonc b/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-complex-with-comments.jsonc new file mode 100644 index 0000000000..d0d8416d4b --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-complex-with-comments.jsonc @@ -0,0 +1,20 @@ +/** + * Configuration file + */ +{ + "$schema": "node_modules/wrangler/config-schema.json", + "name": "temp-cloudflare-starter", + "main": "src/index.ts", + "compatibility_date": "2025-12-02", + "compatibility_flags": [ + "global_fetch_strictly_public" + ], + "assets": { + // The path to the directory + "directory": "./public" + }, + "observability": { + "enabled": true + } + // More comments +} \ No newline at end of file diff --git a/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-empty.json b/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-empty.json new file mode 100644 index 0000000000..7a73a41bfd --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-empty.json @@ -0,0 +1,2 @@ +{ +} \ No newline at end of file diff --git a/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-minimal.json b/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-minimal.json new file mode 100644 index 0000000000..7904d22563 --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-minimal.json @@ -0,0 +1 @@ +{"name":"my-worker"} \ No newline at end of file diff --git a/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-multi-line-array.json b/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-multi-line-array.json new file mode 100644 index 0000000000..fb605c8235 --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-multi-line-array.json @@ -0,0 +1,12 @@ +{ + "$schema": "node_modules/wrangler/config-schema.json", + "name": "temp-cloudflare-starter", + "main": "src/index.ts", + "compatibility_date": "2025-12-02", + "compatibility_flags": [ + "global_fetch_strictly_public" + ], + "assets": { + "directory": "./public" + } +} \ No newline at end of file diff --git a/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-trailing-comma.jsonc b/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-trailing-comma.jsonc new file mode 100644 index 0000000000..322404fbdd --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-trailing-comma.jsonc @@ -0,0 +1,4 @@ +{ + "name": "my-worker", + "main": "src/index.ts", +} diff --git a/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-with-comment.jsonc b/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-with-comment.jsonc new file mode 100644 index 0000000000..6c0d3ecd10 --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-with-comment.jsonc @@ -0,0 +1,5 @@ +{ + // This is a comment + "name": "my-worker", + "main": "src/index.ts" +} \ No newline at end of file diff --git a/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-with-duplicate-flags.json b/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-with-duplicate-flags.json new file mode 100644 index 0000000000..ecbd21b0e4 --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-with-duplicate-flags.json @@ -0,0 +1 @@ +{"name":"my-worker","compatibility_flags":["nodejs_als","old_flag"]} \ No newline at end of file diff --git a/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-with-flags.json b/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-with-flags.json new file mode 100644 index 0000000000..22164f4227 --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-with-flags.json @@ -0,0 +1 @@ +{"name":"my-worker","compatibility_flags":["old_flag"]} \ No newline at end of file diff --git a/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-with-metadata.jsonc b/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-with-metadata.jsonc new file mode 100644 index 0000000000..25b343eb0a --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/fixtures/wrangler/wrangler-with-metadata.jsonc @@ -0,0 +1,8 @@ +{ + // This is a comment + "name": "my-worker", + "main": "src/index.ts", + "version_metadata": { + "existing_field": "existing_value" + } +} \ No newline at end of file diff --git a/packages/cli/test/lib/wizard/cloudflare/get-entry-point-from-wrangler-config.test.ts b/packages/cli/test/lib/wizard/cloudflare/get-entry-point-from-wrangler-config.test.ts new file mode 100644 index 0000000000..e26fde579c --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/get-entry-point-from-wrangler-config.test.ts @@ -0,0 +1,92 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import fs from "node:fs"; +import path from "node:path"; +import os from "node:os"; +import { getEntryPointFromWranglerConfig } from "../../../../src/lib/wizard/cloudflare/wrangler/get-entry-point-from-wrangler-config.js"; + +describe("getEntryPointFromWranglerConfig", () => { + let tmpDir: string; + + beforeEach(() => { + vi.clearAllMocks(); + + tmpDir = fs.mkdtempSync( + path.join(os.tmpdir(), "get-entry-point-from-wrangler-config-"), + ); + + vi.spyOn(process, "cwd").mockReturnValue(tmpDir); + }); + + afterEach(() => { + if (fs.existsSync(tmpDir)) { + fs.rmSync(tmpDir, { recursive: true }); + } + + vi.restoreAllMocks(); + }); + + it("returns undefined if no config file exists", () => { + const result = getEntryPointFromWranglerConfig(); + + expect(result).toBeUndefined(); + }); + + it("parses main from wrangler.toml", () => { + fs.writeFileSync( + path.join(tmpDir, "wrangler.toml"), + `name = "my-worker" +main = "src/worker.ts" +compatibility_date = "2024-01-01"`, + ); + + const result = getEntryPointFromWranglerConfig(); + + expect(result).toBe("src/worker.ts"); + }); + + it("parses main from wrangler.json", () => { + fs.writeFileSync( + path.join(tmpDir, "wrangler.json"), + JSON.stringify({ name: "my-worker", main: "src/deeplink/index.ts" }), + ); + + const result = getEntryPointFromWranglerConfig(); + + expect(result).toBe("src/deeplink/index.ts"); + }); + + it("parses main from wrangler.jsonc with comments", () => { + fs.writeFileSync( + path.join(tmpDir, "wrangler.jsonc"), + `{ + // Comment + "name": "my-worker", + "main": "src/inside-app/index.ts" +}`, + ); + + const result = getEntryPointFromWranglerConfig(); + + expect(result).toBe("src/inside-app/index.ts"); + }); + + it("returns undefined if main field is not specified", () => { + fs.writeFileSync( + path.join(tmpDir, "wrangler.toml"), + `name = "my-worker" +compatibility_date = "2024-01-01"`, + ); + + const result = getEntryPointFromWranglerConfig(); + + expect(result).toBeUndefined(); + }); + + it("returns undefined if JSON parsing fails", () => { + fs.writeFileSync(path.join(tmpDir, "wrangler.json"), "{ invalid json }"); + + const result = getEntryPointFromWranglerConfig(); + + expect(result).toBeUndefined(); + }); +}); diff --git a/packages/cli/test/lib/wizard/cloudflare/sdk-setup.test.ts b/packages/cli/test/lib/wizard/cloudflare/sdk-setup.test.ts new file mode 100644 index 0000000000..4417368ce8 --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/sdk-setup.test.ts @@ -0,0 +1,223 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import fs from "node:fs"; +import path from "node:path"; +import os from "node:os"; +import { createSentryInitFile } from "../../../../src/lib/wizard/cloudflare/sdk-setup.js"; +import { defaultEntryPoint } from "../../../../src/lib/wizard/cloudflare/wrangler/get-entry-point-from-wrangler-config.js"; +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as templates from "../../../../src/lib/wizard/cloudflare/templates.js"; +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as wrapWorker from "../../../../src/lib/wizard/cloudflare/wrap-worker.js"; + +const { clackMocks } = vi.hoisted(() => { + const info = vi.fn(); + const warn = vi.fn(); + const success = vi.fn(); + const step = vi.fn(); + const note = vi.fn(); + + return { + clackMocks: { + info, + warn, + success, + step, + note, + }, + }; +}); + +vi.mock("@clack/prompts", () => ({ + log: { + info: clackMocks.info, + warn: clackMocks.warn, + success: clackMocks.success, + step: clackMocks.step, + }, + note: clackMocks.note, +})); + +const { getEntryPointFromWranglerConfigMock } = vi.hoisted(() => ({ + getEntryPointFromWranglerConfigMock: vi.fn(), +})); + +vi.mock( + "../../../../src/lib/wizard/cloudflare/wrangler/get-entry-point-from-wrangler-config.js", + () => ({ + getEntryPointFromWranglerConfig: getEntryPointFromWranglerConfigMock, + defaultEntryPoint: "src/index.ts", + }), +); + +describe("createSentryInitFile", () => { + let tmpDir: string; + const testDsn = "https://example@sentry.io/123"; + const testFeatures = { + performance: true, + }; + + beforeEach(() => { + vi.clearAllMocks(); + getEntryPointFromWranglerConfigMock.mockReset(); + + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "sdk-setup-test-")); + + vi.spyOn(process, "cwd").mockReturnValue(tmpDir); + }); + + afterEach(() => { + if (fs.existsSync(tmpDir)) { + fs.rmSync(tmpDir, { recursive: true }); + } + + vi.restoreAllMocks(); + }); + + it("creates a new default entry point file", async () => { + const template = + 'export default { async fetch() { return new Response("ᕕ(⌐■_■)ᕗ ♪♬"); } }'; + const getCloudflareWorkerTemplateWithHandlerSpy = vi + .spyOn(templates, "getCloudflareWorkerTemplateWithHandler") + .mockReturnValue(template); + + await createSentryInitFile(testDsn, testFeatures, false); + + const expectedPath = path.join(tmpDir, "src/index.ts"); + const content = fs.readFileSync(expectedPath, "utf-8"); + + expect(clackMocks.info).toHaveBeenCalledWith( + "No entry point found in wrangler config, creating a new one.", + ); + expect(fs.existsSync(expectedPath)).toBe(true); + expect(content).toBe(template); + expect(clackMocks.success).toHaveBeenCalledWith("Created src/index.ts."); + expect(getCloudflareWorkerTemplateWithHandlerSpy).toHaveBeenCalled(); + }); + + describe("when entry point is found in wrangler config", () => { + describe("and the entry point file exists", () => { + beforeEach(async () => { + await createSentryInitFile(testDsn, testFeatures, false); + getEntryPointFromWranglerConfigMock.mockReturnValue(defaultEntryPoint); + }); + + it("wraps the worker with Sentry when wrapping succeeds", async () => { + const wrapWorkerWithSentrySpy = vi + .spyOn(wrapWorker, "wrapWorkerWithSentry") + .mockResolvedValue(undefined); + + await createSentryInitFile(testDsn, testFeatures, false); + + expect(wrapWorkerWithSentrySpy).toHaveBeenCalledWith( + path.join(tmpDir, defaultEntryPoint), + testDsn, + testFeatures, + false, + ); + }); + + it("handles wrapping failure gracefully", async () => { + vi.spyOn(wrapWorker, "wrapWorkerWithSentry").mockRejectedValue( + new Error("Wrapping failed"), + ); + + await createSentryInitFile(testDsn, testFeatures, false); + + expect(clackMocks.warn).toHaveBeenCalledWith( + "Failed to wrap worker automatically.", + ); + expect(clackMocks.step).toHaveBeenCalledWith( + "Please wrap your handler with Sentry initialization:", + ); + expect(clackMocks.note).toHaveBeenCalledWith( + expect.stringContaining("import * as Sentry"), + ); + }); + + it("shows template with correct DSN when wrapping fails", async () => { + vi.spyOn(wrapWorker, "wrapWorkerWithSentry").mockRejectedValue( + new Error("Failed"), + ); + const getCloudflareWorkerTemplateSpy = vi + .spyOn(templates, "getCloudflareWorkerTemplate") + .mockReturnValue("template with dsn"); + + await createSentryInitFile(testDsn, testFeatures, false); + + expect(getCloudflareWorkerTemplateSpy).toHaveBeenCalledWith( + testDsn, + testFeatures, + false, + ); + expect(clackMocks.note).toHaveBeenCalledWith("template with dsn"); + }); + + it("passes performance feature flag correctly", async () => { + const wrapWorkerWithSentrySpy = vi + .spyOn(wrapWorker, "wrapWorkerWithSentry") + .mockResolvedValue(undefined); + + await createSentryInitFile(testDsn, { performance: false }, false); + + expect(wrapWorkerWithSentrySpy).toHaveBeenCalledWith( + path.join(tmpDir, defaultEntryPoint), + testDsn, + { performance: false }, + false, + ); + }); + + it("passes performance feature flag when enabled", async () => { + const wrapWorkerWithSentrySpy = vi + .spyOn(wrapWorker, "wrapWorkerWithSentry") + .mockResolvedValue(undefined); + + await createSentryInitFile(testDsn, { performance: true }, false); + + expect(wrapWorkerWithSentrySpy).toHaveBeenCalledWith( + path.join(tmpDir, defaultEntryPoint), + testDsn, + { performance: true }, + false, + ); + }); + + it("passes reduceDataCollection through to the worker wrapper", async () => { + const wrapWorkerWithSentrySpy = vi + .spyOn(wrapWorker, "wrapWorkerWithSentry") + .mockResolvedValue(undefined); + + await createSentryInitFile(testDsn, testFeatures, true); + + expect(wrapWorkerWithSentrySpy).toHaveBeenCalledWith( + path.join(tmpDir, defaultEntryPoint), + testDsn, + testFeatures, + true, + ); + }); + }); + + describe("and the entry point file does not exist", () => { + it("does not throw an error", async () => { + vi.spyOn(wrapWorker, "wrapWorkerWithSentry").mockResolvedValue( + undefined, + ); + + await expect( + createSentryInitFile(testDsn, testFeatures, false), + ).resolves.not.toThrow(); + }); + + it("does not call wrapWorkerWithSentry", async () => { + const wrapWorkerWithSentrySpy = vi + .spyOn(wrapWorker, "wrapWorkerWithSentry") + .mockResolvedValue(undefined); + + await createSentryInitFile(testDsn, testFeatures, false); + + expect(wrapWorkerWithSentrySpy).not.toHaveBeenCalled(); + }); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/cloudflare/templates.test.ts b/packages/cli/test/lib/wizard/cloudflare/templates.test.ts new file mode 100644 index 0000000000..0e833890af --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/templates.test.ts @@ -0,0 +1,136 @@ +import { describe, expect, it } from "vitest"; +import { getCloudflareWorkerTemplate } from "../../../../src/lib/wizard/cloudflare/templates.js"; + +describe("Cloudflare code templates", () => { + describe("getCloudflareWorkerTemplate", () => { + it("generates worker template with performance monitoring enabled", () => { + const template = getCloudflareWorkerTemplate( + "my-dsn", + { + performance: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "import * as Sentry from '@sentry/cloudflare'; + + export default Sentry.withSentry( + (env) => ({ + dsn: 'my-dsn', + // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control. + tracesSampleRate: 1, + }), + { + async fetch(request, env, ctx): Promise { + // Your worker logic here + return new Response('Hello World!'); + }, + } satisfies ExportedHandler, + ); + " + `); + }); + + it("generates worker template with performance monitoring disabled", () => { + const template = getCloudflareWorkerTemplate( + "my-dsn", + { + performance: false, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "import * as Sentry from '@sentry/cloudflare'; + + export default Sentry.withSentry( + (env) => ({ + dsn: 'my-dsn', + }), + { + async fetch(request, env, ctx): Promise { + // Your worker logic here + return new Response('Hello World!'); + }, + } satisfies ExportedHandler, + ); + " + `); + }); + + it("generates worker template with reduced data collection", () => { + const template = getCloudflareWorkerTemplate( + "my-dsn", + { + performance: true, + }, + true, + ); + + expect(template).toContain("userInfo: false"); + expect(template).toContain( + 'httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }', + ); + + expect(template).toMatchInlineSnapshot(` + "import * as Sentry from '@sentry/cloudflare'; + + export default Sentry.withSentry( + (env) => ({ + dsn: 'my-dsn', + // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control. + tracesSampleRate: 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"] }, + }, + }), + { + async fetch(request, env, ctx): Promise { + // Your worker logic here + return new Response('Hello World!'); + }, + } satisfies ExportedHandler, + ); + " + `); + }); + + it("includes the correct DSN", () => { + const dsn = "https://example@sentry.io/123"; + const template = getCloudflareWorkerTemplate( + dsn, + { + performance: true, + }, + false, + ); + + expect(template).toContain(`dsn: '${dsn}'`); + }); + + it("wraps handler with Sentry.withSentry", () => { + const template = getCloudflareWorkerTemplate( + "my-dsn", + { + performance: false, + }, + false, + ); + + expect(template).toContain("Sentry.withSentry"); + expect(template).toContain("async fetch(request, env, ctx)"); + expect(template).toContain("satisfies ExportedHandler"); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/cloudflare/update-wrangler-config.test.ts b/packages/cli/test/lib/wizard/cloudflare/update-wrangler-config.test.ts new file mode 100644 index 0000000000..463dba5584 --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/update-wrangler-config.test.ts @@ -0,0 +1,279 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import fs from "node:fs"; +import path from "node:path"; +import os from "node:os"; +import { updateWranglerConfig } from "../../../../src/lib/wizard/cloudflare/wrangler/update-wrangler-config.js"; + +const { clackMocks } = vi.hoisted(() => { + return { + clackMocks: { + log: { + success: vi.fn(), + info: vi.fn(), + step: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + }, + }, + }; +}); + +vi.mock("@clack/prompts", () => clackMocks); + +describe("updateWranglerConfig", () => { + const fixturesDir = path.join(__dirname, "fixtures", "wrangler"); + let tmpDir: string; + + function copyFixture(fixtureName: string, targetName: string): void { + const content = fs.readFileSync( + path.join(fixturesDir, fixtureName), + "utf-8", + ); + fs.writeFileSync(path.join(tmpDir, targetName), content); + } + + function readResult(fileName: string): string { + return fs.readFileSync(path.join(tmpDir, fileName), "utf-8"); + } + + beforeEach(() => { + vi.clearAllMocks(); + + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "update-wrangler-config-")); + + vi.spyOn(process, "cwd").mockReturnValue(tmpDir); + }); + + afterEach(() => { + if (fs.existsSync(tmpDir)) { + fs.rmSync(tmpDir, { recursive: true }); + } + + vi.restoreAllMocks(); + }); + + describe("JSON/JSONC format", () => { + it("adds new fields to JSON config", async () => { + copyFixture("wrangler-basic.json", "wrangler.json"); + + const result = await updateWranglerConfig({ + compatibility_flags: ["nodejs_als"], + version_metadata: { binding: "CF_VERSION_METADATA" }, + }); + + const writtenContent = readResult("wrangler.json"); + const parsed = JSON.parse(writtenContent) as Record; + + expect(result).toBe(true); + expect(parsed["compatibility_flags"]).toEqual(["nodejs_als"]); + expect(parsed["version_metadata"]).toEqual({ + binding: "CF_VERSION_METADATA", + }); + expect(parsed["name"]).toBe("my-worker"); + }); + + it("overrides existing fields in JSON config", async () => { + copyFixture("wrangler-basic.json", "wrangler.json"); + + const initialContent = readResult("wrangler.json"); + const initialParsed = JSON.parse(initialContent) as Record< + string, + unknown + >; + + const result = await updateWranglerConfig({ + compatibility_date: "1337-01-01", + }); + + const writtenContent = readResult("wrangler.json"); + const parsed = JSON.parse(writtenContent) as Record; + + expect(result).toBe(true); + expect(parsed["compatibility_date"]).not.toEqual( + initialParsed["compatibility_date"], + ); + expect(parsed["compatibility_date"]).toEqual("1337-01-01"); + }); + + it("merges array fields in JSON config", async () => { + copyFixture("wrangler-with-flags.json", "wrangler.json"); + + const result = await updateWranglerConfig({ + compatibility_flags: ["nodejs_als", "nodejs_compat"], + }); + + const writtenContent = readResult("wrangler.json"); + const parsed = JSON.parse(writtenContent) as Record; + + expect(result).toBe(true); + expect(parsed["compatibility_flags"]).toEqual([ + "old_flag", + "nodejs_als", + "nodejs_compat", + ]); + }); + + it("drops superseded compatibility flags when asked to", async () => { + copyFixture("wrangler-with-duplicate-flags.json", "wrangler.json"); + + const result = await updateWranglerConfig( + { compatibility_flags: ["nodejs_compat"] }, + { removeCompatibilityFlags: ["nodejs_als"] }, + ); + + const writtenContent = readResult("wrangler.json"); + const parsed = JSON.parse(writtenContent) as Record; + + expect(result).toBe(true); + expect(parsed["compatibility_flags"]).toEqual([ + "old_flag", + "nodejs_compat", + ]); + }); + + it("only removes flags from compatibility_flags, not from other arrays", async () => { + copyFixture("wrangler-with-duplicate-flags.json", "wrangler.json"); + + const result = await updateWranglerConfig( + { other_list: ["nodejs_als"] }, + { removeCompatibilityFlags: ["nodejs_als"] }, + ); + + const writtenContent = readResult("wrangler.json"); + const parsed = JSON.parse(writtenContent) as Record; + + expect(result).toBe(true); + expect(parsed["other_list"]).toEqual(["nodejs_als"]); + expect(parsed["compatibility_flags"]).toEqual(["nodejs_als", "old_flag"]); + }); + + it("deduplicates array values in JSON", async () => { + copyFixture("wrangler-with-duplicate-flags.json", "wrangler.json"); + + const result = await updateWranglerConfig({ + compatibility_flags: ["nodejs_als", "new_flag"], + }); + + const writtenContent = readResult("wrangler.json"); + const parsed = JSON.parse(writtenContent) as Record; + + expect(result).toBe(true); + expect(parsed["compatibility_flags"]).toEqual([ + "nodejs_als", + "old_flag", + "new_flag", + ]); + }); + + it("preserves comments in JSONC config", async () => { + copyFixture("wrangler-with-comment.jsonc", "wrangler.jsonc"); + + const result = await updateWranglerConfig({ + compatibility_flags: ["nodejs_als"], + }); + + const writtenContent = readResult("wrangler.jsonc"); + + expect(result).toBe(true); + expect(writtenContent).toMatchSnapshot(); + }); + + it("merges multi-line array fields in JSON config", async () => { + copyFixture("wrangler-multi-line-array.json", "wrangler.json"); + + const result = await updateWranglerConfig({ + compatibility_flags: ["nodejs_als"], + }); + + const writtenContent = readResult("wrangler.json"); + const parsed = JSON.parse(writtenContent) as Record; + + expect(result).toBe(true); + expect(parsed["compatibility_flags"]).toEqual([ + "global_fetch_strictly_public", + "nodejs_als", + ]); + }); + + it("adds new fields to JSONC in object", async () => { + copyFixture("wrangler-with-metadata.jsonc", "wrangler.jsonc"); + + const result = await updateWranglerConfig({ + version_metadata: { binding: "CF_VERSION_METADATA" }, + }); + + const writtenContent = readResult("wrangler.jsonc"); + + expect(result).toBe(true); + expect(writtenContent).toMatchSnapshot(); + }); + + it("preserves all comment types in JSONC", async () => { + copyFixture("wrangler-all-comment-types.jsonc", "wrangler.jsonc"); + + await updateWranglerConfig({ + version_metadata: { binding: "CF_VERSION_METADATA" }, + }); + + const writtenContent = readResult("wrangler.jsonc"); + + expect(writtenContent).toMatchSnapshot(); + }); + + it("handles empty JSON object", async () => { + copyFixture("wrangler-empty.json", "wrangler.json"); + + const result = await updateWranglerConfig({ + compatibility_flags: ["nodejs_als"], + }); + + const writtenContent = readResult("wrangler.json"); + const parsed = JSON.parse(writtenContent) as Record; + + expect(result).toBe(true); + expect(parsed["compatibility_flags"]).toEqual(["nodejs_als"]); + }); + + it("adds nested objects to JSON", async () => { + copyFixture("wrangler-minimal.json", "wrangler.json"); + + const result = await updateWranglerConfig({ + version_metadata: { binding: "CF_VERSION_METADATA" }, + }); + + const writtenContent = readResult("wrangler.json"); + const parsed = JSON.parse(writtenContent) as Record; + + expect(result).toBe(true); + expect(parsed["version_metadata"]).toEqual({ + binding: "CF_VERSION_METADATA", + }); + }); + + it("handles JSONC with trailing comma", async () => { + copyFixture("wrangler-trailing-comma.jsonc", "wrangler.jsonc"); + + const result = await updateWranglerConfig({ + compatibility_flags: ["nodejs_als"], + }); + + const writtenContent = readResult("wrangler.jsonc"); + + expect(result).toBe(true); + expect(writtenContent).toContain("compatibility_flags"); + }); + }); + + describe("error handling", () => { + it("returns false when no config file exists", async () => { + const result = await updateWranglerConfig({ + compatibility_flags: ["nodejs_als"], + }); + + expect(result).toBe(false); + expect(clackMocks.log.warn).toHaveBeenCalledWith( + "No wrangler config file found.", + ); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/cloudflare/wrap-worker.test.ts b/packages/cli/test/lib/wizard/cloudflare/wrap-worker.test.ts new file mode 100644 index 0000000000..68530bbb16 --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/wrap-worker.test.ts @@ -0,0 +1,310 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import fs from "node:fs"; +import path from "node:path"; +import os from "node:os"; +import { wrapWorkerWithSentry } from "../../../../src/lib/wizard/cloudflare/wrap-worker.js"; + +describe("wrapWorkerWithSentry", () => { + const fixturesDir = path.join(__dirname, "fixtures", "worker"); + let tmpDir: string; + + function copyFixture(fixtureName: string): string { + const content = fs.readFileSync( + path.join(fixturesDir, fixtureName), + "utf-8", + ); + const targetPath = path.join(tmpDir, "worker.ts"); + fs.writeFileSync(targetPath, content); + return targetPath; + } + + function readResult(): string { + return fs.readFileSync(path.join(tmpDir, "worker.ts"), "utf-8"); + } + + beforeEach(() => { + vi.clearAllMocks(); + + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "wrap-worker-")); + }); + + afterEach(() => { + if (fs.existsSync(tmpDir)) { + fs.rmSync(tmpDir, { recursive: true }); + } + + vi.restoreAllMocks(); + }); + + describe("basic wrapping", () => { + it("wraps a simple worker export with Sentry", async () => { + const filePath = copyFixture("simple-with-satisfies.ts"); + + await wrapWorkerWithSentry( + filePath, + "my-test-dsn", + { + performance: false, + }, + false, + ); + + const result = readResult(); + + expect(result).toMatchSnapshot(); + }); + + it("preserves complex handler logic", async () => { + const filePath = copyFixture("complex-handler.ts"); + + await wrapWorkerWithSentry( + filePath, + "my-dsn", + { + performance: false, + }, + false, + ); + + const result = readResult(); + + expect(result).toMatchSnapshot(); + }); + }); + + describe("performance monitoring", () => { + it("includes tracesSampleRate when performance is enabled", async () => { + const filePath = copyFixture("simple.ts"); + + await wrapWorkerWithSentry( + filePath, + "my-dsn", + { + performance: true, + }, + false, + ); + + const result = readResult(); + + expect(result).toMatchSnapshot(); + }); + + it("omits tracesSampleRate when performance is disabled", async () => { + const filePath = copyFixture("simple.ts"); + + await wrapWorkerWithSentry( + filePath, + "my-dsn", + { + performance: false, + }, + false, + ); + + const result = readResult(); + + expect(result).toMatchSnapshot(); + }); + }); + + describe("data collection", () => { + it("includes the dataCollection preset when reduceDataCollection is enabled", async () => { + const filePath = copyFixture("simple.ts"); + + await wrapWorkerWithSentry( + filePath, + "my-dsn", + { + performance: true, + }, + true, + ); + + const result = readResult(); + + expect(result).toContain("userInfo: false"); + // Recast prints the nested deny-list objects multiline. + expect(result).toContain("httpHeaders: {"); + expect(result).toContain( + 'deny: ["forwarded", "-ip", "remote-", "via", "-user"]', + ); + + expect(result).toMatchSnapshot(); + }); + + it("omits the dataCollection preset when reduceDataCollection is disabled", async () => { + const filePath = copyFixture("simple.ts"); + + await wrapWorkerWithSentry( + filePath, + "my-dsn", + { + performance: true, + }, + false, + ); + + const result = readResult(); + + expect(result).not.toContain("dataCollection"); + }); + }); + + describe("import handling", () => { + it("adds Sentry import at the beginning of the file", async () => { + const filePath = copyFixture("with-comment.ts"); + + await wrapWorkerWithSentry( + filePath, + "my-dsn", + { + performance: false, + }, + false, + ); + + const result = readResult(); + + expect(result).toMatchSnapshot(); + }); + + it("preserves existing imports", async () => { + const filePath = copyFixture("with-import.ts"); + + await wrapWorkerWithSentry( + filePath, + "my-dsn", + { + performance: false, + }, + false, + ); + + const result = readResult(); + + expect(result).toMatchSnapshot(); + }); + + it("preserves an external default export", async () => { + const filePath = copyFixture("external-default-export.ts"); + + await wrapWorkerWithSentry( + filePath, + "my-dsn", + { + performance: false, + }, + false, + ); + + const result = readResult(); + + expect(result).toMatchSnapshot(); + }); + }); + + describe("idempotency", () => { + it("does not wrap again if Sentry is already present", async () => { + const filePath = copyFixture("already-wrapped.ts"); + const originalContent = fs.readFileSync( + path.join(fixturesDir, "already-wrapped.ts"), + "utf-8", + ); + + await wrapWorkerWithSentry( + filePath, + "new-dsn", + { + performance: true, + }, + false, + ); + + const result = readResult(); + + expect(result).toBe(originalContent); + }); + + it("does not modify if @sentry/cloudflare is imported", async () => { + const filePath = copyFixture("with-sentry-import.ts"); + const originalContent = fs.readFileSync( + path.join(fixturesDir, "with-sentry-import.ts"), + "utf-8", + ); + + await wrapWorkerWithSentry( + filePath, + "my-dsn", + { + performance: false, + }, + false, + ); + + const result = readResult(); + + expect(result).toBe(originalContent); + }); + }); + + describe("DSN handling", () => { + it("uses the provided DSN", async () => { + const filePath = copyFixture("simple.ts"); + + const testDsn = + "https://d7a9abbecd95ed7d0f5b6c965f5fb6ba@o447951.ingest.us.sentry.io/4510147615391744"; + + await wrapWorkerWithSentry( + filePath, + testDsn, + { + performance: false, + }, + false, + ); + + const result = readResult(); + + expect(result).toMatchSnapshot(); + }); + }); + + describe("edge cases", () => { + it("handles worker without satisfies clause", async () => { + const filePath = copyFixture("simple.ts"); + + await wrapWorkerWithSentry( + filePath, + "my-dsn", + { + performance: false, + }, + false, + ); + + const result = readResult(); + + expect(result).toMatchSnapshot(); + }); + + it("handles files with no default export gracefully", async () => { + const filePath = copyFixture("no-default-export.ts"); + + await expect( + wrapWorkerWithSentry( + filePath, + "my-dsn", + { + performance: false, + }, + false, + ), + ).resolves.not.toThrow(); + + const result = readResult(); + + expect(result).toMatchSnapshot(); + }); + }); +}); 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 0000000000..ef40a9f22e --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/sentry-cli.test.ts @@ -0,0 +1,106 @@ +import fs from "node:fs"; + +import { + addSentryCommandToBuildCommand, + getSentryCliNpmScript, +} from "../../../../../src/lib/wizard/sourcemaps/tools/sentry-cli.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 } from "../../../../../src/lib/wizard/utils/clack/index.js"; + +import { vi, it, describe, expect, afterEach } from "vitest"; + +const writeFileSpy = vi + .spyOn(fs.promises, "writeFile") + .mockImplementation(() => Promise.resolve()); + +vi.mock("@clack/prompts", () => { + return { + log: { + info: vi.fn(), + success: vi.fn(), + }, + confirm: vi.fn().mockResolvedValue(true), + 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", + )), + 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(); + }); +}); + +describe("getSentryCliNpmScript", () => { + const options = { + orgSlug: "my-org", + projectSlug: "my-project", + url: "https://sentry.io", + selfHosted: false, + authToken: "_ignore", + }; + + it("injects debug IDs and uploads the build output", () => { + expect(getSentryCliNpmScript(options, "./dist")).toBe( + "sentry sourcemap inject ./dist && sentry sourcemap upload --org my-org --project my-project ./dist", + ); + }); + + it("passes a self-hosted URL in SENTRY_URL", () => { + expect( + getSentryCliNpmScript( + { ...options, selfHosted: true, url: "https://sentry.example.com" }, + "./dist", + ), + ).toBe( + "sentry sourcemap inject ./dist && SENTRY_URL=https://sentry.example.com sentry sourcemap upload --org my-org --project my-project ./dist", + ); + }); +}); diff --git a/packages/cli/test/lib/wizard/sourcemaps/tools/tsc.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/tsc.test.ts new file mode 100644 index 0000000000..76b35a23cf --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/tsc.test.ts @@ -0,0 +1,183 @@ +import fs from "node:fs"; +import { enableSourcemaps } from "../../../../../src/lib/wizard/sourcemaps/tools/tsc.js"; + +import { vi, it, describe, expect, afterEach } from "vitest"; + +function updateFileContent(content: string): void { + fileContent = content; +} + +let fileContent = ""; + +vi.mock("@clack/prompts", () => { + return { + log: { + info: vi.fn(), + success: vi.fn(), + }, + }; +}); + +vi.spyOn(fs.promises, "readFile").mockImplementation(() => + Promise.resolve(fileContent), +); + +const writeFileSpy = vi + .spyOn(fs.promises, "writeFile") + .mockImplementation(() => Promise.resolve(void 0)); + +describe("enableSourcemaps", () => { + afterEach(() => { + fileContent = ""; + vi.clearAllMocks(); + }); + + it.each([ + [ + "no sourcemaps options", + ` +/** + * My TS config with comments + */ +{ + "extends": "./tsconfig.build.json", + + "compilerOptions": { + // line comment which should stay + "moduleResolution": "node16", + "outDir": "dist" // another inline comment + }, + + "include": [ + "src/**/*", + "test/**/*" + ] +} +`, + ` +/** + * My TS config with comments + */ +{ + "extends": "./tsconfig.build.json", + + "compilerOptions": { + // line comment which should stay + "moduleResolution": "node16", + + // another inline comment + "outDir": "dist", + + "sourceMap": true, + "inlineSources": true, + + // Set \`sourceRoot\` to "/" to strip the build path prefix + // from generated source code references. + // This improves issue grouping in Sentry. + "sourceRoot": "/" + }, + + "include": [ + "src/**/*", + "test/**/*" + ] +} +`, + ], + [ + "a few sourcemaps options", + ` +/** + * My TS config with comments + */ +{ + "extends": "./tsconfig.build.json", + + "compilerOptions": { + // line comment which should stay + "moduleResolution": "node16", + "outDir": "dist", // another inline comment + "sourceMap": false, + "sourceRoot": "/src" + }, + + "include": [ + "src/**/*", + "test/**/*" + ] +} +`, + ` +/** + * My TS config with comments + */ +{ + "extends": "./tsconfig.build.json", + + "compilerOptions": { + // line comment which should stay + "moduleResolution": "node16", + + // another inline comment + "outDir": "dist", + + "sourceMap": true, + + // Set \`sourceRoot\` to "/" to strip the build path prefix + // from generated source code references. + // This improves issue grouping in Sentry. + "sourceRoot": "/", + + "inlineSources": true + }, + + "include": [ + "src/**/*", + "test/**/*" + ] +} +`, + ], + [ + "no compiler options", + ` +{ + "include": [ + "src/**/*", + "test/**/*" + ] +} +`, + ` +{ + "include": [ + "src/**/*", + "test/**/*" + ], + + "compilerOptions": { + "sourceMap": true, + "inlineSources": true, + + // Set \`sourceRoot\` to "/" to strip the build path prefix + // from generated source code references. + // This improves issue grouping in Sentry. + "sourceRoot": "/" + } +} +`, + ], + ])( + "adds the plugin and enables source maps generation (%s)", + async (_, originalCode, expectedCode) => { + updateFileContent(originalCode); + + const addedCode = await enableSourcemaps(""); + + expect(writeFileSpy).toHaveBeenCalledTimes(1); + const fileContent = writeFileSpy.mock.calls[0]?.[1]; + expect(fileContent).toBe(expectedCode); + expect(addedCode).toBe(true); + }, + ); +}); diff --git a/packages/cli/test/lib/wizard/sourcemaps/tools/vite.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/vite.test.ts new file mode 100644 index 0000000000..13385d3e19 --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/vite.test.ts @@ -0,0 +1,159 @@ +import fs from "node:fs"; +import { addVitePluginToConfig } from "../../../../../src/lib/wizard/sourcemaps/tools/vite.js"; + +import { vi, it, describe, expect, afterEach } from "vitest"; + +function updateFileContent(content: string): void { + fileContent = content; +} + +let fileContent = ""; + +vi.mock("@clack/prompts", () => { + return { + log: { + info: vi.fn(), + success: vi.fn(), + }, + }; +}); + +vi.spyOn(fs.promises, "readFile").mockImplementation(() => + Promise.resolve(fileContent), +); + +const writeFileSpy = vi + .spyOn(fs.promises, "writeFile") + .mockImplementation(() => Promise.resolve(void 0)); + +describe("addVitePluginToConfig", () => { + afterEach(() => { + fileContent = ""; + vi.clearAllMocks(); + }); + + it.each([ + [ + "no build options", + ` +export default defineConfig({ + plugins: [ + vue(), + ], +}) +`, + `import { sentryVitePlugin } from "@sentry/bundler-plugins/vite"; +export default defineConfig({ + plugins: [vue(), sentryVitePlugin({ + org: "my-org", + project: "my-project" + })], + + build: { + sourcemap: true + } +}) +`, + ], + [ + "no build.sourcemap options", + ` +export default defineConfig({ + plugins: [ + vue(), + ], + build: { + test: 1, + } +}) +`, + `import { sentryVitePlugin } from "@sentry/bundler-plugins/vite"; +export default defineConfig({ + plugins: [vue(), sentryVitePlugin({ + org: "my-org", + project: "my-project" + })], + build: { + test: 1, + sourcemap: true + } +}) +`, + ], + [ + 'keep sourcemap: "hidden"', + ` +export default { + plugins: [ + vue(), + ], + build: { + sourcemap: "hidden", + } +} +`, + `import { sentryVitePlugin } from "@sentry/bundler-plugins/vite"; +export default { + plugins: [vue(), sentryVitePlugin({ + org: "my-org", + project: "my-project" + })], + build: { + sourcemap: "hidden", + } +} +`, + ], + [ + "rewrite sourcemap: false to true", + ` +const cfg = { + plugins: [ + vue(), + ], + build: { + sourcemap: false, + } +} + +export default cfg; +`, + `import { sentryVitePlugin } from "@sentry/bundler-plugins/vite"; +const cfg = { + plugins: [vue(), sentryVitePlugin({ + org: "my-org", + project: "my-project" + })], + + build: { + sourcemap: true, + } +} + +export default cfg; +`, + ], + ])( + "adds the plugin and enables source maps generation (%s)", + async (_, originalCode, expectedCode) => { + updateFileContent(originalCode); + + const addedCode = await addVitePluginToConfig( + "", + { + authToken: "", + orgSlug: "my-org", + projectSlug: "my-project", + selfHosted: false, + url: "https://sentry.io/", + }, + "@sentry/bundler-plugins/vite", + ); + + expect(writeFileSpy).toHaveBeenCalledTimes(1); + const fileContent = writeFileSpy.mock.calls[0]?.[1]; + expect(fileContent).toBe(expectedCode); + expect(addedCode).toBe(true); + }, + ); +}); diff --git a/packages/cli/test/lib/wizard/sourcemaps/tools/webpack.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/webpack.test.ts new file mode 100644 index 0000000000..b61d8108df --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/webpack.test.ts @@ -0,0 +1,313 @@ +import fs from "node:fs"; + +import { modifyWebpackConfig } from "../../../../../src/lib/wizard/sourcemaps/tools/webpack.js"; + +import { vi, it, expect, describe, afterEach } from "vitest"; + +function updateFileContent(content: string): void { + fileContent = content; +} + +let fileContent = ""; + +vi.mock("@clack/prompts", () => { + return { + log: { + info: vi.fn(), + success: vi.fn(), + }, + select: vi.fn().mockImplementation(() => Promise.resolve(true)), + isCancel: vi.fn().mockReturnValue(false), + }; +}); + +vi.spyOn(fs.promises, "readFile").mockImplementation(() => + Promise.resolve(fileContent), +); + +const writeFileSpy = vi + .spyOn(fs.promises, "writeFile") + .mockImplementation(() => Promise.resolve(void 0)); + +const noSourcemapNoPluginsPojo = `module.exports = { + entry: "./src/index.js", + output: { + filename: "main.js", + path: path.resolve(__dirname, "build"), + }, +};`; + +const noSourcemapNoPluginsPojoResult = `const { + sentryWebpackPlugin +} = require("@sentry/bundler-plugins/webpack"); + +module.exports = { + entry: "./src/index.js", + + output: { + filename: "main.js", + path: path.resolve(__dirname, "build"), + }, + + devtool: "source-map", + + plugins: [sentryWebpackPlugin({ + authToken: process.env.SENTRY_AUTH_TOKEN, + org: "my-org", + project: "my-project" + })] +};`; + +const noSourcemapsNoPluginsId = `const config = { + entry: "./src/index.js", + + output: { + filename: "main.js", + path: path.resolve(__dirname, "build"), + }, +}; + +module.exports = config;`; + +const noSourcemapsNoPluginsIdResult = `const { + sentryWebpackPlugin +} = require("@sentry/bundler-plugins/webpack"); + +const config = { + entry: "./src/index.js", + + output: { + filename: "main.js", + path: path.resolve(__dirname, "build"), + }, + + devtool: "source-map", + + plugins: [sentryWebpackPlugin({ + authToken: process.env.SENTRY_AUTH_TOKEN, + org: "my-org", + project: "my-project" + })] +}; + +module.exports = config;`; + +const hiddenSourcemapNoPluginsId = `const config = { + entry: "./src/index.js", + + output: { + filename: "main.js", + path: path.resolve(__dirname, "build"), + }, + + devtool: "hidden-cheap-source-map", +}; + +module.exports = config; + `; +const hiddenSourcemapNoPluginsIdResult = `const { + sentryWebpackPlugin +} = require("@sentry/bundler-plugins/webpack"); + +const config = { + entry: "./src/index.js", + + output: { + filename: "main.js", + path: path.resolve(__dirname, "build"), + }, + + devtool: "hidden-source-map", + + plugins: [sentryWebpackPlugin({ + authToken: process.env.SENTRY_AUTH_TOKEN, + org: "my-org", + project: "my-project" + })] +}; + +module.exports = config;`; + +const arbitrarySourcemapNoPluginsId = ` +const config = { + entry: "./src/index.js", + + output: { + filename: "main.js", + path: path.resolve(__dirname, "build"), + }, + + devtool: getSourcemapSetting(), +}; + +module.exports = config; + `; +const arbitrarySourcemapNoPluginsIdResult = `const { + sentryWebpackPlugin +} = require("@sentry/bundler-plugins/webpack"); + +const config = { + entry: "./src/index.js", + + output: { + filename: "main.js", + path: path.resolve(__dirname, "build"), + }, + + devtool: "source-map", + + plugins: [sentryWebpackPlugin({ + authToken: process.env.SENTRY_AUTH_TOKEN, + org: "my-org", + project: "my-project" + })] +}; + +module.exports = config;`; + +const noSourcemapUndefinedPluginsPojo = `module.exports = { + entry: "./src/index.js", + plugins: undefined, + output: { + filename: "main.js", + path: path.resolve(__dirname, "build"), + }, +};`; + +const noSourcemapUndefinedPluginsPojoResult = `const { + sentryWebpackPlugin +} = require("@sentry/bundler-plugins/webpack"); + +module.exports = { + entry: "./src/index.js", + + plugins: [sentryWebpackPlugin({ + authToken: process.env.SENTRY_AUTH_TOKEN, + org: "my-org", + project: "my-project" + })], + + output: { + filename: "main.js", + path: path.resolve(__dirname, "build"), + }, + + devtool: "source-map" +};`; + +const noSourcemapPluginsPojo = `module.exports = { + entry: "./src/index.js", + plugins: [ + new HtmlWebpackPlugin(), + new MiniCssExtractPlugin(), + ], + output: { + filename: "main.js", + path: path.resolve(__dirname, "build"), + }, +};`; + +const noSourcemapPluginsPojoResult = `const { + sentryWebpackPlugin +} = require("@sentry/bundler-plugins/webpack"); + +module.exports = { + entry: "./src/index.js", + + plugins: [new HtmlWebpackPlugin(), new MiniCssExtractPlugin(), sentryWebpackPlugin({ + authToken: process.env.SENTRY_AUTH_TOKEN, + org: "my-org", + project: "my-project" + })], + + output: { + filename: "main.js", + path: path.resolve(__dirname, "build"), + }, + + devtool: "source-map" +};`; + +describe("modifyWebpackConfig", () => { + afterEach(() => { + fileContent = ""; + vi.clearAllMocks(); + }); + + it.each([ + [ + "no sourcemap option, no plugins, object", + noSourcemapNoPluginsPojo, + noSourcemapNoPluginsPojoResult, + ], + [ + "no sourcemap option, no plugins, identifier", + noSourcemapsNoPluginsId, + noSourcemapsNoPluginsIdResult, + ], + [ + "hidden sourcemap option, no plugins, identifier", + hiddenSourcemapNoPluginsId, + hiddenSourcemapNoPluginsIdResult, + ], + [ + "arbitrary sourcemap option, no plugins, identifier", + arbitrarySourcemapNoPluginsId, + arbitrarySourcemapNoPluginsIdResult, + ], + [ + "no sourcemap option, plugins, object", + noSourcemapUndefinedPluginsPojo, + noSourcemapUndefinedPluginsPojoResult, + ], + [ + "no sourcemap option, plugins, object", + noSourcemapPluginsPojo, + noSourcemapPluginsPojoResult, + ], + ])( + "adds plugin and source maps emission to the webpack config (%s)", + async (_, originalCode, expectedCode) => { + updateFileContent(originalCode); + + // updateFileContent(originalCode); + const addedCode = await modifyWebpackConfig( + "", + { + authToken: "", + orgSlug: "my-org", + projectSlug: "my-project", + selfHosted: false, + url: "https://sentry.io/", + }, + "@sentry/bundler-plugins/webpack", + ); + + expect(writeFileSpy).toHaveBeenCalledTimes(1); + const fileContent = writeFileSpy.mock.calls[0]?.[1]; + expect(fileContent).toBe(expectedCode); + expect(addedCode).toBe(true); + }, + ); + + it("adds the url parameter to the webpack plugin options if self-hosted", async () => { + updateFileContent(noSourcemapNoPluginsPojo); + + const addedCode = await modifyWebpackConfig( + "", + { + authToken: "", + orgSlug: "my-org", + projectSlug: "my-project", + selfHosted: true, + url: "https://santry.io/", + }, + "@sentry/bundler-plugins/webpack", + ); + + expect(writeFileSpy).toHaveBeenCalledTimes(1); + const fileContent = writeFileSpy.mock.calls[0]?.[1]; + expect(fileContent).toContain('url: "https://santry.io/"'); + expect(addedCode).toBe(true); + }); +}); diff --git a/packages/cli/test/lib/wizard/sourcemaps/tools/wrangler.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/wrangler.test.ts new file mode 100644 index 0000000000..2ff8425af9 --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/wrangler.test.ts @@ -0,0 +1,320 @@ +import { + DIST_DIR, + findOutDir, + getSentryCliCommand, + getWranglerDeployCommand, + safeInsertArgsToWranglerDeployCommand, +} from "../../../../../src/lib/wizard/sourcemaps/tools/wrangler.js"; +import { describe, expect, it } from "vitest"; +import { execFileSync } from "node:child_process"; + +describe("getSentryCliCommand", () => { + it.each([ + "wrangler deploy --outdir 'dist$(printf${IFS}INJECTED)'", + "wrangler deploy --outdir='dist$(printf${IFS}INJECTED)'", + "wrangler deploy --outdir dist", + ])("passes the directory from %s literally to sentry", (deployCommand) => { + const outDir = findOutDir(deployCommand); + const command = getSentryCliCommand({ + selfHosted: false, + orgSlug: "myOrg", + projectSlug: "myProject", + url: "https://sentry.io", + authToken: "_ignore", + outDir, + }); + + expect(runSentryCliCommand(command)).toEqual([ + "release", + "create", + "release with spaces", + "--org=myOrg", + "--project=myProject", + "sourcemap", + "upload", + "--org=myOrg", + "--project=myProject", + "--release=release with spaces", + "--no-rewrite", + outDir, + ]); + }); + + it("preserves quotes and shell syntax in paths and self-hosted arguments", () => { + const outDir = "worker's dist;$(printf${IFS}INJECTED)"; + const url = "https://sentry.example/worker's"; + const orgSlug = "org$(printf${IFS}INJECTED)"; + const projectSlug = "project`printf INJECTED`"; + const command = getSentryCliCommand({ + selfHosted: true, + url, + orgSlug, + projectSlug, + authToken: "_ignore", + outDir, + }); + + expect(runSentryCliCommand(command)).toEqual([ + `SENTRY_URL=${url}`, + "release", + "create", + "release with spaces", + `--org=${orgSlug}`, + `--project=${projectSlug}`, + `SENTRY_URL=${url}`, + "sourcemap", + "upload", + `--org=${orgSlug}`, + `--project=${projectSlug}`, + "--release=release with spaces", + "--no-rewrite", + outDir, + ]); + }); + + it("returns correct command for SaaS", () => { + const command = getSentryCliCommand({ + selfHosted: false, + orgSlug: "myOrg", + projectSlug: "myProject", + url: "https://sentry.io", + authToken: "_ignore", + outDir: "dist", + }); + + expect(command).toBe( + "_SENTRY_RELEASE=$(sentry release propose-version | head -n 1) && sentry release create \"$_SENTRY_RELEASE\" --org='myOrg' --project='myProject' && sentry sourcemap upload --org='myOrg' --project='myProject' --release=\"$_SENTRY_RELEASE\" --no-rewrite 'dist'", + ); + }); + + it("returns correct command for self-hosted", () => { + const command = getSentryCliCommand({ + selfHosted: true, + orgSlug: "myOrg", + projectSlug: "myProject", + url: "https://santry.io", + authToken: "_ignore", + outDir: "someplace", + }); + + expect(command).toBe( + "_SENTRY_RELEASE=$(sentry release propose-version | head -n 1) && SENTRY_URL='https://santry.io' sentry release create \"$_SENTRY_RELEASE\" --org='myOrg' --project='myProject' && SENTRY_URL='https://santry.io' sentry sourcemap upload --org='myOrg' --project='myProject' --release=\"$_SENTRY_RELEASE\" --no-rewrite 'someplace'", + ); + }); +}); + +describe("safeInsertArgsToWranglerDeployCommand", () => { + it("correctly inserts args into default command", () => { + const newCommand = safeInsertArgsToWranglerDeployCommand( + "wrangler deploy", + "dist", + ); + + expect(newCommand).toBe( + "wrangler deploy --outdir 'dist' --upload-source-maps --var SENTRY_RELEASE:$(sentry release propose-version | head -n 1)", + ); + }); + + it.each([ + "--outdir someplace", + "--outdir=someplace", + '--outdir="./someplace.js"', + ])("retains existing %s arg", (arg) => { + const newCommand = safeInsertArgsToWranglerDeployCommand( + `wrangler deploy ${arg}`, + "dist", + ); + + expect(newCommand).toBe( + `wrangler deploy ${arg} --upload-source-maps --var SENTRY_RELEASE:$(sentry release propose-version | head -n 1)`, + ); + }); + + it.each([ + "--upload-source-maps", + "--upload-source-maps=true", + "--upload-source-maps true", + "--upload-source-maps=false", + "--upload-source-maps false", + ])("retains existing %s arg", (arg) => { + const newCommand = safeInsertArgsToWranglerDeployCommand( + `wrangler deploy ${arg}`, + "dist", + ); + + expect(newCommand).toBe( + `wrangler deploy ${arg} --outdir 'dist' --var SENTRY_RELEASE:$(sentry release propose-version | head -n 1)`, + ); + }); + + it('appends to the "wrangler deploy" command', () => { + const newCommand = safeInsertArgsToWranglerDeployCommand( + "precheck && wrangler deploy --outdir dist --upload-source-maps --var SOMEVAR:someValue && postcheck", + "dist", + ); + + expect(newCommand).toBe( + "precheck && wrangler deploy --outdir dist --upload-source-maps --var SOMEVAR:someValue --var SENTRY_RELEASE:$(sentry release propose-version | head -n 1) && postcheck", + ); + }); + + it("handles multiple wrangler commands", () => { + const newCommand = safeInsertArgsToWranglerDeployCommand( + "wrangler whoami && wrangler deploy --outdir dist --upload-source-maps --var SOMEVAR:someValue && wrangler someothercommand", + "dist", + ); + + expect(newCommand).toBe( + "wrangler whoami && wrangler deploy --outdir dist --upload-source-maps --var SOMEVAR:someValue --var SENTRY_RELEASE:$(sentry release propose-version | head -n 1) && wrangler someothercommand", + ); + }); + + it("handles wrangler deploy command with global args", () => { + const newCommand = safeInsertArgsToWranglerDeployCommand( + "wrangler --version --env production deploy --outdir someplace", + "dist", + ); + + expect(newCommand).toBe( + "wrangler --version --env production deploy --outdir someplace --upload-source-maps --var SENTRY_RELEASE:$(sentry release propose-version | head -n 1)", + ); + }); + + it("handles multiple commands and wrangler deploy command with global args", () => { + const newCommand = safeInsertArgsToWranglerDeployCommand( + "notwrangler --version deploy && wrangler --version --env whoami && wrangler --version --env production deploy --outdir someplace", + "dist", + ); + + expect(newCommand).toBe( + "notwrangler --version deploy && wrangler --version --env whoami && wrangler --version --env production deploy --outdir someplace --upload-source-maps --var SENTRY_RELEASE:$(sentry release propose-version | head -n 1)", + ); + }); + + it.each([ + "notwrangler deploy", + "wrangler dev", + "wrangler dev && notwrangler deploy", + "wrangler dev ; notwrangler deploy", + "wrangler dev; notwrangler deploy", + "wrangler dev ;notwrangler deploy", + "wrangler --env dev dev && notwrangler deploy", + "some completely different command", + ])("returns undefined if deploy command is not found", (command) => { + const newCommand = safeInsertArgsToWranglerDeployCommand(command, "dist"); + + expect(newCommand).toBeUndefined(); + }); +}); + +describe("findOutDir", () => { + it("returns dist dir if no outdir arg is found", () => { + const outDir = findOutDir("wrangler deploy"); + + expect(outDir).toBe(DIST_DIR); + }); + + it("returns outdir arg if it is found", () => { + const outDir = findOutDir("wrangler deploy --outdir someplace"); + + expect(outDir).toBe("someplace"); + }); + + it('handles --outdir "./someplace.js"', () => { + const outDir = findOutDir('wrangler deploy --outdir "./someplace.js"'); + + expect(outDir).toBe("./someplace.js"); + }); + + it("handles --outdir=someplace", () => { + const outDir = findOutDir("wrangler deploy --outdir=someplace"); + + expect(outDir).toBe("someplace"); + }); + + it("handles --outdir='./someplace.js'", () => { + const outDir = findOutDir('wrangler deploy --outdir="./someplace.js"'); + + expect(outDir).toBe("./someplace.js"); + }); + + it("returns dist dir if deploy command is not found", () => { + const outDir = findOutDir( + "wrangler --environment testing dev --outdir someplace", + ); + + expect(outDir).toBe(DIST_DIR); + }); +}); + +describe("getWranglerDeployCommand", () => { + it("returns the deploy command", () => { + const deployCommand = getWranglerDeployCommand( + "wrangler deploy --outdir someplace", + ); + + expect(deployCommand).toBe("wrangler deploy --outdir someplace"); + }); + + it("keeps the release version pipe inside the deploy command", () => { + const deployCommand = safeInsertArgsToWranglerDeployCommand( + "wrangler deploy && postcheck", + "dist", + ); + + const rerunDeployCommand = getWranglerDeployCommand(deployCommand ?? ""); + + expect(rerunDeployCommand?.replace(/\s+/g, " ").trim()).toBe( + "wrangler deploy --outdir 'dist' --upload-source-maps --var SENTRY_RELEASE:$(sentry release propose-version | head -n 1)", + ); + }); + + it("returns undefined if deploy command is not found", () => { + const deployCommand = getWranglerDeployCommand( + "wrangler --environment testing dev --outdir someplace", + ); + + expect(deployCommand).toBeUndefined(); + }); + + it.each([ + "wrangler deploy --outdir someplace && some other command", + "wrangler deploy --outdir someplace || some other command", + "wrangler deploy --outdir someplace ; some other command", + "wrangler deploy --outdir someplace && some other command || some other command", + "yarn precheck && wrangler deploy --outdir someplace && some other command", + "yarn precheck || wrangler deploy --outdir someplace && some other command", + "npm run test; wrangler deploy --outdir someplace && some other command", + "npm run test; wrangler version > text && wrangler deploy --outdir someplace && some other command", + "wrangler deploy --outdir someplace > deployment.txt", + ])("returns the deploy command for `%s`", (command) => { + const deployCommand = getWranglerDeployCommand(command)?.trim(); + + expect(deployCommand).toBe("wrangler deploy --outdir someplace"); + }); +}); + +// Print the release and upload arguments instead of running the Sentry CLI. +// The `sentry` shell function shadows any `sentry` binary on PATH, so the +// script never reaches Sentry. `propose-version` prints a hint after the +// version, as `sentry` does when its output is piped. Command substitution +// payloads use printf so a quoting regression has no filesystem side effects. +function runSentryCliCommand(command: string): string[] { + const script = ` +sentry() { + case "$1 $2" in + 'release propose-version') printf '%s\\n' 'release with spaces' 'Detected from git HEAD' ;; + 'release create' | 'sourcemap upload') + if [ -n "$SENTRY_URL" ]; then + printf '%s\\n' "SENTRY_URL=$SENTRY_URL" + fi + printf '%s\\n' "$@" + ;; + esac +} +unset SENTRY_URL +${command}`; + return execFileSync("/bin/bash", ["-c", script], { encoding: "utf8" }) + .trimEnd() + .split("\n"); +} diff --git a/packages/cli/test/lib/wizard/sourcemaps/utils/bundler-plugin.test.ts b/packages/cli/test/lib/wizard/sourcemaps/utils/bundler-plugin.test.ts new file mode 100644 index 0000000000..ff9103a04e --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/utils/bundler-plugin.test.ts @@ -0,0 +1,166 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + getPackageDotJson: vi.fn(), + installPackage: vi.fn(), + printSdkV11MigrationGuideIfOutdated: vi.fn(), + setTag: vi.fn(), +})); + +vi.mock("../../../../../src/lib/wizard/utils/clack/index.js", () => ({ + getPackageDotJson: mocks.getPackageDotJson, + installPackage: mocks.installPackage, + printSdkV11MigrationGuideIfOutdated: + mocks.printSdkV11MigrationGuideIfOutdated, +})); + +vi.mock("../../../../../src/lib/wizard/telemetry.js", () => ({ + Sentry: { setTag: mocks.setTag }, +})); + +import { ensureBundlerPlugin } from "../../../../../src/lib/wizard/sourcemaps/utils/bundler-plugin.js"; + +type Deps = Record; + +function mockPackageJson(before: Deps, after: Deps = before) { + mocks.getPackageDotJson + .mockResolvedValueOnce({ dependencies: before }) + .mockResolvedValueOnce({ dependencies: after }); +} + +describe("ensureBundlerPlugin", () => { + beforeEach(() => { + vi.clearAllMocks(); + // Drop queued once-values left over from tests that read package.json + // only once. + mocks.getPackageDotJson.mockReset(); + mocks.installPackage.mockResolvedValue({}); + }); + + it("installs @sentry/bundler-plugins as a dev dependency when no SDK ships the plugin", async () => { + mockPackageJson({ "@sentry/browser": "^11.0.0" }); + + const importPath = await ensureBundlerPlugin("vite"); + + expect(importPath).toBe("@sentry/bundler-plugins/vite"); + expect(mocks.installPackage).toHaveBeenCalledTimes(1); + expect(mocks.installPackage).toHaveBeenCalledWith({ + packageName: "@sentry/bundler-plugins@^11", + packageNameDisplayLabel: "@sentry/bundler-plugins", + alreadyInstalled: false, + devDependency: true, + }); + expect(mocks.setTag).toHaveBeenCalledWith( + "bundler-plugin-source", + "bundler-plugins", + ); + }); + + it("marks @sentry/bundler-plugins as already installed", async () => { + mockPackageJson({ "@sentry/bundler-plugins": "^11.0.0" }); + + await ensureBundlerPlugin("rollup"); + + expect(mocks.installPackage).toHaveBeenCalledWith( + expect.objectContaining({ + packageName: "@sentry/bundler-plugins@^11", + alreadyInstalled: true, + }), + ); + }); + + it.each(["vite", "webpack", "rollup", "esbuild"] as const)( + "imports the %s plugin from @sentry/node when it is installed at v11", + async (bundler) => { + mockPackageJson({ "@sentry/node": "^11.0.0" }); + + const importPath = await ensureBundlerPlugin(bundler); + + expect(importPath).toBe(`@sentry/node/${bundler}`); + expect(mocks.installPackage).toHaveBeenCalledTimes(1); + expect(mocks.installPackage).toHaveBeenCalledWith({ + packageName: "@sentry/node@^11", + packageNameDisplayLabel: "@sentry/node", + alreadyInstalled: true, + }); + expect(mocks.setTag).toHaveBeenCalledWith("bundler-plugin-source", "sdk"); + }, + ); + + it("updates an outdated SDK and imports from it after the update", async () => { + mockPackageJson( + { "@sentry/node": "^9.0.0" }, + { "@sentry/node": "^11.10.0" }, + ); + + const importPath = await ensureBundlerPlugin("vite"); + + expect(mocks.printSdkV11MigrationGuideIfOutdated).toHaveBeenCalledWith( + "@sentry/node", + { dependencies: { "@sentry/node": "^9.0.0" } }, + ); + expect(importPath).toBe("@sentry/node/vite"); + }); + + it("falls back to @sentry/bundler-plugins when the SDK update is declined", async () => { + mockPackageJson({ "@sentry/node": "^9.0.0" }); + + const importPath = await ensureBundlerPlugin("vite"); + + expect(importPath).toBe("@sentry/bundler-plugins/vite"); + expect(mocks.installPackage).toHaveBeenCalledTimes(2); + expect(mocks.installPackage).toHaveBeenLastCalledWith( + expect.objectContaining({ + packageName: "@sentry/bundler-plugins@^11", + devDependency: true, + }), + ); + }); + + it("imports the webpack plugin from @sentry/nestjs", async () => { + mockPackageJson({ + "@sentry/nestjs": "^11.10.0", + "@sentry/node": "^11.10.0", + }); + + const importPath = await ensureBundlerPlugin("webpack"); + + expect(importPath).toBe("@sentry/nestjs/webpack"); + }); + + it("falls back when @sentry/nestjs stays on a version without the webpack subpath", async () => { + mockPackageJson({ "@sentry/nestjs": "^11.5.0" }); + + const importPath = await ensureBundlerPlugin("webpack"); + + expect(importPath).toBe("@sentry/bundler-plugins/webpack"); + }); + + it("uses @sentry/node for bundlers that @sentry/nestjs does not ship", async () => { + mockPackageJson({ + "@sentry/nestjs": "^11.10.0", + "@sentry/node": "^11.10.0", + }); + + const importPath = await ensureBundlerPlugin("vite"); + + expect(importPath).toBe("@sentry/node/vite"); + }); + + it("installs @sentry/bundler-plugins for bundlers the installed SDK does not ship", async () => { + mockPackageJson({ "@sentry/aws-serverless": "^11.10.0" }); + + const importPath = await ensureBundlerPlugin("vite"); + + expect(importPath).toBe("@sentry/bundler-plugins/vite"); + expect(mocks.installPackage).toHaveBeenCalledTimes(1); + }); + + it("imports the esbuild plugin from @sentry/aws-serverless", async () => { + mockPackageJson({ "@sentry/aws-serverless": "^11.10.0" }); + + const importPath = await ensureBundlerPlugin("esbuild"); + + expect(importPath).toBe("@sentry/aws-serverless/esbuild"); + }); +}); diff --git a/packages/cli/test/lib/wizard/sourcemaps/utils/sdk-version.test.ts b/packages/cli/test/lib/wizard/sourcemaps/utils/sdk-version.test.ts new file mode 100644 index 0000000000..b8aec8ebd6 --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/utils/sdk-version.test.ts @@ -0,0 +1,64 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const clackMocks = vi.hoisted(() => ({ + warn: vi.fn(), + info: vi.fn(), + select: vi.fn(), + getPackageDotJson: vi.fn(), +})); + +vi.mock("@clack/prompts", () => ({ + log: { + warn: clackMocks.warn, + info: clackMocks.info, + }, + select: clackMocks.select, +})); + +vi.mock("../../../../../src/lib/wizard/utils/clack/index.js", () => ({ + abortIfCancelled: vi.fn((v: unknown) => v), + getPackageDotJson: clackMocks.getPackageDotJson, + installPackage: vi.fn(), +})); + +import { ensureMinimumSdkVersionIsInstalled } from "../../../../../src/lib/wizard/sourcemaps/utils/sdk-version.js"; + +describe("ensureMinimumSdkVersionIsInstalled", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it.each([ + "11.0.0-beta.2", + "^11.0.0-beta.2", + "11.0.0-rc.1", + "8.0.0-alpha.1", + "10.74.0", + "^7.47.0", + ])("does not warn for SDK version %s", async (version) => { + clackMocks.getPackageDotJson.mockResolvedValue({ + dependencies: { "@sentry/browser": version }, + }); + + await ensureMinimumSdkVersionIsInstalled(); + + expect(clackMocks.warn).not.toHaveBeenCalled(); + expect(clackMocks.select).not.toHaveBeenCalled(); + }); + + it.each(["7.46.0", "^7.0.0", "6.19.7"])( + "warns for outdated SDK version %s", + async (version) => { + clackMocks.getPackageDotJson.mockResolvedValue({ + dependencies: { "@sentry/browser": version }, + }); + clackMocks.select.mockResolvedValue(false); + + await ensureMinimumSdkVersionIsInstalled(); + + expect(clackMocks.warn).toHaveBeenCalledWith( + expect.stringContaining("outdated version"), + ); + }, + ); +}); diff --git a/packages/cli/test/tsconfig.json b/packages/cli/test/tsconfig.json index 07b7248608..b626e81b70 100644 --- a/packages/cli/test/tsconfig.json +++ b/packages/cli/test/tsconfig.json @@ -3,5 +3,6 @@ "compilerOptions": { "lib": ["ESNext", "DOM"] }, - "include": ["**/*.ts", "**/*.tsx"] + "include": ["**/*.ts", "**/*.tsx"], + "exclude": ["lib/wizard/**/fixtures/**"] } From 94377dfb9661efeec352d1adcdfbd448c94f0847 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:29:17 +0000 Subject: [PATCH 05/20] feat(cli): read wizard source map upload target from .sentryclirc Generated `sentry` commands no longer pass the hidden `--org` and `--project` compat flags. The generic and Wrangler source maps flows merge `org` and `project` into the project's `.sentryclirc` `[defaults]`, next to the existing `[auth] token` and any other keys, and v4 reads them from there. Wrangler's `sentry:sourcemaps` script drops the `SENTRY_URL=` prefix and the flags from `sentry release create` and `sentry sourcemap upload`. The self-hosted URL is not written to the file. v4 only trusts a non-SaaS `[defaults] url` when the token's host or a stored login vouches for it, and a token from the same file does not, so the upload would be refused. Self-hosted users are told to set `SENTRY_URL` instead. `setupCI` gets the upload target, so the CI step lists `SENTRY_AUTH_TOKEN`, `SENTRY_ORG`, `SENTRY_PROJECT` and, for self-hosted, `SENTRY_URL`. Wrangler counts as a `sentry`-command tool there (its token lives in `.sentryclirc`), but skips the "run the script in CI" prompt, since its `post` script already runs it. `sentry@^4` is installed as a devDependency. `sourcemaps/ci.ts`, `sourcemaps/tools/sentry-cli.ts`, `angular.ts`, `types.ts` and `abort-if-sportlight-not-supported.ts` now match getsentry/toolkit#2525, apart from exporting `addOrgAndProjectToSentryCliRc` for Wrangler, the devDependency install, and the Wrangler CI case. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .../cli-docs/src/fragments/commands/wizard.md | 9 + packages/cli/src/lib/wizard/sourcemaps/ci.ts | 4 +- .../wizard/sourcemaps/sourcemaps-wizard.ts | 8 +- .../lib/wizard/sourcemaps/tools/angular.ts | 9 +- .../lib/wizard/sourcemaps/tools/sentry-cli.ts | 206 ++++++++++++++---- .../src/lib/wizard/sourcemaps/tools/types.ts | 2 +- .../lib/wizard/sourcemaps/tools/wrangler.ts | 54 ++--- .../abort-if-sportlight-not-supported.ts | 2 +- .../lib/wizard/sourcemaps/ci-setup.test.ts | 83 +++++++ .../cli/test/lib/wizard/sourcemaps/ci.test.ts | 34 +++ .../sourcemaps/tools/sentry-cli.test.ts | 86 ++++++-- .../tools/sentryclirc-defaults.test.ts | 109 +++++++++ .../sourcemaps/tools/sentryclirc-file.test.ts | 109 +++++++++ .../wizard/sourcemaps/tools/wrangler.test.ts | 73 +------ 14 files changed, 626 insertions(+), 162 deletions(-) create mode 100644 packages/cli/test/lib/wizard/sourcemaps/ci-setup.test.ts create mode 100644 packages/cli/test/lib/wizard/sourcemaps/ci.test.ts create mode 100644 packages/cli/test/lib/wizard/sourcemaps/tools/sentryclirc-defaults.test.ts create mode 100644 packages/cli/test/lib/wizard/sourcemaps/tools/sentryclirc-file.test.ts diff --git a/apps/cli-docs/src/fragments/commands/wizard.md b/apps/cli-docs/src/fragments/commands/wizard.md index d754b8845b..c36fcb7ffc 100644 --- a/apps/cli-docs/src/fragments/commands/wizard.md +++ b/apps/cli-docs/src/fragments/commands/wizard.md @@ -27,3 +27,12 @@ changes nothing. promo code there), then run the wizard. - The Cordova and Electron wizards. 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 inject` and `sentry sourcemap upload` +on your build output. The wizard writes your org and project 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`, +`SENTRY_ORG` and `SENTRY_PROJECT` instead. On self-hosted Sentry, also set +`SENTRY_URL` wherever that script runs. diff --git a/packages/cli/src/lib/wizard/sourcemaps/ci.ts b/packages/cli/src/lib/wizard/sourcemaps/ci.ts index 04e5ff1ce6..863416c1d1 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/ci.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/ci.ts @@ -21,6 +21,7 @@ const CLI_BASED_FLOW_TOOLS: readonly string[] = [ "tsc", "angular", "create-react-app", + "wrangler", ]; /** @@ -95,7 +96,8 @@ async function configureCI( return; } - if (isCliBasedFlowTool) { + // Wrangler's `post` script already runs `sentry:sourcemaps` + if (isCliBasedFlowTool && selectedTool !== "wrangler") { await traceStep("ci-npm-script-setup", setupNpmScriptInCI); } diff --git a/packages/cli/src/lib/wizard/sourcemaps/sourcemaps-wizard.ts b/packages/cli/src/lib/wizard/sourcemaps/sourcemaps-wizard.ts index 33f1546f03..dc8f864fd7 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/sourcemaps-wizard.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/sourcemaps-wizard.ts @@ -125,7 +125,13 @@ Thank you for using Sentry :)`, ), ); - await traceStep("ci-setup", () => setupCI(selectedTool, authToken)); + await traceStep("ci-setup", () => + setupCI(selectedTool, authToken, { + org: selectedProject.organization.slug, + project: selectedProject.slug, + url: selfHosted ? sentryUrl : undefined, + }), + ); if (!preSelectedTool) { // running prettier is only necessary if the source maps wizard is the main flow diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/angular.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/angular.ts index 5e757e02c7..0a5a2485d3 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/tools/angular.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/angular.ts @@ -1,12 +1,13 @@ /** - * Source map generation step for Angular: ask the user to turn on - * `sourceMap` in `angular.json`. + * 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"; -import { clack } from "../../utils/clack/prompts.js"; +/** The `angular.json` change that turns on source maps. */ const angularJsonTemplate = makeCodeSnippet(true, (unchanged, plus) => unchanged(`{ "projects": { @@ -23,7 +24,7 @@ const angularJsonTemplate = makeCodeSnippet(true, (unchanged, plus) => }`), ); -/** Show the `angular.json` change and wait until the user made it. */ +/** 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:`, diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts index fc56d36a4d..9eda726ab5 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts @@ -1,16 +1,22 @@ /** - * Source maps setup for projects without a supported bundler plugin: install - * the `sentry` CLI and add a `sentry:sourcemaps` npm script that injects - * debug IDs into the build output and uploads it. + * Source map upload with `sentry` commands, for build tools that have no + * Sentry bundler plugin (Angular, tsc, Create React App, …). * - * sentry-wizard installed `@sentry/cli@^2` and wrote `sentry-cli sourcemaps - * inject/upload` scripts. These are the v4 `sentry sourcemap` commands. + * Installs the `sentry` CLI package, adds a `sentry:sourcemaps` npm script + * that runs `sentry sourcemap inject` and `sentry sourcemap upload` on the + * build output, optionally appends it to the production build script, and + * writes the org, project, and auth token to `.sentryclirc`. v4 reads that + * file: `[defaults]` feeds org/project 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 chalk from "chalk"; -import { promises } from "node:fs"; +import { existsSync, promises, readFileSync } from "node:fs"; import path from "node:path"; - +import chalk from "chalk"; import { Sentry, traceStep } from "../../telemetry.js"; import { abortIfCancelled, @@ -20,46 +26,43 @@ import { 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"; -/** The npm package of the `sentry` CLI. */ -export const SENTRY_CLI_PACKAGE = "sentry"; - -/** The `sentry` CLI major the generated scripts are written for. */ -export const SENTRY_CLI_PACKAGE_RANGE = `${SENTRY_CLI_PACKAGE}@^4`; - const SENTRY_NPM_SCRIPT_NAME = "sentry:sourcemaps"; let addedToBuildCommand = false; -type ConfigureSentryCLIOptions = SourceMapUploadToolConfigurationOptions & { +type configureSentryCLIOptions = SourceMapUploadToolConfigurationOptions & { defaultArtifactPath?: string | undefined; }; /** - * Install the `sentry` CLI, ask for the build output directory, and add the - * `sentry:sourcemaps` script (optionally to the production build command). + * Set up source map upload with `sentry sourcemap` commands. * - * @param configureSourcemapGenerationFlow - Tool-specific step that makes - * sure the build emits source maps - * @param skipValidation - Skip `configureSourcemapGenerationFlow`, for - * callers (the Angular wizard) that already configured it + * @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, + options: configureSentryCLIOptions, configureSourcemapGenerationFlow: () => Promise = defaultConfigureSourcemapGenerationFlow, skipValidation = false, ): Promise { const packageDotJson = await getPackageDotJson(); await installPackage({ - packageName: SENTRY_CLI_PACKAGE_RANGE, - packageNameDisplayLabel: SENTRY_CLI_PACKAGE, - alreadyInstalled: hasPackageInstalled(SENTRY_CLI_PACKAGE, packageDotJson), + packageName: "sentry@^4", + alreadyInstalled: hasPackageInstalled("sentry", packageDotJson), + devDependency: true, }); let validPath = false; @@ -114,7 +117,7 @@ export async function configureSentryCLI( await configureSourcemapGenerationFlow(); } - await createAndAddNpmScript(options, relativePosixArtifactPath); + await createAndAddNpmScript(relativePosixArtifactPath); if (await askShouldAddToBuildCommand()) { await traceStep("sentry-cli-add-to-build-cmd", () => @@ -128,12 +131,21 @@ export async function configureSentryCLI( ); } + await addOrgAndProjectToSentryCliRc(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 added it to the build command. + * wizard already appended it to the build script. */ export async function setupNpmScriptInCI(): Promise { if (addedToBuildCommand) { @@ -172,29 +184,136 @@ export async function setupNpmScriptInCI(): Promise { /** * The `sentry:sourcemaps` script: inject debug IDs into the build output, - * then upload it. A self-hosted URL goes in `SENTRY_URL`, which replaced - * the `--url` flag of sentry-cli. + * then upload it. `sentry sourcemap upload` reads the org and project from + * `.sentryclirc` locally and from `SENTRY_ORG` / `SENTRY_PROJECT` in CI, and + * the self-hosted URL from `SENTRY_URL`. */ export function getSentryCliNpmScript( - options: SourceMapUploadToolConfigurationOptions, relativePosixArtifactPath: string, ): string { - const urlEnv = options.selfHosted ? `SENTRY_URL=${options.url} ` : ""; - // oxlint-disable-next-line sentry-cli/no-hardcoded-sentry-command -- runs the project's installed `sentry` package from its package.json scripts, not a hint - return `sentry sourcemap inject ${relativePosixArtifactPath} && ${urlEnv}sentry sourcemap upload --org ${options.orgSlug} --project ${options.projectSlug} ${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 inject ${relativePosixArtifactPath} && sentry sourcemap upload ${relativePosixArtifactPath}`; } -async function createAndAddNpmScript( +/** 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; + + lines.forEach((line, index) => { + const section = INI_SECTION_RE.exec(line); + if (section) { + inDefaults = section[1]?.trim().toLowerCase() === "defaults"; + if (inDefaults && firstDefaultsHeader === -1) { + firstDefaultsHeader = index; + } + return; + } + 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 and project to the project's `.sentryclirc`, so that + * `sentry sourcemap upload` finds them when the script runs locally. + * + * The self-hosted URL stays out of the file. v4 refuses a non-SaaS + * `[defaults] url` unless the token's host or a stored login vouches for it, + * and the `[auth] token` from the same file doesn't (see + * `assertRcUrlTrusted`), so users set `SENTRY_URL` instead. + */ +export async function addOrgAndProjectToSentryCliRc( 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, + }), + ); + } 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] = getSentryCliNpmScript( - options, - relativePosixArtifactPath, - ); + packageDotJson.scripts[SENTRY_NPM_SCRIPT_NAME] = sentryCliNpmScript; await promises.writeFile( path.join(process.cwd(), "package.json"), @@ -235,15 +354,16 @@ async function askShouldAddToBuildCommand(): Promise { * 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 scripts = packageDotJson.scripts; - const allNpmScripts = Object.keys(scripts).filter( + const allNpmScripts = Object.keys(packageDotJson.scripts).filter( (s) => s !== SENTRY_NPM_SCRIPT_NAME, ); @@ -253,7 +373,7 @@ export async function addSentryCommandToBuildCommand(): Promise { // 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 scripts["build"] === "string" + typeof packageDotJson.scripts["build"] === "string" ? "build" : allNpmScripts.find((s) => s.toLocaleLowerCase().includes("build")); @@ -294,7 +414,7 @@ Please add it manually to your prod build command.`, return; } - const oldCommand = scripts[buildCommand]; + const oldCommand = packageDotJson.scripts[buildCommand]; if (!oldCommand) { // very unlikely to happen but nevertheless clack.log.warn( @@ -319,7 +439,7 @@ Would have injected: ${chalk.dim(newCommand)}`, return; } - scripts[buildCommand] = newCommand; + packageDotJson.scripts[buildCommand] = newCommand; await promises.writeFile( path.join(process.cwd(), "package.json"), diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/types.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/types.ts index e6fe4d4689..a36ff55e94 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/tools/types.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/types.ts @@ -1,5 +1,5 @@ /** - * Options every source maps upload tool setup takes. + * Options the source map upload tool setups take. */ export type SourceMapUploadToolConfigurationOptions = { diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/wrangler.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/wrangler.ts index 8cd439ebd6..2e94763490 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/tools/wrangler.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/wrangler.ts @@ -5,7 +5,8 @@ * * sentry-wizard installed `@sentry/cli@^2` and called `sentry-cli releases * propose-version/new` and `sentry-cli sourcemaps upload`. These are the v4 - * `sentry release` and `sentry sourcemap` commands. + * `sentry release` and `sentry sourcemap` commands, which read the org and + * project from `.sentryclirc`. */ import chalk from "chalk"; @@ -24,7 +25,7 @@ import { import { clack } from "../../utils/clack/prompts.js"; import { hasPackageInstalled } from "../../utils/package-json.js"; import { NPM } from "../../utils/package-manager.js"; -import { SENTRY_CLI_PACKAGE, SENTRY_CLI_PACKAGE_RANGE } from "./sentry-cli.js"; +import { addOrgAndProjectToSentryCliRc } from "./sentry-cli.js"; import type { SourceMapUploadToolConfigurationOptions } from "./types.js"; const SENTRY_NPM_SCRIPT_NAME = "sentry:sourcemaps"; @@ -74,12 +75,8 @@ Otherwise, let's proceed with the Wrangler setup.`, } await installPackage({ - packageName: SENTRY_CLI_PACKAGE_RANGE, - packageNameDisplayLabel: SENTRY_CLI_PACKAGE, - alreadyInstalled: hasPackageInstalled( - SENTRY_CLI_PACKAGE, - await getPackageDotJson(), - ), + packageName: "sentry@^4", + alreadyInstalled: hasPackageInstalled("sentry", await getPackageDotJson()), devDependency: true, }); @@ -94,21 +91,30 @@ Otherwise, let's proceed with the Wrangler setup.`, const outDir = await getWranglerOutDir(deployCommand); - await createAndAddSentrySourcemapsScript({ ...options, outDir }); + await createAndAddSentrySourcemapsScript(outDir); await writePostDeployCommand(deployCommand); await modifyDeployCommand(deployCommand, outDir); + await addOrgAndProjectToSentryCliRc(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.`, + ); + } } async function createAndAddSentrySourcemapsScript( - options: SourceMapUploadToolConfigurationOptions & { outDir: string }, -) { + outDir: string, +): Promise { const pkgJson = await getPackageDotJson(); pkgJson.scripts = pkgJson.scripts ?? {}; - pkgJson.scripts[SENTRY_NPM_SCRIPT_NAME] = getSentryCliCommand(options); + pkgJson.scripts[SENTRY_NPM_SCRIPT_NAME] = getSentryCliCommand(outDir); await promises.writeFile( path.join(process.cwd(), "package.json"), @@ -134,26 +140,20 @@ const PROPOSE_VERSION = "$(sentry release propose-version | head -n 1)"; * The `sentry:sourcemaps` script: create the release and upload the deploy * output for it. The output is uploaded as deployed (`--no-rewrite`): the * worker was already deployed without debug IDs, so the files are matched - * by release and URL, as with sentry-cli. + * by release and URL, as with sentry-cli. The org and project come from + * `.sentryclirc` (or `SENTRY_ORG` and `SENTRY_PROJECT` in CI), and a + * self-hosted URL from `SENTRY_URL`. * * only exported for testing */ -export function getSentryCliCommand( - options: SourceMapUploadToolConfigurationOptions & { outDir: string }, -): string { - // `SENTRY_URL` replaced the `--url` flag of sentry-cli - const urlEnv = options.selfHosted - ? `SENTRY_URL=${quoteShellArg(options.url)} ` - : ""; - const orgAndProjectArgs = `--org=${quoteShellArg( - options.orgSlug, - )} --project=${quoteShellArg(options.projectSlug)}`; - +export function getSentryCliCommand(outDir: string): string { return [ `_SENTRY_RELEASE=${PROPOSE_VERSION}`, - `${urlEnv}sentry release create "$_SENTRY_RELEASE" ${orgAndProjectArgs}`, - `${urlEnv}sentry sourcemap upload ${orgAndProjectArgs} --release="$_SENTRY_RELEASE" --no-rewrite ${quoteShellArg( - options.outDir, + // oxlint-disable-next-line sentry-cli/no-hardcoded-sentry-command -- a package.json script, not a hint + 'sentry release create "$_SENTRY_RELEASE"', + // oxlint-disable-next-line sentry-cli/no-hardcoded-sentry-command -- a package.json script, not a hint + `sentry sourcemap upload --release="$_SENTRY_RELEASE" --no-rewrite ${quoteShellArg( + outDir, )}`, ].join(" && "); } diff --git a/packages/cli/src/lib/wizard/utils/abort-if-sportlight-not-supported.ts b/packages/cli/src/lib/wizard/utils/abort-if-sportlight-not-supported.ts index 3f612e0f0b..0aed208bf2 100644 --- a/packages/cli/src/lib/wizard/utils/abort-if-sportlight-not-supported.ts +++ b/packages/cli/src/lib/wizard/utils/abort-if-sportlight-not-supported.ts @@ -1,5 +1,5 @@ /** - * Stop a wizard that has no Spotlight (`--spotlight`) mode yet. + * Stop a wizard flow that has no Spotlight mode yet. */ import { abort } from "./clack/index.js"; diff --git a/packages/cli/test/lib/wizard/sourcemaps/ci-setup.test.ts b/packages/cli/test/lib/wizard/sourcemaps/ci-setup.test.ts new file mode 100644 index 0000000000..23c2a65718 --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/ci-setup.test.ts @@ -0,0 +1,83 @@ +/** + * `setupCI` for the tools that upload with `sentry` commands: which prompts + * it shows and which environment variables it tells the user to set in CI. + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const { clackMocks } = vi.hoisted(() => ({ + clackMocks: { + select: vi.fn(), + isCancel: vi.fn(() => false), + log: { + info: vi.fn(), + step: vi.fn(), + success: vi.fn(), + warn: vi.fn(), + }, + }, +})); + +vi.mock("@clack/prompts", () => clackMocks); + +import { setupCI } from "../../../../src/lib/wizard/sourcemaps/ci.js"; + +let stdout: string; + +beforeEach(() => { + stdout = ""; + vi.spyOn(process.stdout, "write").mockImplementation((chunk) => { + stdout += String(chunk); + return true; + }); + // Every select answers "yes": using CI, added the script, configured CI + clackMocks.select.mockResolvedValue(true); +}); + +afterEach(() => { + vi.restoreAllMocks(); + vi.clearAllMocks(); +}); + +const uploadTarget = { org: "my-org", project: "my-project" }; + +describe("setupCI", () => { + it("names the auth token, org and project for Wrangler", async () => { + await setupCI("wrangler", "sntrys_tok", uploadTarget); + + expect(stdout).toContain("SENTRY_AUTH_TOKEN=sntrys_tok"); + expect(stdout).toContain("SENTRY_ORG=my-org"); + expect(stdout).toContain("SENTRY_PROJECT=my-project"); + expect(stdout).not.toContain("SENTRY_URL"); + }); + + it("adds SENTRY_URL for self-hosted Sentry", async () => { + await setupCI("wrangler", "sntrys_tok", { + ...uploadTarget, + url: "https://sentry.example.com/", + }); + + expect(stdout).toContain("SENTRY_URL=https://sentry.example.com/"); + }); + + it("does not ask to add the upload script to CI for Wrangler, whose post-deploy script runs it", async () => { + await setupCI("wrangler", "sntrys_tok", uploadTarget); + + // "Using CI?" and "Configured CI?" only + expect(clackMocks.select).toHaveBeenCalledTimes(2); + }); + + it("asks to add the upload script to CI for the generic flow", async () => { + await setupCI("sentry-cli", "sntrys_tok", uploadTarget); + + expect(clackMocks.select).toHaveBeenCalledTimes(3); + expect(stdout).toContain("SENTRY_ORG=my-org"); + }); + + it("names only the auth token for bundler plugins", async () => { + await setupCI("vite", "sntrys_tok", uploadTarget); + + expect(stdout).toContain("SENTRY_AUTH_TOKEN=sntrys_tok"); + expect(stdout).not.toContain("SENTRY_ORG"); + }); +}); 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 0000000000..2b80dfd59b --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/ci.test.ts @@ -0,0 +1,34 @@ +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("adds the org and project for sentry.io", () => { + expect( + getCIEnvVars("tok", { org: "my-org", project: "my-project" }), + ).toEqual([ + "SENTRY_AUTH_TOKEN=tok", + "SENTRY_ORG=my-org", + "SENTRY_PROJECT=my-project", + ]); + }); + + it("adds SENTRY_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/sentry-cli.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/sentry-cli.test.ts index ef40a9f22e..22bea7aa46 100644 --- a/packages/cli/test/lib/wizard/sourcemaps/tools/sentry-cli.test.ts +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/sentry-cli.test.ts @@ -1,8 +1,9 @@ -import fs from "node:fs"; +import { promises } from "node:fs"; import { addSentryCommandToBuildCommand, getSentryCliNpmScript, + setSentryCliRcDefaults, } from "../../../../../src/lib/wizard/sourcemaps/tools/sentry-cli.js"; // oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking @@ -12,7 +13,7 @@ import { getPackageDotJson } from "../../../../../src/lib/wizard/utils/clack/ind import { vi, it, describe, expect, afterEach } from "vitest"; const writeFileSpy = vi - .spyOn(fs.promises, "writeFile") + .spyOn(promises, "writeFile") .mockImplementation(() => Promise.resolve()); vi.mock("@clack/prompts", () => { @@ -25,7 +26,6 @@ vi.mock("@clack/prompts", () => { 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", @@ -79,28 +79,78 @@ describe("addSentryCommandToBuildCommand", () => { }); describe("getSentryCliNpmScript", () => { - const options = { - orgSlug: "my-org", - projectSlug: "my-project", - url: "https://sentry.io", - selfHosted: false, - authToken: "_ignore", - }; + it("injects debug IDs and uploads with v4 sentry commands, without org or project flags", () => { + expect(getSentryCliNpmScript("./dist")).toBe( + "sentry sourcemap inject ./dist && sentry sourcemap upload ./dist", + ); + }); +}); + +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("injects debug IDs and uploads the build output", () => { - expect(getSentryCliNpmScript(options, "./dist")).toBe( - "sentry sourcemap inject ./dist && sentry sourcemap upload --org my-org --project my-project ./dist", + 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("passes a self-hosted URL in SENTRY_URL", () => { + 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( - getSentryCliNpmScript( - { ...options, selfHosted: true, url: "https://sentry.example.com" }, - "./dist", + setSentryCliRcDefaults( + "[defaults]\norg=a\n[auth]\ntoken=t\n[defaults]\nproject=b\n", + values, ), ).toBe( - "sentry sourcemap inject ./dist && SENTRY_URL=https://sentry.example.com sentry sourcemap upload --org my-org --project my-project ./dist", + "[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-defaults.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/sentryclirc-defaults.test.ts new file mode 100644 index 0000000000..113fe47b8f --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/sentryclirc-defaults.test.ts @@ -0,0 +1,109 @@ +/** + * `addOrgAndProjectToSentryCliRc`, which the generic and Wrangler source + * maps flows call: the `[defaults]` it writes, read back the way v4 reads + * `.sentryclirc`, next to the `[auth]` token and the user's other keys. It + * never writes a self-hosted `url`, which v4 wouldn't trust from this file. + */ + +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 { addOrgAndProjectToSentryCliRc } 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-defaults-")); + // An empty config dir so a global ~/.sentryclirc can't leak in. + configDir = mkdtempSync(path.join(tmpdir(), "wizard-rc-defaults-config-")); + process.env["SENTRY_CONFIG_DIR"] = configDir; + 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"); + +const saasOptions = { + orgSlug: "my-org", + projectSlug: "my-project", + url: "https://sentry.io/", + selfHosted: false, + authToken: "sntrys_tok", +}; + +describe("addOrgAndProjectToSentryCliRc", () => { + it("writes the org and project, but no url, for sentry.io", async () => { + await addOrgAndProjectToSentryCliRc(saasOptions); + + expect(readFileSync(rcPath(), "utf8")).toBe( + "[defaults]\norg=my-org\nproject=my-project\n", + ); + }); + + it("writes no url for self-hosted Sentry, which users set as SENTRY_URL", async () => { + await addOrgAndProjectToSentryCliRc({ + ...saasOptions, + selfHosted: true, + url: "https://sentry.example.com/", + }); + + expect(readFileSync(rcPath(), "utf8")).toBe( + "[defaults]\norg=my-org\nproject=my-project\n", + ); + expect((await loadSentryCliRc(projectDir)).url).toBeUndefined(); + }); + + it("keeps the [auth] token and the user's other keys", async () => { + writeFileSync( + rcPath(), + "# my settings\n[defaults]\norg=old-org\n\n[http]\nverify_ssl=false\n", + ); + await addSentryCliConfig({ authToken: "sntrys_tok" }); + await addOrgAndProjectToSentryCliRc(saasOptions); + + const contents = readFileSync(rcPath(), "utf8"); + expect(contents).toContain("# my settings"); + expect(contents).toContain("[http]\nverify_ssl=false"); + expect(contents).not.toContain("old-org"); + + const config = await loadSentryCliRc(projectDir); + expect(config.org).toBe("my-org"); + expect(config.project).toBe("my-project"); + expect(config.token).toBe("sntrys_tok"); + }); +}); 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 0000000000..9411b2ed3e --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/sentryclirc-file.test.ts @@ -0,0 +1,109 @@ +/** + * `.sentryclirc` written by the wizard, read back the way v4 reads it. + * + * Writes the `[defaults]` org/project and the `[auth]` token into a real + * temp dir in both orders and checks that `loadSentryCliRc` resolves all + * three, and that `.sentryclirc` ends up in `.gitignore`. + */ + +import { + existsSync, + 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 { setSentryCliRcDefaults } 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(): void { + const contents = existsSync(rcPath()) ? readFileSync(rcPath(), "utf8") : ""; + writeFileSync( + rcPath(), + setSentryCliRcDefaults(contents, { org: "my-org", project: "my-project" }), + ); +} + +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 () => { + writeDefaults(); + await addSentryCliConfig({ authToken: "sntrys_tok" }); + await expectV4ReadsAll(); + }); + + it("keeps [auth] when [defaults] is written after the token", async () => { + await addSentryCliConfig({ authToken: "sntrys_tok" }); + writeDefaults(); + await expectV4ReadsAll(); + }); + + it("keeps the user's other keys", async () => { + writeFileSync(rcPath(), "[defaults]\nurl=https://sentry.example.com/\n"); + writeDefaults(); + await addSentryCliConfig({ authToken: "sntrys_tok" }); + await expectV4ReadsAll(); + expect((await loadSentryCliRc(projectDir)).url).toBe( + "https://sentry.example.com/", + ); + }); +}); diff --git a/packages/cli/test/lib/wizard/sourcemaps/tools/wrangler.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/wrangler.test.ts index 2ff8425af9..50e5538901 100644 --- a/packages/cli/test/lib/wizard/sourcemaps/tools/wrangler.test.ts +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/wrangler.test.ts @@ -15,90 +15,37 @@ describe("getSentryCliCommand", () => { "wrangler deploy --outdir dist", ])("passes the directory from %s literally to sentry", (deployCommand) => { const outDir = findOutDir(deployCommand); - const command = getSentryCliCommand({ - selfHosted: false, - orgSlug: "myOrg", - projectSlug: "myProject", - url: "https://sentry.io", - authToken: "_ignore", - outDir, - }); - expect(runSentryCliCommand(command)).toEqual([ + expect(runSentryCliCommand(getSentryCliCommand(outDir))).toEqual([ "release", "create", "release with spaces", - "--org=myOrg", - "--project=myProject", "sourcemap", "upload", - "--org=myOrg", - "--project=myProject", "--release=release with spaces", "--no-rewrite", outDir, ]); }); - it("preserves quotes and shell syntax in paths and self-hosted arguments", () => { + it("preserves quotes and shell syntax in paths", () => { const outDir = "worker's dist;$(printf${IFS}INJECTED)"; - const url = "https://sentry.example/worker's"; - const orgSlug = "org$(printf${IFS}INJECTED)"; - const projectSlug = "project`printf INJECTED`"; - const command = getSentryCliCommand({ - selfHosted: true, - url, - orgSlug, - projectSlug, - authToken: "_ignore", - outDir, - }); - expect(runSentryCliCommand(command)).toEqual([ - `SENTRY_URL=${url}`, + expect(runSentryCliCommand(getSentryCliCommand(outDir))).toEqual([ "release", "create", "release with spaces", - `--org=${orgSlug}`, - `--project=${projectSlug}`, - `SENTRY_URL=${url}`, "sourcemap", "upload", - `--org=${orgSlug}`, - `--project=${projectSlug}`, "--release=release with spaces", "--no-rewrite", outDir, ]); }); - it("returns correct command for SaaS", () => { - const command = getSentryCliCommand({ - selfHosted: false, - orgSlug: "myOrg", - projectSlug: "myProject", - url: "https://sentry.io", - authToken: "_ignore", - outDir: "dist", - }); - - expect(command).toBe( - "_SENTRY_RELEASE=$(sentry release propose-version | head -n 1) && sentry release create \"$_SENTRY_RELEASE\" --org='myOrg' --project='myProject' && sentry sourcemap upload --org='myOrg' --project='myProject' --release=\"$_SENTRY_RELEASE\" --no-rewrite 'dist'", - ); - }); - - it("returns correct command for self-hosted", () => { - const command = getSentryCliCommand({ - selfHosted: true, - orgSlug: "myOrg", - projectSlug: "myProject", - url: "https://santry.io", - authToken: "_ignore", - outDir: "someplace", - }); - - expect(command).toBe( - "_SENTRY_RELEASE=$(sentry release propose-version | head -n 1) && SENTRY_URL='https://santry.io' sentry release create \"$_SENTRY_RELEASE\" --org='myOrg' --project='myProject' && SENTRY_URL='https://santry.io' sentry sourcemap upload --org='myOrg' --project='myProject' --release=\"$_SENTRY_RELEASE\" --no-rewrite 'someplace'", + it("reads the org and project from .sentryclirc instead of flags", () => { + expect(getSentryCliCommand("dist")).toBe( + '_SENTRY_RELEASE=$(sentry release propose-version | head -n 1) && sentry release create "$_SENTRY_RELEASE" && sentry sourcemap upload --release="$_SENTRY_RELEASE" --no-rewrite \'dist\'', ); }); }); @@ -304,15 +251,9 @@ function runSentryCliCommand(command: string): string[] { sentry() { case "$1 $2" in 'release propose-version') printf '%s\\n' 'release with spaces' 'Detected from git HEAD' ;; - 'release create' | 'sourcemap upload') - if [ -n "$SENTRY_URL" ]; then - printf '%s\\n' "SENTRY_URL=$SENTRY_URL" - fi - printf '%s\\n' "$@" - ;; + 'release create' | 'sourcemap upload') printf '%s\\n' "$@" ;; esac } -unset SENTRY_URL ${command}`; return execFileSync("/bin/bash", ["-c", script], { encoding: "utf8" }) .trimEnd() From 0c113512b26e400c88bec114d751b46ec43ffbc1 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:45:05 +0000 Subject: [PATCH 06/20] test(cli): list the Cloudflare wizard fixtures as unchecked TypeScript The Cloudflare wizard fixtures are upstream sentry-wizard Worker sources that `wrap-worker` and `update-wrangler-config` tests read and compare as text. The test tsconfig excludes them, so the tsconfig policy check needs them in its list of files no type check covers on purpose. --- scripts/tsconfig-policy.test.mjs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/scripts/tsconfig-policy.test.mjs b/scripts/tsconfig-policy.test.mjs index 1d36a8cc59..6bacccca7a 100644 --- a/scripts/tsconfig-policy.test.mjs +++ b/scripts/tsconfig-policy.test.mjs @@ -23,6 +23,11 @@ const UNCHECKED = [ reason: "codemod input and expected-output fixtures, compared as text by `jssg test`", }, + { + pattern: /^packages\/cli\/test\/lib\/wizard\/cloudflare\/fixtures\//, + reason: + "upstream sentry-wizard Worker sources the Cloudflare wizard rewrites, read and compared as text", + }, { pattern: /^packages\/logger\/test\/package\/consumer\//, reason: From 39e20d513acc8f5c30e2611396fad46aa89bdac7 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:10:45 +0000 Subject: [PATCH 07/20] fix(cli): address review findings in sentry wizard - Skip the `.sentryclirc` URL check, like `sentry init`: the wizard picks its instance (`--url`, `--saas` or a prompt) before it logs in. - Use the stored login's instance for `sentryUrl` when none was chosen, and log in again when the stored login is for another instance. - Link self-hosted users to `/settings//auth-tokens/`. - Leave an unparseable MCP config alone (show the copy-paste fallback), and let a cancel inside the MCP setup stop the wizard. - Resolve `catalog:` and `catalog:default` against both pnpm default catalog forms. - Find an existing `SENTRY_AUTH_TOKEN` after the comment header of `.env.sentry-build-plugin`, so re-runs don't add a second one. - Run Windows formatters with Node in the standalone binary, where `process.execPath` is `sentry`. - Ask before updating an `@sentry/nextjs` listed in devDependencies, and treat an unknown SDK version as the `^11` the wizard installs. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- packages/cli/src/commands/wizard.ts | 3 + .../src/lib/wizard/nextjs/nextjs-wizard.ts | 5 +- .../cli/src/lib/wizard/utils/clack/index.ts | 28 ++--- .../src/lib/wizard/utils/clack/mcp-config.ts | 22 +++- .../cli/src/lib/wizard/utils/package-json.ts | 12 ++- .../cli/src/lib/wizard/utils/project-data.ts | 16 ++- .../lib/wizard/utils/clack/mcp-config.test.ts | 101 ++++++++++++------ .../lib/wizard/utils/package-json.test.ts | 18 ++++ .../lib/wizard/utils/project-data.test.ts | 72 ++++++++++++- 9 files changed, 211 insertions(+), 66 deletions(-) diff --git a/packages/cli/src/commands/wizard.ts b/packages/cli/src/commands/wizard.ts index 2b291ef787..71f4b7fefd 100644 --- a/packages/cli/src/commands/wizard.ts +++ b/packages/cli/src/commands/wizard.ts @@ -79,6 +79,9 @@ function envValue(name: string): string | undefined { export const wizardCommand = buildCommand({ auth: false, + // The wizard picks the Sentry instance itself (`--url`, `--saas` or a + // prompt) before it logs in, like `sentry init`. + skipRcUrlCheck: true, docs: { brief: topLevelBrief("wizard"), fullDescription: diff --git a/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts b/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts index fd14f9bb03..cb02e11492 100644 --- a/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts +++ b/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts @@ -155,7 +155,7 @@ The wizard will continue, but you may need to upgrade Next.js for the SDK to wor await installPackage({ packageName: "@sentry/nextjs@^11", packageNameDisplayLabel: "@sentry/nextjs", - alreadyInstalled: !!packageJson.dependencies?.["@sentry/nextjs"], + alreadyInstalled: sdkAlreadyInstalled, forceInstall, }); @@ -185,7 +185,8 @@ The wizard will import ${chalk.cyan( // 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, "^10.73.0") && + // An unknown version (e.g. `workspace:*`) is the `^11` the wizard asked for. + sdkSupportsDataCollection(installedSdkVersion, "^11") && (await askShouldReduceDataCollection()); let selectedProject: SentryProjectData; diff --git a/packages/cli/src/lib/wizard/utils/clack/index.ts b/packages/cli/src/lib/wizard/utils/clack/index.ts index 0bdb01dc8c..a076b5049b 100644 --- a/packages/cli/src/lib/wizard/utils/clack/index.ts +++ b/packages/cli/src/lib/wizard/utils/clack/index.ts @@ -24,6 +24,7 @@ import { sentry } from "../../../app-identity.js"; import { CLI_VERSION } from "../../../constants.js"; import { reportCliError } from "../../../error-reporting.js"; import { WizardExitError } from "../../../errors.js"; +import { isSea } from "../../../react-native/wrap-call.js"; import { Sentry, traceStep } from "../../telemetry.js"; import { debug } from "../debug.js"; import { getUncommittedOrUntrackedFilePaths, isInGitRepo } from "../git.js"; @@ -717,9 +718,7 @@ SENTRY_AUTH_TOKEN=${authToken} if (dotEnvFileExists) { const dotEnvFileContent = readFileSync(dotEnvFilePath, "utf8"); - const hasAuthToken = !!dotEnvFileContent.match( - /^\s*SENTRY_AUTH_TOKEN\s*=/g, - ); + const hasAuthToken = /^\s*SENTRY_AUTH_TOKEN\s*=/m.test(dotEnvFileContent); if (hasAuthToken) { clack.log.warn( @@ -887,7 +886,9 @@ function runFormatterCommand( new Error(`Could not resolve the ${packageName} binary.`), ); } - command = process.execPath; + // In the standalone binary, `process.execPath` is `sentry` itself, not + // Node, so run the formatter with the project's Node. + command = isSea() ? "node" : process.execPath; args = [binPath, ...subArgs, "--", ...files]; } else { command = "npx"; @@ -1265,16 +1266,15 @@ export async function getPackageManager( return fallback; } - const selectedPackageManager: PackageManager | symbol = - await abortIfCancelled( - clack.select({ - message: "Please select your package manager.", - options: packageManagers.map((packageManager) => ({ - value: packageManager, - label: packageManager.label, - })), - }), - ); + const selectedPackageManager = await abortIfCancelled( + clack.select({ + message: "Please select your package manager.", + options: packageManagers.map((packageManager) => ({ + value: packageManager, + label: packageManager.label, + })), + }), + ); globalWithSentryWizard.__sentry_wizard_cached_package_manager = selectedPackageManager; diff --git a/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts b/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts index 867c9c0140..0d01374036 100644 --- a/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts +++ b/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts @@ -10,6 +10,7 @@ import { Sentry } from "../../telemetry.js"; import chalk from "chalk"; import { clack } from "./prompts.js"; import { abortIfCancelled, showCopyPasteInstructions } from "./index.js"; +import { WizardExitError } from "../../../errors.js"; import { debug } from "../debug.js"; const SENTRY_MCP_BASE_URL = "https://mcp.sentry.dev/mcp"; @@ -48,14 +49,23 @@ function ensureDir(dirpath: string): void { mkdirSync(dirpath, { recursive: true }); } +/** + * The parsed JSON in `filepath`, or `null` when the file doesn't exist. + * + * @throws {SyntaxError} When the file exists but isn't valid JSON, so the + * caller shows the copy-paste fallback instead of overwriting it + */ async function readJsonIfExists(filepath: string): Promise { + let txt: string; try { - const txt = await promises.readFile(filepath, "utf8"); - return JSON.parse(txt) as unknown; + txt = await promises.readFile(filepath, "utf8"); } catch (error) { - debug(error); - return null; + if ((error as NodeJS.ErrnoException).code === "ENOENT") { + return null; + } + throw error; } + return JSON.parse(txt) as unknown; } async function writeJson(filepath: string, obj: unknown): Promise { @@ -600,6 +610,10 @@ export async function offerProjectScopedMcpConfig( } Sentry.setTag(`mcp-config-${editor}-success`, true); } catch (e) { + if (e instanceof WizardExitError) { + throw e; + } + debug(e); Sentry.setTag(`mcp-config-${editor}-success`, false); Sentry.setTag("mcp-config-fallback", true); clack.log.warn( diff --git a/packages/cli/src/lib/wizard/utils/package-json.ts b/packages/cli/src/lib/wizard/utils/package-json.ts index 1de6728d35..775d4f8212 100644 --- a/packages/cli/src/lib/wizard/utils/package-json.ts +++ b/packages/cli/src/lib/wizard/utils/package-json.ts @@ -135,10 +135,14 @@ function resolveCatalogVersion( return undefined; } - const catalog = - catalogName === "" ? workspace.catalog : workspace.catalogs?.[catalogName]; - - return catalog?.[packageName]; + // pnpm treats `catalog:` and `catalogs.default` as the same catalog. + if (catalogName === "" || catalogName === "default") { + return ( + workspace.catalog?.[packageName] ?? + workspace.catalogs?.["default"]?.[packageName] + ); + } + return workspace.catalogs?.[catalogName]?.[packageName]; } /** diff --git a/packages/cli/src/lib/wizard/utils/project-data.ts b/packages/cli/src/lib/wizard/utils/project-data.ts index 87718dcbb9..0e4b856c32 100644 --- a/packages/cli/src/lib/wizard/utils/project-data.ts +++ b/packages/cli/src/lib/wizard/utils/project-data.ts @@ -42,8 +42,12 @@ import { logger } from "../../logger.js"; import { OAUTH_SCOPES, resolveOAuthScopeString } from "../../oauth.js"; import { resolveOrCreateTeam } from "../../resolve-team.js"; import { ensureScopesForAction } from "../../scope-recovery.js"; -import { getSentryBaseUrl, isSentrySaasUrl } from "../../sentry-urls.js"; -import { registerLoginTrustAnchor } from "../../token-host.js"; +import { isSentrySaasUrl } from "../../sentry-urls.js"; +import { getApiBaseUrl } from "../../sentry-client.js"; +import { + isRequestOriginTrusted, + registerLoginTrustAnchor, +} from "../../token-host.js"; import { slugify } from "../../utils.js"; import { sentry } from "../../app-identity.js"; import type { @@ -130,7 +134,8 @@ export async function getOrAskForProjectData( ); const handoffOrg = await traceStep("login", ensureLoggedIn); - const sentryUrl = withTrailingSlash(getSentryBaseUrl()); + // The chosen instance, or the stored login's when none was chosen. + const sentryUrl = withTrailingSlash(getApiBaseUrl()); const selfHosted = !isSentrySaasUrl(sentryUrl); Sentry.setTag("url", sentryUrl); Sentry.setTag("self-hosted", selfHosted); @@ -261,7 +266,8 @@ async function ensureLoggedIn(): Promise { return handoff.organizationSlug; } - if (getAuthConfig()) { + // A login for another instance than the selected one can't be used. + if (getAuthConfig() && isRequestOriginTrusted(getApiBaseUrl())) { Sentry.setTag("login-method", "stored"); return; } @@ -464,7 +470,7 @@ async function createAuthToken( Sentry.setTag("auth-token-created", false); const settingsUrl = isSentrySaasUrl(sentryUrl) ? `https://${orgSlug}.sentry.io/settings/auth-tokens/` - : `${sentryUrl}organizations/${orgSlug}/settings/auth-tokens/`; + : `${sentryUrl}settings/${orgSlug}/auth-tokens/`; clack.log.warn( `Could not create an auth token for you. We'll add a placeholder (${chalk.cyan( `"${DUMMY_AUTH_TOKEN}"`, diff --git a/packages/cli/test/lib/wizard/utils/clack/mcp-config.test.ts b/packages/cli/test/lib/wizard/utils/clack/mcp-config.test.ts index af614d9793..2a83ff5028 100644 --- a/packages/cli/test/lib/wizard/utils/clack/mcp-config.test.ts +++ b/packages/cli/test/lib/wizard/utils/clack/mcp-config.test.ts @@ -13,8 +13,16 @@ import * as fs from "node:fs"; import * as path from "node:path"; // oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking import * as childProcess from "node:child_process"; +import { WizardExitError } from "../../../../../src/lib/errors.js"; import { offerProjectScopedMcpConfig } from "../../../../../src/lib/wizard/utils/clack/mcp-config.js"; +/** The error `fs.promises.readFile` rejects with for a missing file. */ +function fileNotFound(): NodeJS.ErrnoException { + return Object.assign(new Error("ENOENT: no such file or directory"), { + code: "ENOENT", + }); +} + // Mock types for better type safety type ConfigContent = { mcpServers?: Record; @@ -115,9 +123,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi.fn().mockResolvedValue(undefined); const mockMkdirSync = vi.fn(); @@ -164,9 +170,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi.fn().mockResolvedValue(undefined); const mockMkdirSync = vi.fn(); @@ -196,9 +200,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi.fn().mockResolvedValue(undefined); const mockMkdirSync = vi.fn(); @@ -349,9 +351,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi.fn().mockResolvedValue(undefined); const mockMkdirSync = vi.fn(); @@ -435,9 +435,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi .fn() .mockRejectedValue(new Error("Permission denied")); @@ -462,7 +460,7 @@ describe("mcp-config", () => { ); }); - it("should handle file write errors gracefully for Cursor", async () => { + it("shows the fallback instead of overwriting an unparseable config", async () => { const { clack, clackUtils } = await getMocks(); vi.mocked(clack.select).mockResolvedValueOnce("yes"); @@ -473,7 +471,52 @@ describe("mcp-config", () => { const mockReadFile = vi .fn() - .mockRejectedValue(new Error("File not found")); + .mockResolvedValue('{ "mcpServers": { "OtherServer": {}, } }'); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(vi.fn()); + + await offerProjectScopedMcpConfig(); + + expect(mockWriteFile).not.toHaveBeenCalled(); + expect(clackUtils.showCopyPasteInstructions).toHaveBeenCalledWith( + expect.objectContaining({ filename: path.join(".cursor", "mcp.json") }), + ); + }); + + it("lets a WizardExitError from an editor's setup stop the wizard", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["cursor", "vscode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockWriteFile = vi.fn().mockRejectedValue(new WizardExitError(0)); + vi.spyOn(fs.promises, "readFile").mockRejectedValue(fileNotFound()); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(vi.fn()); + + await expect(offerProjectScopedMcpConfig()).rejects.toThrow( + WizardExitError, + ); + expect(mockWriteFile).toHaveBeenCalledTimes(1); + expect(clackUtils.showCopyPasteInstructions).not.toHaveBeenCalled(); + }); + + it("should handle file write errors gracefully for Cursor", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["cursor"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi .fn() .mockRejectedValue(new Error("Permission denied")); @@ -507,9 +550,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi .fn() .mockRejectedValue(new Error("Permission denied")); @@ -539,9 +580,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi .fn() .mockRejectedValue(new Error("Permission denied")); @@ -608,9 +647,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi.fn().mockResolvedValue(undefined); const mockMkdirSync = vi.fn().mockImplementation(() => { throw new Error("Permission denied"); @@ -823,9 +860,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi.fn().mockResolvedValue(undefined); const mockMkdirSync = vi.fn(); @@ -944,9 +979,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi.fn().mockResolvedValue(undefined); const mockMkdirSync = vi.fn(); @@ -1015,9 +1048,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi .fn() .mockResolvedValueOnce(undefined) // Cursor succeeds diff --git a/packages/cli/test/lib/wizard/utils/package-json.test.ts b/packages/cli/test/lib/wizard/utils/package-json.test.ts index f04f2f9fd4..51845812e1 100644 --- a/packages/cli/test/lib/wizard/utils/package-json.test.ts +++ b/packages/cli/test/lib/wizard/utils/package-json.test.ts @@ -123,6 +123,24 @@ catalog: expect(getPackageVersion("@sentry/node", packageJson)).toBe("^7.100.0"); }); + it.each([ + ["catalog:default", "catalog:\n '@sentry/node': ^7.100.0\n"], + ["catalog:", "catalogs:\n default:\n '@sentry/node': ^7.100.0\n"], + ])("resolves %s against either default catalog form", (ref, yaml) => { + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + mockedFs.readFileSync.mockReturnValue(yaml); + + const packageJson: PackageDotJson = { + dependencies: { "@sentry/node": ref }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBe("^7.100.0"); + }); + it("resolves named catalog reference", () => { mockedFs.existsSync.mockImplementation((filepath: string) => { return ( diff --git a/packages/cli/test/lib/wizard/utils/project-data.test.ts b/packages/cli/test/lib/wizard/utils/project-data.test.ts index a691410ee2..152d7adb29 100644 --- a/packages/cli/test/lib/wizard/utils/project-data.test.ts +++ b/packages/cli/test/lib/wizard/utils/project-data.test.ts @@ -19,6 +19,9 @@ const mocks = vi.hoisted(() => ({ createOrgAuthToken: vi.fn(), select: vi.fn(), text: vi.fn(), + isRequestOriginTrusted: vi.fn(), + getApiBaseUrl: vi.fn(), + warn: vi.fn(), })); vi.mock("@clack/prompts", () => ({ @@ -31,10 +34,23 @@ vi.mock("@clack/prompts", () => ({ log: { info: vi.fn(), step: vi.fn(), - warn: vi.fn(), + warn: mocks.warn, error: vi.fn(), }, })); +// The stored login (`getAuthConfig`) is mocked, so its host check is too. +vi.mock("../../../../src/lib/token-host.js", async (importOriginal) => ({ + ...(await importOriginal< + typeof import("../../../../src/lib/token-host.js") + >()), + isRequestOriginTrusted: mocks.isRequestOriginTrusted, +})); +vi.mock("../../../../src/lib/sentry-client.js", async (importOriginal) => ({ + ...(await importOriginal< + typeof import("../../../../src/lib/sentry-client.js") + >()), + getApiBaseUrl: mocks.getApiBaseUrl, +})); vi.mock("../../../../src/lib/db/auth.js", async (importOriginal) => ({ ...(await importOriginal()), getAuthConfig: mocks.getAuthConfig, @@ -87,10 +103,15 @@ const KEY = { dsn: { public: "https://abc@o1.ingest.sentry.io/42", secret: "" }, }; -beforeEach(() => { +beforeEach(async () => { vi.clearAllMocks(); + const actualClient = await vi.importActual< + typeof import("../../../../src/lib/sentry-client.js") + >("../../../../src/lib/sentry-client.js"); + mocks.getApiBaseUrl.mockImplementation(actualClient.getApiBaseUrl); vi.stubEnv("SENTRY_HANDOFF", ""); mocks.getAuthConfig.mockReturnValue({ token: "stored" }); + mocks.isRequestOriginTrusted.mockReturnValue(true); mocks.listOrganizations.mockResolvedValue([ORG]); mocks.getProject.mockResolvedValue(PROJECT); mocks.getProjectKeys.mockResolvedValue([KEY]); @@ -236,6 +257,53 @@ describe("getOrAskForProjectData", () => { ).rejects.toThrow(WizardExitError); }); + it("logs in again when the stored login is for another instance", async () => { + mocks.isRequestOriginTrusted.mockReturnValueOnce(false); + mocks.runInteractiveLogin.mockResolvedValue({ method: "oauth" }); + + await getOrAskForProjectData({ + telemetryEnabled: false, + url: "https://sentry.example.com", + orgSlug: "acme", + projectSlug: "web", + }); + + expect(mocks.runInteractiveLogin).toHaveBeenCalled(); + }); + + it("uses the stored login's instance when none is chosen", async () => { + mocks.getApiBaseUrl.mockReturnValue("https://sentry.example.com"); + + const result = await getOrAskForProjectData({ + telemetryEnabled: false, + orgSlug: "acme", + projectSlug: "web", + }); + + expect(mocks.runInteractiveLogin).not.toHaveBeenCalled(); + expect(result).toMatchObject({ + sentryUrl: "https://sentry.example.com/", + selfHosted: true, + }); + }); + + it("links to the self-hosted auth token settings when it can't create one", async () => { + mocks.getApiBaseUrl.mockReturnValue("https://sentry.example.com"); + mocks.createOrgAuthToken.mockRejectedValue(new Error("forbidden")); + + await getOrAskForProjectData({ + telemetryEnabled: false, + orgSlug: "acme", + projectSlug: "web", + }); + + expect(mocks.warn).toHaveBeenCalledWith( + expect.stringContaining( + "https://sentry.example.com/settings/acme/auth-tokens/", + ), + ); + }); + it("claims an agent handoff and uses its org", async () => { vi.stubEnv("SENTRY_HANDOFF", "handoff-code"); mocks.completeAgentHandoff.mockResolvedValue({ organizationSlug: "acme" }); From e40669bc236bbb2620d84bc1754c4be0f317d0c8 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:19:55 +0000 Subject: [PATCH 08/20] feat(cli): write the self-hosted URL to .sentryclirc in the wizard On self-hosted Sentry, the generic and Wrangler source maps flows now write `url` to `.sentryclirc` `[defaults]` next to `org` and `project`. v4 rejects that URL from the same file as the token today. The trust check fix is separate, and the generated script depends on it. The CI step on sentry.io now lists only `SENTRY_AUTH_TOKEN`. On self-hosted Sentry it also lists `SENTRY_ORG`, `SENTRY_PROJECT` and `SENTRY_URL`. The wizard docs fragment says the same. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .../cli-docs/src/fragments/commands/wizard.md | 10 +++---- packages/cli/src/lib/wizard/sourcemaps/ci.ts | 16 +++++------ .../lib/wizard/sourcemaps/tools/sentry-cli.ts | 15 +++++------ .../lib/wizard/sourcemaps/ci-setup.test.ts | 27 +++++++++++-------- .../cli/test/lib/wizard/sourcemaps/ci.test.ts | 10 +++---- .../tools/sentryclirc-defaults.test.ts | 8 +++--- 6 files changed, 41 insertions(+), 45 deletions(-) diff --git a/apps/cli-docs/src/fragments/commands/wizard.md b/apps/cli-docs/src/fragments/commands/wizard.md index c36fcb7ffc..c0825dff4f 100644 --- a/apps/cli-docs/src/fragments/commands/wizard.md +++ b/apps/cli-docs/src/fragments/commands/wizard.md @@ -31,8 +31,8 @@ changes nothing. 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 inject` and `sentry sourcemap upload` -on your build output. The wizard writes your org and project 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`, -`SENTRY_ORG` and `SENTRY_PROJECT` instead. On self-hosted Sentry, also set -`SENTRY_URL` wherever that script runs. +on your build output. 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/sourcemaps/ci.ts b/packages/cli/src/lib/wizard/sourcemaps/ci.ts index 863416c1d1..136492b314 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/ci.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/ci.ts @@ -25,8 +25,8 @@ const CLI_BASED_FLOW_TOOLS: readonly string[] = [ ]; /** - * Where `sentry sourcemap upload` sends source maps. In CI it comes from - * `SENTRY_ORG`, `SENTRY_PROJECT` and, for self-hosted Sentry, `SENTRY_URL`. + * Where `sentry sourcemap upload` sends source maps. On self-hosted Sentry, + * CI gets it from `SENTRY_ORG`, `SENTRY_PROJECT` and `SENTRY_URL`. */ export type SentryCliUploadTarget = { org: string; @@ -42,7 +42,7 @@ export type SentryCliUploadTarget = { * @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 that CI needs as well + * org, project, and URL that CI needs as well on self-hosted Sentry */ export async function setupCI( selectedTool: string, @@ -115,14 +115,14 @@ export function getCIEnvVars( uploadTarget: SentryCliUploadTarget | undefined, ): string[] { const lines = [`SENTRY_AUTH_TOKEN=${authToken}`]; - if (uploadTarget) { + // On sentry.io the auth token is enough. Self-hosted Sentry also needs + // the org, project and URL. + if (uploadTarget?.url) { lines.push( `SENTRY_ORG=${uploadTarget.org}`, `SENTRY_PROJECT=${uploadTarget.project}`, + `SENTRY_URL=${uploadTarget.url}`, ); - if (uploadTarget.url) { - lines.push(`SENTRY_URL=${uploadTarget.url}`); - } } return lines; } @@ -133,7 +133,7 @@ async function setupAuthTokenInCI( uploadTarget: SentryCliUploadTarget | undefined, ): Promise { clack.log.step( - uploadTarget + uploadTarget?.url ? "Add these environment variables to your CI setup:" : "Add the Sentry authentication token as an environment variable to your CI setup:", ); diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts index 9eda726ab5..42ef7f86d9 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts @@ -262,13 +262,9 @@ export function setSentryCliRcDefaults( } /** - * Write the org and project to the project's `.sentryclirc`, so that - * `sentry sourcemap upload` finds them when the script runs locally. - * - * The self-hosted URL stays out of the file. v4 refuses a non-SaaS - * `[defaults] url` unless the token's host or a stored login vouches for it, - * and the `[auth] token` from the same file doesn't (see - * `assertRcUrlTrusted`), so users set `SENTRY_URL` instead. + * 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. */ export async function addOrgAndProjectToSentryCliRc( options: SourceMapUploadToolConfigurationOptions, @@ -284,11 +280,12 @@ export async function addOrgAndProjectToSentryCliRc( 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. + // Not fatal, like the auth token write: the warning says how to set + // them instead. debug(error); clack.log.warning( `Failed to add the org and project to ${chalk.cyan( diff --git a/packages/cli/test/lib/wizard/sourcemaps/ci-setup.test.ts b/packages/cli/test/lib/wizard/sourcemaps/ci-setup.test.ts index 23c2a65718..fb2c7a984b 100644 --- a/packages/cli/test/lib/wizard/sourcemaps/ci-setup.test.ts +++ b/packages/cli/test/lib/wizard/sourcemaps/ci-setup.test.ts @@ -41,22 +41,27 @@ afterEach(() => { const uploadTarget = { org: "my-org", project: "my-project" }; +const selfHostedTarget = { + ...uploadTarget, + url: "https://sentry.example.com/", +}; + describe("setupCI", () => { - it("names the auth token, org and project for Wrangler", async () => { + it("names only the auth token for Wrangler on sentry.io", async () => { await setupCI("wrangler", "sntrys_tok", uploadTarget); expect(stdout).toContain("SENTRY_AUTH_TOKEN=sntrys_tok"); - expect(stdout).toContain("SENTRY_ORG=my-org"); - expect(stdout).toContain("SENTRY_PROJECT=my-project"); + expect(stdout).not.toContain("SENTRY_ORG"); + expect(stdout).not.toContain("SENTRY_PROJECT"); expect(stdout).not.toContain("SENTRY_URL"); }); - it("adds SENTRY_URL for self-hosted Sentry", async () => { - await setupCI("wrangler", "sntrys_tok", { - ...uploadTarget, - url: "https://sentry.example.com/", - }); + it("adds the org, project and URL for Wrangler on self-hosted Sentry", async () => { + await setupCI("wrangler", "sntrys_tok", selfHostedTarget); + expect(stdout).toContain("SENTRY_AUTH_TOKEN=sntrys_tok"); + expect(stdout).toContain("SENTRY_ORG=my-org"); + expect(stdout).toContain("SENTRY_PROJECT=my-project"); expect(stdout).toContain("SENTRY_URL=https://sentry.example.com/"); }); @@ -68,14 +73,14 @@ describe("setupCI", () => { }); it("asks to add the upload script to CI for the generic flow", async () => { - await setupCI("sentry-cli", "sntrys_tok", uploadTarget); + await setupCI("sentry-cli", "sntrys_tok", selfHostedTarget); expect(clackMocks.select).toHaveBeenCalledTimes(3); expect(stdout).toContain("SENTRY_ORG=my-org"); }); - it("names only the auth token for bundler plugins", async () => { - await setupCI("vite", "sntrys_tok", uploadTarget); + it("names only the auth token for bundler plugins, even on self-hosted Sentry", async () => { + await setupCI("vite", "sntrys_tok", selfHostedTarget); expect(stdout).toContain("SENTRY_AUTH_TOKEN=sntrys_tok"); expect(stdout).not.toContain("SENTRY_ORG"); diff --git a/packages/cli/test/lib/wizard/sourcemaps/ci.test.ts b/packages/cli/test/lib/wizard/sourcemaps/ci.test.ts index 2b80dfd59b..f82fdaa1b4 100644 --- a/packages/cli/test/lib/wizard/sourcemaps/ci.test.ts +++ b/packages/cli/test/lib/wizard/sourcemaps/ci.test.ts @@ -7,17 +7,13 @@ describe("getCIEnvVars", () => { expect(getCIEnvVars("tok", undefined)).toEqual(["SENTRY_AUTH_TOKEN=tok"]); }); - it("adds the org and project for sentry.io", () => { + it("lists only the auth token for sentry.io", () => { expect( getCIEnvVars("tok", { org: "my-org", project: "my-project" }), - ).toEqual([ - "SENTRY_AUTH_TOKEN=tok", - "SENTRY_ORG=my-org", - "SENTRY_PROJECT=my-project", - ]); + ).toEqual(["SENTRY_AUTH_TOKEN=tok"]); }); - it("adds SENTRY_URL for self-hosted Sentry", () => { + it("adds the org, project and SENTRY_URL for self-hosted Sentry", () => { expect( getCIEnvVars("tok", { org: "my-org", diff --git a/packages/cli/test/lib/wizard/sourcemaps/tools/sentryclirc-defaults.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/sentryclirc-defaults.test.ts index 113fe47b8f..214b297bfb 100644 --- a/packages/cli/test/lib/wizard/sourcemaps/tools/sentryclirc-defaults.test.ts +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/sentryclirc-defaults.test.ts @@ -1,8 +1,7 @@ /** * `addOrgAndProjectToSentryCliRc`, which the generic and Wrangler source * maps flows call: the `[defaults]` it writes, read back the way v4 reads - * `.sentryclirc`, next to the `[auth]` token and the user's other keys. It - * never writes a self-hosted `url`, which v4 wouldn't trust from this file. + * `.sentryclirc`, next to the `[auth]` token and the user's other keys. */ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; @@ -75,7 +74,7 @@ describe("addOrgAndProjectToSentryCliRc", () => { ); }); - it("writes no url for self-hosted Sentry, which users set as SENTRY_URL", async () => { + it("writes the url for self-hosted Sentry", async () => { await addOrgAndProjectToSentryCliRc({ ...saasOptions, selfHosted: true, @@ -83,9 +82,8 @@ describe("addOrgAndProjectToSentryCliRc", () => { }); expect(readFileSync(rcPath(), "utf8")).toBe( - "[defaults]\norg=my-org\nproject=my-project\n", + "[defaults]\norg=my-org\nproject=my-project\nurl=https://sentry.example.com/\n", ); - expect((await loadSentryCliRc(projectDir)).url).toBeUndefined(); }); it("keeps the [auth] token and the user's other keys", async () => { From 2c987511447e235888f3773f3599aaf82d742b54 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:01:23 +0000 Subject: [PATCH 09/20] refactor(cli): reuse existing CLI helpers in the wizard AST utils Address review feedback on the shared wizard helpers: - Enable unicorn/no-array-for-each repo-wide and convert every .forEach call site to for...of, including getLastRequireIndex. - Add buildProjectIssuesUrl to lib/sentry-urls.ts, built on getOrgBaseUrl like buildEventSearchUrl, and delete the wizard-specific wizard/utils/url.ts. - Move findFile into lib/dsn/fs-utils.ts and build it on isRegularFile, so a directory or FIFO with a matching name is skipped. It is async now. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .oxlintrc.json | 1 + apps/games-api/src/leaderboard.test.ts | 4 +- apps/local/src/lib/profile-session.ts | 14 +++--- packages/cli/src/commands/api.ts | 4 +- packages/cli/src/lib/db/completion-cache.ts | 4 +- packages/cli/src/lib/dsn/errors.ts | 4 +- packages/cli/src/lib/dsn/fs-utils.ts | 22 ++++++++++ packages/cli/src/lib/formatters/alerts.ts | 8 ++-- packages/cli/src/lib/formatters/human.ts | 8 ++-- packages/cli/src/lib/games/snake-game.ts | 4 +- packages/cli/src/lib/select-ui/picker.ts | 4 +- packages/cli/src/lib/sentry-urls.ts | 18 ++++++++ packages/cli/src/lib/sixel-image.ts | 4 +- .../cli/src/lib/wizard/utils/ast-utils.ts | 19 +------- packages/cli/src/lib/wizard/utils/url.ts | 29 ------------- packages/cli/test/lib/api/traces.test.ts | 4 +- packages/cli/test/lib/dsn/fs-utils.test.ts | 43 ++++++++++++++++++- .../test/lib/sdk-positionals.property.test.ts | 4 +- .../cli/test/lib/sentry-urls.property.test.ts | 16 +++++++ .../cli/test/lib/wizard/nextjs/utils.test.ts | 4 +- packages/cli/test/mocks/server.ts | 4 +- .../client/components/chat/chat-messages.tsx | 38 ++++++++-------- packages/mcp-core/chart-app/chart.ts | 8 ++-- .../api-client/client-request-paths.test.ts | 6 +-- .../src/internal/issue-side-quests.test.ts | 8 ++-- packages/mcp-core/src/internal/side-quests.ts | 4 +- .../src/internal/source-map-diagnosis.ts | 8 ++-- .../src/tools/catalog/get-event-attachment.ts | 4 +- .../src/tools/support/profile/analyzer.ts | 8 ++-- .../support/profile/flamegraph-output.ts | 6 +-- .../tools/support/search-events/replays.ts | 4 +- .../src/tools/support/search-events/utils.ts | 21 ++++----- 32 files changed, 193 insertions(+), 144 deletions(-) delete mode 100644 packages/cli/src/lib/wizard/utils/url.ts diff --git a/.oxlintrc.json b/.oxlintrc.json index ff2085d067..4304d7920f 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -69,6 +69,7 @@ "typescript/no-useless-default-assignment": "error", "jsx-a11y/interactive-supports-focus": "off", "unicorn/prefer-spread": "error", + "unicorn/no-array-for-each": "error", "typescript/no-misused-promises": "error", "typescript/switch-exhaustiveness-check": [ "error", diff --git a/apps/games-api/src/leaderboard.test.ts b/apps/games-api/src/leaderboard.test.ts index 09b62a9838..cfd655cab1 100644 --- a/apps/games-api/src/leaderboard.test.ts +++ b/apps/games-api/src/leaderboard.test.ts @@ -179,7 +179,9 @@ describe("games leaderboard route", () => { "kk", "ll", ]; - names.forEach((n, i) => rows.push([`${n}-${n}-100${i % 10}`, 300 - i])); + for (const [i, n] of names.entries()) { + rows.push([`${n}-${n}-100${i % 10}`, 300 - i]); + } fetchMock.mockResolvedValue(jsonResponse(upstreamBody(rows))); const res = await app.request(PATH, REQ, makeEnv()); diff --git a/apps/local/src/lib/profile-session.ts b/apps/local/src/lib/profile-session.ts index f29d4ae532..2099a05dfb 100644 --- a/apps/local/src/lib/profile-session.ts +++ b/apps/local/src/lib/profile-session.ts @@ -128,8 +128,8 @@ export function mergeProfileChunks( const frameMap = new Map(), stackMap = new Map(); if (Array.isArray(profile["frames"])) - profile["frames"].forEach((frame, index) => { - if (!Object.keys(record(frame)).length) return; + for (const [index, frame] of profile["frames"].entries()) { + if (!Object.keys(record(frame)).length) continue; const key = profileValueKey(frame); let id = frameIds.get(key); if (id === undefined) { @@ -138,15 +138,15 @@ export function mergeProfileChunks( frameIds.set(key, id); } frameMap.set(index, id); - }); + } if (Array.isArray(profile["stacks"])) - profile["stacks"].forEach((stack, index) => { - if (!Array.isArray(stack)) return; + stacks: for (const [index, stack] of profile["stacks"].entries()) { + if (!Array.isArray(stack)) continue; const mapped: number[] = []; for (const frame of stack) { const id = typeof frame === "number" ? frameMap.get(frame) : undefined; - if (id === undefined) return; // Broken indexes cannot silently describe another frame. + if (id === undefined) continue stacks; // Broken indexes cannot silently describe another frame. mapped.push(id); } const key = JSON.stringify(mapped); @@ -157,7 +157,7 @@ export function mergeProfileChunks( stackIds.set(key, id); } stackMap.set(index, id); - }); + } const chunkThreads = new Map[]>(); if (Array.isArray(profile["samples"])) for (const value of profile["samples"]) { diff --git a/packages/cli/src/commands/api.ts b/packages/cli/src/commands/api.ts index 3d2ff084d9..e6f7e0c03c 100644 --- a/packages/cli/src/commands/api.ts +++ b/packages/cli/src/commands/api.ts @@ -1487,9 +1487,9 @@ function logResponse(response: { log.debug( `< HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ""}`, ); - response.headers.forEach((value, key) => { + for (const [key, value] of response.headers) { log.debug(`< ${key}: ${value}`); - }); + } log.debug("<"); } diff --git a/packages/cli/src/lib/db/completion-cache.ts b/packages/cli/src/lib/db/completion-cache.ts index 3cd00d3cb2..8236087027 100644 --- a/packages/cli/src/lib/db/completion-cache.ts +++ b/packages/cli/src/lib/db/completion-cache.ts @@ -114,7 +114,7 @@ export function cacheCompletionEntities( ) .get(kind, orgSlug) as { latest: number | null } | undefined; const now = Math.max(Date.now(), (latest?.latest ?? 0) + valid.length); - valid.forEach((entity, index) => { + for (const [index, entity] of valid.entries()) { runUpsert( db, "completion_cache", @@ -127,7 +127,7 @@ export function cacheCompletionEntities( }, ["kind", "org_slug", "value"], ); - }); + } db.query( `DELETE FROM completion_cache WHERE kind = ? AND org_slug = ? AND rowid NOT IN ( diff --git a/packages/cli/src/lib/dsn/errors.ts b/packages/cli/src/lib/dsn/errors.ts index 9ad83c3ce8..cccef4c341 100644 --- a/packages/cli/src/lib/dsn/errors.ts +++ b/packages/cli/src/lib/dsn/errors.ts @@ -22,14 +22,14 @@ import type { DsnDetectionResult } from "./types.js"; export function formatConflictError(result: DsnDetectionResult): string { const lines = ["Error: Multiple Sentry DSNs detected in this project.\n"]; - result.all.forEach((dsn, i) => { + for (const [i, dsn] of result.all.entries()) { lines.push(` DSN ${i + 1}: ${dsn.raw}`); lines.push(` Source: ${getDsnSourceDescription(dsn)}`); if (dsn.projectId) { lines.push(` Project ID: ${dsn.projectId}`); } lines.push(""); - }); + } lines.push("To resolve, specify which project to use:"); lines.push(` ${sentry` /`}`); diff --git a/packages/cli/src/lib/dsn/fs-utils.ts b/packages/cli/src/lib/dsn/fs-utils.ts index 9c954d0686..1c28aebffe 100644 --- a/packages/cli/src/lib/dsn/fs-utils.ts +++ b/packages/cli/src/lib/dsn/fs-utils.ts @@ -113,3 +113,25 @@ export async function isRegularFile( return false; } } + +/** + * Find the first of `basePath` + each extension that is a regular file, for + * config files whose extension isn't known yet (`next.config` → + * `next.config.mjs`). + * + * @param basePath - Path without the extension + * @param extensions - Extensions to try, in order, each with its leading dot + * @returns The first matching path, or undefined when none is a regular file + */ +export async function findFile( + basePath: string, + extensions: readonly string[] = [".js", ".ts", ".mjs", ".cjs"], +): Promise { + for (const extension of extensions) { + const candidate = `${basePath}${extension}`; + if (await isRegularFile(candidate, "findFile")) { + return candidate; + } + } + return undefined; +} diff --git a/packages/cli/src/lib/formatters/alerts.ts b/packages/cli/src/lib/formatters/alerts.ts index ecee154539..24e0171353 100644 --- a/packages/cli/src/lib/formatters/alerts.ts +++ b/packages/cli/src/lib/formatters/alerts.ts @@ -81,9 +81,9 @@ function conditionRows(value: unknown, detector: boolean): Row[] { const rows: Row[] = [["Logic", valueText(group["logicType"])]]; const conditions = group["conditions"]; if (Array.isArray(conditions) && conditions.length > 0) { - conditions.forEach((condition, index) => { + for (const [index, condition] of conditions.entries()) { rows.push([`Condition ${index + 1}`, conditionText(condition, detector)]); - }); + } } else { rows.push([ "Conditions", @@ -150,11 +150,11 @@ function workflowSections(workflow: GetOrganizationWorkflowResponse): string[] { ...workflowGroupSections(workflow.triggers, "Triggers"), ]; if (workflow.actionFilters?.length) { - workflow.actionFilters.forEach((group, index) => { + for (const [index, group] of workflow.actionFilters.entries()) { sections.push( ...workflowGroupSections(group, `Action filter ${index + 1}`), ); - }); + } } else { sections.push(table([["Action filters", "none"]])); } diff --git a/packages/cli/src/lib/formatters/human.ts b/packages/cli/src/lib/formatters/human.ts index 2ee356406a..e34818d542 100644 --- a/packages/cli/src/lib/formatters/human.ts +++ b/packages/cli/src/lib/formatters/human.ts @@ -1286,7 +1286,7 @@ function formatSpanSimple(span: TraceSpan, opts: FormatSpanOptions): void { if (currentDepth < maxDepth) { const children = span.children ?? []; const childCount = children.length; - children.forEach((child, i) => { + for (const [i, child] of children.entries()) { formatSpanSimple(child, { lines, prefix: childPrefix, @@ -1294,7 +1294,7 @@ function formatSpanSimple(span: TraceSpan, opts: FormatSpanOptions): void { currentDepth: currentDepth + 1, maxDepth, }); - }); + } } } @@ -1367,7 +1367,7 @@ export function formatSimpleSpanTree( const displaySpans = truncated ? spans.slice(0, MAX_ROOT_SPANS) : spans; const displayCount = displaySpans.length; - displaySpans.forEach((span, i) => { + for (const [i, span] of displaySpans.entries()) { formatSpanSimple(span, { lines, prefix: "", @@ -1375,7 +1375,7 @@ export function formatSimpleSpanTree( currentDepth: 1, maxDepth: effectiveMaxDepth, }); - }); + } if (truncated) { const remaining = totalRootSpans - MAX_ROOT_SPANS; diff --git a/packages/cli/src/lib/games/snake-game.ts b/packages/cli/src/lib/games/snake-game.ts index b4b3f4c052..5be8d6628a 100644 --- a/packages/cli/src/lib/games/snake-game.ts +++ b/packages/cli/src/lib/games/snake-game.ts @@ -313,9 +313,9 @@ export function renderSnake( if (state.food) { cells[state.food.y * state.width + state.food.x] = FOOD; } - state.body.forEach((part, index) => { + for (const [index, part] of state.body.entries()) { cells[part.y * state.width + part.x] = index === 0 ? HEAD : BODY; - }); + } const lines: string[] = []; for (let row = 0; row < snakeTerminalRows(state.height); row++) { diff --git a/packages/cli/src/lib/select-ui/picker.ts b/packages/cli/src/lib/select-ui/picker.ts index 3e5a729799..7060a1a276 100644 --- a/packages/cli/src/lib/select-ui/picker.ts +++ b/packages/cli/src/lib/select-ui/picker.ts @@ -450,14 +450,14 @@ function renderPicker( const accent = chalk.hex(ACCENT); const lines = [""]; - titleLines.forEach((line, index) => { + for (const [index, line] of titleLines.entries()) { const icon = padIcon(index === 0 ? ICONS.diamondOpen : ""); const counter = index === 0 && isWindowed ? chalk.hex(MUTED_DIM)(` (${highlighted + 1}/${filtered.length})`) : ""; lines.push(`${accent.bold(icon)}${chalk.bold(line)}${counter}`); - }); + } lines.push(""); const optionLines = diff --git a/packages/cli/src/lib/sentry-urls.ts b/packages/cli/src/lib/sentry-urls.ts index 3e8dbd5072..902e2fcdc7 100644 --- a/packages/cli/src/lib/sentry-urls.ts +++ b/packages/cli/src/lib/sentry-urls.ts @@ -236,6 +236,24 @@ export function buildEventSearchUrl(orgSlug: string, eventId: string): string { return `${getSentryBaseUrl()}/organizations/${orgSlug}/issues/?query=event.id:${eventId}`; } +/** + * Build URL to a project's issue stream in Sentry. + * + * @param orgSlug - Organization slug + * @param projectId - Numeric project ID + * @returns Full URL to the issues list filtered to the project + */ +export function buildProjectIssuesUrl( + orgSlug: string, + projectId: string, +): string { + const project = encodeURIComponent(projectId); + if (isSaaS()) { + return `${getOrgBaseUrl(orgSlug)}/issues/?project=${project}`; + } + return `${getSentryBaseUrl()}/organizations/${orgSlug}/issues/?project=${project}`; +} + // Settings URLs /** diff --git a/packages/cli/src/lib/sixel-image.ts b/packages/cli/src/lib/sixel-image.ts index 30b175ac3d..a7ac0f3141 100644 --- a/packages/cli/src/lib/sixel-image.ts +++ b/packages/cli/src/lib/sixel-image.ts @@ -601,9 +601,9 @@ export function encodeImageToSixel( // DCS: P1=0 aspect, P2=1 (unpainted = transparent), P3=0 grid; then raster // attributes "1;1;W;H so the terminal reserves the right pixel box. let out = `\x1bP0;1;0q"1;1;${width};${height}`; - palette.forEach(([r, g, b], i) => { + for (const [i, [r, g, b]] of palette.entries()) { out += `#${i};2;${to100(r)};${to100(g)};${to100(b)}`; - }); + } const totalBands = Math.ceil(height / 6); for (let band = 0; band < totalBands; band++) { diff --git a/packages/cli/src/lib/wizard/utils/ast-utils.ts b/packages/cli/src/lib/wizard/utils/ast-utils.ts index 05929e5203..9bf504f456 100644 --- a/packages/cli/src/lib/wizard/utils/ast-utils.ts +++ b/packages/cli/src/lib/wizard/utils/ast-utils.ts @@ -3,8 +3,6 @@ * that edit JavaScript and TypeScript config files. */ -import { existsSync } from "node:fs"; - import recast from "recast"; import { debug } from "./debug.js"; @@ -12,19 +10,6 @@ import type { namedTypes as t } from "ast-types"; const b = recast.types.builders; -/** - * Checks if a file where we don't know its concrete file type yet exists - * and returns the full path to the file with the correct file type. - */ -export function findFile( - filePath: string, - fileTypes: string[] = [".js", ".ts", ".mjs", ".cjs"], -): string | undefined { - return fileTypes - .map((type) => `${filePath}${type}`) - .find((file) => existsSync(file)); -} - /** * checks for require('@sentry/*') syntax */ @@ -237,7 +222,7 @@ export function printJsonC(ast: t.Program): string { */ export function getLastRequireIndex(program: t.Program): number { let lastRequireIdex = -1; - program.body.forEach((s, i) => { + for (const [i, s] of program.body.entries()) { const declaration = s.type === "VariableDeclaration" ? s.declarations[0] : undefined; if ( @@ -248,7 +233,7 @@ export function getLastRequireIndex(program: t.Program): number { ) { lastRequireIdex = i; } - }); + } return lastRequireIdex; } diff --git a/packages/cli/src/lib/wizard/utils/url.ts b/packages/cli/src/lib/wizard/utils/url.ts deleted file mode 100644 index 6d3af99d64..0000000000 --- a/packages/cli/src/lib/wizard/utils/url.ts +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Sentry URLs the wizards print after setup. - */ - -/** - * Returns the url to the Sentry project stream. - * - * Example: https://org-slug.sentry.io/issues/?project=1234567 - */ -export function getIssueStreamUrl({ - url, - orgSlug, - projectId, -}: { - url: string; - orgSlug: string; - projectId: string; -}): string { - const urlObject = new URL(url); - if (urlObject.host === "sentry.io") { - urlObject.host = `${orgSlug}.${urlObject.host}`; - urlObject.pathname = "/issues/"; - } else { - urlObject.pathname = `/organizations/${orgSlug}/issues/`; - } - urlObject.searchParams.set("project", projectId); - - return urlObject.toString(); -} diff --git a/packages/cli/test/lib/api/traces.test.ts b/packages/cli/test/lib/api/traces.test.ts index 1b7b0d06a2..2cdc4babac 100644 --- a/packages/cli/test/lib/api/traces.test.ts +++ b/packages/cli/test/lib/api/traces.test.ts @@ -594,9 +594,9 @@ describe("getSpanDetails", () => { const req = new Request(input, init); capturedUrl = req.url; const url = new URL(capturedUrl); - url.searchParams.forEach((v, k) => { + for (const [k, v] of url.searchParams) { capturedParams[k] = v; - }); + } return new Response(JSON.stringify(body), { status: 200, headers: { "Content-Type": "application/json" }, diff --git a/packages/cli/test/lib/dsn/fs-utils.test.ts b/packages/cli/test/lib/dsn/fs-utils.test.ts index a1b47c0da7..c637ac2761 100644 --- a/packages/cli/test/lib/dsn/fs-utils.test.ts +++ b/packages/cli/test/lib/dsn/fs-utils.test.ts @@ -5,6 +5,10 @@ * errors (ignored, debug-logged) from unexpected ones (reported to Sentry). */ +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; const { reportCliError } = vi.hoisted(() => ({ @@ -16,7 +20,8 @@ vi.mock("@sentry/node", () => ({ startSpan: (_opts: unknown, fn: () => unknown) => fn(), })); -const { handleFileError } = await import("../../../src/lib/dsn/fs-utils.js"); +const { findFile, handleFileError } = + await import("../../../src/lib/dsn/fs-utils.js"); /** Create an Error with a `code` property, mimicking Node/Bun errno errors. */ function errnoError(code: string, message?: string): Error { @@ -184,3 +189,39 @@ describe("handleFileError", () => { }); }); }); + +describe("findFile", () => { + let dir: string; + + beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), "find-file-")); + }); + + afterEach(async () => { + await rm(dir, { recursive: true, force: true }); + }); + + test("returns the first extension that exists, in order", async () => { + await writeFile(join(dir, "next.config.mjs"), ""); + await writeFile(join(dir, "next.config.cjs"), ""); + + expect(await findFile(join(dir, "next.config"))).toBe( + join(dir, "next.config.mjs"), + ); + }); + + test("skips a directory with a matching name", async () => { + await mkdir(join(dir, "next.config.js")); + await writeFile(join(dir, "next.config.ts"), ""); + + expect(await findFile(join(dir, "next.config"))).toBe( + join(dir, "next.config.ts"), + ); + }); + + test("returns undefined when no extension matches", async () => { + expect( + await findFile(join(dir, "vite.config"), [".js", ".ts"]), + ).toBeUndefined(); + }); +}); diff --git a/packages/cli/test/lib/sdk-positionals.property.test.ts b/packages/cli/test/lib/sdk-positionals.property.test.ts index 15b53cb35c..b1a45e503a 100644 --- a/packages/cli/test/lib/sdk-positionals.property.test.ts +++ b/packages/cli/test/lib/sdk-positionals.property.test.ts @@ -26,9 +26,9 @@ describe("positionals", () => { fcAssert( property(valuesArb, (values) => { const result = positionals(...values); - result.forEach((token, i) => { + for (const [i, token] of result.entries()) { expect(token).toBe(values[i] ?? ""); - }); + } }), { numRuns: DEFAULT_NUM_RUNS }, ); diff --git a/packages/cli/test/lib/sentry-urls.property.test.ts b/packages/cli/test/lib/sentry-urls.property.test.ts index 22027bdf10..1d4227b1ae 100644 --- a/packages/cli/test/lib/sentry-urls.property.test.ts +++ b/packages/cli/test/lib/sentry-urls.property.test.ts @@ -19,6 +19,7 @@ import { buildDashboardsListUrl, buildDashboardUrl, buildEventSearchUrl, + buildProjectIssuesUrl, buildLogsUrl, buildOrgSettingsUrl, buildOrgUrl, @@ -301,6 +302,21 @@ describe("buildEventSearchUrl properties", () => { }); }); +describe("buildProjectIssuesUrl", () => { + test("filters the org-subdomain issue stream to the project on SaaS", () => { + expect(buildProjectIssuesUrl("my-org", "1234567")).toBe( + "https://my-org.sentry.io/issues/?project=1234567", + ); + }); + + test("uses the organizations path on self-hosted", () => { + process.env["SENTRY_URL"] = "https://sentry.example.com"; + expect(buildProjectIssuesUrl("my-org", "42")).toBe( + "https://sentry.example.com/organizations/my-org/issues/?project=42", + ); + }); +}); + describe("buildOrgSettingsUrl properties", () => { test("without hash, output ends with trailing slash", async () => { fcAssert( diff --git a/packages/cli/test/lib/wizard/nextjs/utils.test.ts b/packages/cli/test/lib/wizard/nextjs/utils.test.ts index df026e57ed..cddd023814 100644 --- a/packages/cli/test/lib/wizard/nextjs/utils.test.ts +++ b/packages/cli/test/lib/wizard/nextjs/utils.test.ts @@ -89,13 +89,13 @@ describe("Next.js Utils", () => { const mockAppFolderPath = "/mock/app"; const supportedExtensions = ["jsx", "tsx", "js"]; - supportedExtensions.forEach((ext) => { + for (const ext of supportedExtensions) { (fs.existsSync as Mock).mockImplementation((filePath: string) => { return filePath === `/mock/app/layout.${ext}`; }); expect(hasRootLayoutFile(mockAppFolderPath)).toBe(true); - }); + } }); it("returns false when no layout file exists", () => { diff --git a/packages/cli/test/mocks/server.ts b/packages/cli/test/mocks/server.ts index 364b5b3f90..9e5b466d8c 100644 --- a/packages/cli/test/mocks/server.ts +++ b/packages/cli/test/mocks/server.ts @@ -69,12 +69,12 @@ function matchRoute( if (match) { const [, ...values] = match; const params: Record = {}; - route.paramNames.forEach((name, i) => { + for (const [i, name] of route.paramNames.entries()) { const value = values[i]; if (value !== undefined) { params[name] = value; } - }); + } return { route, params }; } } diff --git a/packages/mcp-cloudflare/src/client/components/chat/chat-messages.tsx b/packages/mcp-cloudflare/src/client/components/chat/chat-messages.tsx index 9aedb5d575..242541ed7f 100644 --- a/packages/mcp-cloudflare/src/client/components/chat/chat-messages.tsx +++ b/packages/mcp-cloudflare/src/client/components/chat/chat-messages.tsx @@ -24,34 +24,32 @@ function processMessages( // Only the very last text part of the very last message should be streaming const lastMessageIndex = messages.length - 1; - messages.forEach((message, messageIndex) => { + for (const [messageIndex, message] of messages.entries()) { const isLastMessage = messageIndex === lastMessageIndex; // Handle messages with parts array if (message.parts.length > 0) { const lastPartIndex = message.parts.length - 1; - message.parts.forEach( - (part: UIMessage["parts"][number], partIndex: number) => { - const isLastPartOfLastMessage = - isLastMessage && partIndex === lastPartIndex; + for (const [partIndex, part] of message.parts.entries()) { + const isLastPartOfLastMessage = + isLastMessage && partIndex === lastPartIndex; - allParts.push({ - part, - messageId: message.id, - messageRole: message.role, - partIndex, - // Stream if it's AI response OR local streaming simulation - isStreaming: - (isLastPartOfLastMessage && - isChatLoading && - part.type === "text") || - (part.type === "text" && !!isMessageStreaming?.(message.id)), - }); - }, - ); + allParts.push({ + part, + messageId: message.id, + messageRole: message.role, + partIndex, + // Stream if it's AI response OR local streaming simulation + isStreaming: + (isLastPartOfLastMessage && + isChatLoading && + part.type === "text") || + (part.type === "text" && !!isMessageStreaming?.(message.id)), + }); + } } - }); + } return allParts; } diff --git a/packages/mcp-core/chart-app/chart.ts b/packages/mcp-core/chart-app/chart.ts index 569d49cdd4..78c9f684ea 100644 --- a/packages/mcp-core/chart-app/chart.ts +++ b/packages/mcp-core/chart-app/chart.ts @@ -256,7 +256,7 @@ export function drawChart( const single = chart.series.length === 1; const path = (pts: readonly Point[]) => pts.map(([px, py], i) => `${i ? "L" : "M"}${px},${py}`).join(""); - chart.series.forEach((series, index) => { + for (const [index, series] of chart.series.entries()) { const color = SERIES_COLORS[index % SERIES_COLORS.length] ?? "#7553ff"; // Runs of buckets with data. A null bucket ends a run, so it draws as a // gap instead of a drop to 0. @@ -306,7 +306,7 @@ export function drawChart( ); } } - }); + } const crosshair = svg( "line", @@ -397,11 +397,11 @@ export function drawChart( } const time = first + ((px - MARGIN.left) / plotWidth) * span; let nearest = 0; - times.forEach((t, i) => { + for (const [i, t] of times.entries()) { if (Math.abs(t - time) < Math.abs((times[nearest] ?? 0) - time)) { nearest = i; } - }); + } showAt(nearest); }); root.addEventListener("pointerleave", hide); diff --git a/packages/mcp-core/src/api-client/client-request-paths.test.ts b/packages/mcp-core/src/api-client/client-request-paths.test.ts index c4b347c859..b0f893bb48 100644 --- a/packages/mcp-core/src/api-client/client-request-paths.test.ts +++ b/packages/mcp-core/src/api-client/client-request-paths.test.ts @@ -35,9 +35,9 @@ describe("client.ts request path invariant", () => { it("interpolates every request path through apiPath", () => { const offenders: string[] = []; - source.split("\n").forEach((line, index) => { + for (const [index, line] of source.split("\n").entries()) { const trimmed = line.trim(); - if (trimmed.startsWith("//") || trimmed.startsWith("*")) return; + if (trimmed.startsWith("//") || trimmed.startsWith("*")) continue; // A template literal opening with a slash is an API request path. for (let i = 0; i < line.length - 1; i++) { @@ -53,7 +53,7 @@ describe("client.ts request path invariant", () => { offenders.push(`${index + 1}: ${trimmed}`); } } - }); + } expect( offenders, diff --git a/packages/mcp-core/src/internal/issue-side-quests.test.ts b/packages/mcp-core/src/internal/issue-side-quests.test.ts index 894aab0c0a..6fa41fde2c 100644 --- a/packages/mcp-core/src/internal/issue-side-quests.test.ts +++ b/packages/mcp-core/src/internal/issue-side-quests.test.ts @@ -24,11 +24,9 @@ function eventWithFourFiles() { if (!("rawStacktrace" in value)) { continue; } - value.rawStacktrace.frames.forEach( - (frame: { absPath: string | null }, index: number) => { - frame.absPath = files[index] ?? frame.absPath; - }, - ); + for (const [index, frame] of value.rawStacktrace.frames.entries()) { + frame.absPath = files[index] ?? frame.absPath; + } } } return EventSchema.parse({ diff --git a/packages/mcp-core/src/internal/side-quests.ts b/packages/mcp-core/src/internal/side-quests.ts index be29b1e1a5..06e18f95d8 100644 --- a/packages/mcp-core/src/internal/side-quests.ts +++ b/packages/mcp-core/src/internal/side-quests.ts @@ -122,9 +122,9 @@ function recordSideQuests(ids: string[], max: number) { "app.side_quests.detected": ids.length, "app.side_quests.shown": shown.length, }; - ids.forEach((id, index) => { + for (const [index, id] of ids.entries()) { attributes[`app.side_quest.${id}`] = index < max ? "shown" : "capped"; - }); + } getActiveSpan()?.setAttributes(attributes); for (const id of shown) { metrics.count("app.side_quest.shown", 1, { diff --git a/packages/mcp-core/src/internal/source-map-diagnosis.ts b/packages/mcp-core/src/internal/source-map-diagnosis.ts index 6ae0968dfc..d1519414f3 100644 --- a/packages/mcp-core/src/internal/source-map-diagnosis.ts +++ b/packages/mcp-core/src/internal/source-map-diagnosis.ts @@ -101,17 +101,17 @@ function getDebugFramesByPath(event: Event, debug: SourceMapDebug) { } return parsed.data.values ?? (parsed.data.value ? [parsed.data.value] : []); }); - values.forEach((value, exceptionIndex) => { + for (const [exceptionIndex, value] of values.entries()) { const rawFrames = value?.rawStacktrace?.frames ?? []; - rawFrames.forEach((rawFrame, frameIndex) => { + for (const [frameIndex, rawFrame] of rawFrames.entries()) { const path = rawFrame.absPath; // the check can return fewer exceptions or frames than the event has const frame = debug.exceptions.at(exceptionIndex)?.frames.at(frameIndex); if (path && frame && !frames.has(path)) { frames.set(path, frame); } - }); - }); + } + } return frames; } diff --git a/packages/mcp-core/src/tools/catalog/get-event-attachment.ts b/packages/mcp-core/src/tools/catalog/get-event-attachment.ts index 44591e0df7..1ab6b10733 100644 --- a/packages/mcp-core/src/tools/catalog/get-event-attachment.ts +++ b/packages/mcp-core/src/tools/catalog/get-event-attachment.ts @@ -221,7 +221,7 @@ export default defineTool({ output += `Found ${attachments.length} attachment(s):\n\n`; - attachments.forEach((attachment, index) => { + for (const [index, attachment] of attachments.entries()) { output += `## Attachment ${index + 1}\n\n`; output += `**ID:** ${attachment.id}\n`; output += `**Name:** ${attachment.name}\n`; @@ -242,7 +242,7 @@ export default defineTool({ availableToolNames: context.availableToolNames, directToolNames: context.directToolNames, })}\n\n`; - }); + } return output; }, diff --git a/packages/mcp-core/src/tools/support/profile/analyzer.ts b/packages/mcp-core/src/tools/support/profile/analyzer.ts index 70c89eeacf..8900f03c64 100644 --- a/packages/mcp-core/src/tools/support/profile/analyzer.ts +++ b/packages/mcp-core/src/tools/support/profile/analyzer.ts @@ -338,15 +338,15 @@ export function compareFrameStats( { baselineIdx?: number; currentIdx?: number } >(); - baselineFrames.forEach((frame, idx) => { + for (const [idx, frame] of baselineFrames.entries()) { const existing = frameMap.get(frame.fingerprint) || {}; frameMap.set(frame.fingerprint, { ...existing, baselineIdx: idx }); - }); + } - currentFrames.forEach((frame, idx) => { + for (const [idx, frame] of currentFrames.entries()) { const existing = frameMap.get(frame.fingerprint) || {}; frameMap.set(frame.fingerprint, { ...existing, currentIdx: idx }); - }); + } // Compare frames that exist in both const comparisons: FrameComparison[] = []; diff --git a/packages/mcp-core/src/tools/support/profile/flamegraph-output.ts b/packages/mcp-core/src/tools/support/profile/flamegraph-output.ts index 848a6963ee..16df286e86 100644 --- a/packages/mcp-core/src/tools/support/profile/flamegraph-output.ts +++ b/packages/mcp-core/src/tools/support/profile/flamegraph-output.ts @@ -178,15 +178,15 @@ export function buildFlamegraphAnalysis( // both overlap across nested frames, so they cannot be summed. const totalNs = sumOf(mainProfile?.sample_durations_ns); let userCodeNs = 0; - mainProfile?.samples.forEach((stack, index) => { + for (const [index, stack] of (mainProfile?.samples ?? []).entries()) { const leafIndex = stack.at(-1); if ( leafIndex !== undefined && flamegraph.shared.frames[leafIndex]?.is_application ) { - userCodeNs += mainProfile.sample_durations_ns[index] ?? 0; + userCodeNs += mainProfile?.sample_durations_ns[index] ?? 0; } - }); + } const outputFrames: FlamegraphAnalysis["frames"] = []; const outputIndexBySource = new Map(); diff --git a/packages/mcp-core/src/tools/support/search-events/replays.ts b/packages/mcp-core/src/tools/support/search-events/replays.ts index 9d3dc817b3..45b9003865 100644 --- a/packages/mcp-core/src/tools/support/search-events/replays.ts +++ b/packages/mcp-core/src/tools/support/search-events/replays.ts @@ -312,7 +312,7 @@ export function formatReplayResults(params: FormatReplayResultsParams): string { output += `Found **${replays.length}** replay${replays.length === 1 ? "" : "s"}:\n\n`; - replays.forEach((replay, index) => { + for (const [index, replay] of replays.entries()) { const replayUrl = apiService.getReplayUrl(organizationSlug, replay.id); const user = formatReplayUser(replay); const clickSummary = [ @@ -343,7 +343,7 @@ export function formatReplayResults(params: FormatReplayResultsParams): string { } output += "\n"; - }); + } output += "## Next Steps\n\n"; const replayDetailsInstruction = formatToolCallInstruction({ diff --git a/packages/mcp-core/src/tools/support/search-events/utils.ts b/packages/mcp-core/src/tools/support/search-events/utils.ts index af4975d8b2..131472ef92 100644 --- a/packages/mcp-core/src/tools/support/search-events/utils.ts +++ b/packages/mcp-core/src/tools/support/search-events/utils.ts @@ -1348,21 +1348,18 @@ export function createDatasetAttributesTool(options: { let commonFields: Record = {}; let datasetFields: Record = {}; if (substringMatch) { - Object.entries(BASE_COMMON_FIELDS).forEach(([key, value]) => { + for (const [key, value] of Object.entries(BASE_COMMON_FIELDS)) { if (key.includes(substringMatch) || value.includes(substringMatch)) { commonFields[key] = value; } - }); - Object.entries(DATASET_FIELDS[normalizedDataset]).forEach( - ([key, value]) => { - if ( - key.includes(substringMatch) || - value.includes(substringMatch) - ) { - datasetFields[key] = value; - } - }, - ); + } + for (const [key, value] of Object.entries( + DATASET_FIELDS[normalizedDataset], + )) { + if (key.includes(substringMatch) || value.includes(substringMatch)) { + datasetFields[key] = value; + } + } } else { commonFields = BASE_COMMON_FIELDS; datasetFields = DATASET_FIELDS[normalizedDataset]; From ac6b75d40aa9bc5a13bab92a14f1612b0d165343 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:06:39 +0000 Subject: [PATCH 10/20] feat(cli): use positionals and existing CLI flags in sentry wizard `sentry wizard [/] []` replaces the `@sentry/wizard` flags, with the target first like other commands. - The integration is a positional, one at a time. A bare integration id is never read as a target, and a single bare word is always read as an integration, so a project or org spelled like one is written `my-org/nextjs`, `nextjs/` or `/nextjs`. - The target parses with the CLI's org/project grammar and resolves after login with `resolveOrgOptionalTarget`, like other commands. Without one the org and project pickers run, with no detection. - `-f/--force` is the only flag. It sets both `forceInstall` and `ignoreGitChanges`. - The instance comes from `SENTRY_URL` or the stored login, so the SaaS/self-hosted prompt, `--url`, `--saas` and `skipRcUrlCheck` go. - Spotlight mode follows `SENTRY_SPOTLIGHT`, telemetry follows `isTelemetryEnabled()`, and debug output goes through the CLI logger (`--verbose`, `--log-level`). - Every other `@sentry/wizard` flag and `SENTRY_WIZARD_*` variable is gone, hidden ones included, with `disableTelemetryForRun` and `rejectRemovedFlags`. A test pins the wizard's own flags to `force`, and `check:env-coverage` (part of `ci:policy`) fails when any file under `src/` names `SENTRY_WIZARD_`. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .../cli-docs/src/fragments/commands/wizard.md | 51 ++- .../sentry-cli/skills/sentry-cli/SKILL.md | 2 +- .../skills/sentry-cli/references/wizard.md | 30 +- packages/cli/script/check-env-coverage.ts | 37 +- packages/cli/src/commands/wizard.ts | 346 +++++++++--------- packages/cli/src/lib/env-registry.ts | 25 +- packages/cli/src/lib/telemetry.ts | 13 - packages/cli/src/lib/wizard/run.ts | 47 +-- packages/cli/src/lib/wizard/telemetry.ts | 9 +- .../cli/src/lib/wizard/utils/clack/index.ts | 8 +- packages/cli/src/lib/wizard/utils/debug.ts | 31 +- .../cli/src/lib/wizard/utils/project-data.ts | 120 +----- packages/cli/src/lib/wizard/utils/types.ts | 32 +- packages/cli/test/commands/wizard.test.ts | 253 +++++++++---- .../lib/wizard/utils/project-data.test.ts | 127 +++++-- 15 files changed, 592 insertions(+), 539 deletions(-) diff --git a/apps/cli-docs/src/fragments/commands/wizard.md b/apps/cli-docs/src/fragments/commands/wizard.md index d754b8845b..91218e9918 100644 --- a/apps/cli-docs/src/fragments/commands/wizard.md +++ b/apps/cli-docs/src/fragments/commands/wizard.md @@ -4,13 +4,29 @@ `sentry wizard` sets up the Sentry SDK in the project in the current directory. It asks a few questions, installs the SDK for your framework, -writes its configuration, and sets up source map or debug file uploads. -Pass `-i` with an integration, such as `nextjs`, to skip the integration -picker. +writes its configuration, and sets up source map or debug file uploads. It +takes an optional `/` first, then an optional integration: + +- Pass an integration, such as `nextjs`, to skip the integration picker. +- Pass `/` first to skip the org and project pickers, or + `/` to pick only the project. Without it, the wizard asks; it doesn't + detect a project from your files. +- An integration id is never read as a project or org, and a single bare + word is always read as an integration. Write a project or org with a `/`: + `my-org/my-project`, `my-org/`, or `/my-project`. For a project spelled + like an integration, write `my-org/nextjs`. +- `-f`/`--force` changes a project with uncommitted changes without asking, + and installs the SDK even when the package manager's checks fail. It logs in with your `sentry auth login` account, or starts a login when you -have none, and lets you pick or create the Sentry project to send data to. -Pass `--org` and `--project` to skip those questions. +have none, on the Sentry instance the rest of the CLI uses: `SENTRY_URL`, or +the stored login's. To use a self-hosted instance, log in to it first with +`sentry auth login --url`. + +Set `SENTRY_SPOTLIGHT=1` to set up Spotlight for local development instead, +with no Sentry account or login. Telemetry follows the CLI's settings +(`SENTRY_CLI_NO_TELEMETRY`, `DO_NOT_TRACK`, `sentry cli defaults`), and the +global `--verbose` flag shows the wizard's debug output. `sentry wizard` changes your project's files. To have a coding agent set up Sentry instead, run `sentry init`, which prints the agent's setup guide and @@ -18,12 +34,19 @@ changes nothing. ## Coming from `@sentry/wizard` -`sentry wizard` takes the same integrations and flags as -`npx @sentry/wizard`, so `npx @sentry/wizard -i nextjs` and -`sentry wizard -i nextjs` do the same thing. These were removed: - -- The sign-up flags `--signup`, `--promo-code` and `--coming-from`. Passing one - fails with an explanation. Sign up at https://sentry.io/signup/ (and apply a - promo code there), then run the wizard. -- The Cordova and Electron wizards. Follow their setup guides in the Sentry - docs instead. +`sentry wizard` takes the same integration ids as `npx @sentry/wizard -i`, +but not its flags or `SENTRY_WIZARD_*` environment variables: + +| `@sentry/wizard` | `sentry wizard` | +| -------------------------------------- | ------------------------------------------------ | +| `-i nextjs` | `nextjs` | +| `--org my-org --project my-project` | `my-org/my-project`, before the integration | +| `--url`, `-u`, `--saas` | `sentry auth login --url`, or `SENTRY_URL` | +| `--spotlight` | `SENTRY_SPOTLIGHT=1` | +| `--force-install`, `--ignore-git-changes` | `-f`/`--force` | +| `--disable-telemetry` | `SENTRY_CLI_NO_TELEMETRY=1` or `DO_NOT_TRACK=1` | +| `--debug` | `--verbose` or `--log-level debug` | +| `--signup`, `--promo-code`, `--coming-from` | Sign up at https://sentry.io/signup/ first | + +The Cordova and Electron wizards were retired. Follow their setup guides in +the Sentry docs instead. diff --git a/packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md b/packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md index 963ccb51a1..d5dc5253d3 100644 --- a/packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md +++ b/packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md @@ -818,7 +818,7 @@ Print instructions for a coding agent to set up Sentry Set up the Sentry SDK in your project interactively -- `sentry wizard` — Set up the Sentry SDK in your project interactively +- `sentry wizard [/] []` — Set up the Sentry SDK in your project interactively → Full flags and examples: `references/wizard.md` diff --git a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md index 7e8405f3e0..fe5382422e 100644 --- a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md +++ b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md @@ -11,33 +11,33 @@ requires: Set up the Sentry SDK in your project interactively -### `sentry wizard` +### `sentry wizard [/] []` Set up the Sentry SDK in your project interactively +**Arguments:** + +| Argument | Description | +|----------|-------------| +| `[/] []` | <org>/<project> to set up (skips the project picker), then the integration (skips the integration picker) | + **Flags:** -- `-i, --integration - Integration to set up (skips the picker)` -- `-u, --url - URL of your self-hosted Sentry instance` -- `--org - Slug of the Sentry organization to use` -- `--project - Slug of the Sentry project to use` -- `--saas - Use Sentry SaaS (sentry.io) without asking` -- `--spotlight - Set up Spotlight for local development, without a Sentry account` -- `--force-install - Install the SDK even when the package manager's checks fail` -- `--ignore-git-changes - Don't ask before changing a project with uncommitted changes` -- `--disable-telemetry - Don't send telemetry about this run to Sentry` -- `--debug - Print the wizard's debug output` +- `-f, --force - Change a project with uncommitted changes without asking, and install the SDK even when the package manager's checks fail` **Examples:** ```bash -# Pick an integration and set it up +# Pick an integration and a project, then set it up sentry wizard -# Set up Next.js for a known org and project on sentry.io -sentry wizard -i nextjs --saas --org my-org --project my-project +# Set up Next.js, picking the project +sentry wizard nextjs + +# Set up Next.js for a known org and project +sentry wizard my-org/my-project nextjs # Set up Next.js for Spotlight, without a Sentry account -sentry wizard -i nextjs --spotlight +SENTRY_SPOTLIGHT=1 sentry wizard nextjs ``` All commands also support `--json`, `--fields`, `--help`, `--log-level`, and `--verbose` flags. diff --git a/packages/cli/script/check-env-coverage.ts b/packages/cli/script/check-env-coverage.ts index c07ddd5fc9..92e7d6c431 100644 --- a/packages/cli/script/check-env-coverage.ts +++ b/packages/cli/script/check-env-coverage.ts @@ -15,13 +15,17 @@ * test-only hooks, and vars inherited from the SDK are listed (with a reason) in * INTERNAL_ENV_VARS so their exclusion is explicit and reviewable. * + * It also fails when any file under src/ names a prefix in + * RETIRED_ENV_PREFIXES, such as the `SENTRY_WIZARD_*` vars of `@sentry/wizard`. + * * Usage: * pnpm ts script/check-env-coverage.ts * * Exit codes: * 0 - Every user-facing env var read by the CLI or an installer is documented * or explicitly internal - * 1 - Coverage gap, redundant allowlist entry, or stale allowlist entry + * 1 - Coverage gap, redundant allowlist entry, stale allowlist entry, or a + * retired env var prefix (RETIRED_ENV_PREFIXES) under src/ */ import { readFile } from "node:fs/promises"; @@ -51,10 +55,6 @@ const INTERNAL_ENV_VARS = new Map([ "SENTRY_ENVIRONMENT", "bash-hook traceback template only; inherited SDK convention", ], - [ - "SENTRY_SPOTLIGHT", - "set by `local run` for the child app; the CLI only names it in Worker setup hints", - ], [ "SENTRY_TRACES_SAMPLE_RATE", "inherited from the SDK when spawning subprocesses, not a CLI config knob", @@ -79,6 +79,17 @@ const INTERNAL_ENV_VARS = new Map([ ["SENTRY_RN_SOURCEMAP_REPORT", "internal react-native wrapper plumbing"], ]); +/** + * Env var prefixes the CLI dropped on purpose. No file under src/ may name + * one, read or not, so none comes back as a hidden alias. Each has a reason. + */ +const RETIRED_ENV_PREFIXES = new Map([ + [ + "SENTRY_WIZARD_", + "`sentry wizard` takes `/` and the integration as positionals, and reads only the CLI's own env vars (SENTRY_URL, SENTRY_SPOTLIGHT, SENTRY_LOG_LEVEL)", + ], +]); + const registryNames = new Set(ENV_VAR_REGISTRY.map((entry) => entry.name)); /** @@ -230,6 +241,22 @@ for (const name of INTERNAL_ENV_VARS.keys()) { } } +// Every file type under src/, generated files included, not just the env +// reads above: a retired name in a string or a comment fails too. +for (const file of await glob("src/**/*")) { + const content = await readFile(file, "utf-8"); + for (const [prefix, reason] of RETIRED_ENV_PREFIXES) { + const index = content.indexOf(prefix); + if (index !== -1) { + const line = content.slice(0, index).split("\n").length; + errors.push( + `Retired env var prefix: ${prefix} (at ${file}:${line})\n` + + ` Remove it: ${reason}.`, + ); + } + } +} + if (errors.length > 0) { logger.error( [ diff --git a/packages/cli/src/commands/wizard.ts b/packages/cli/src/commands/wizard.ts index 71f4b7fefd..01311bd7a6 100644 --- a/packages/cli/src/commands/wizard.ts +++ b/packages/cli/src/commands/wizard.ts @@ -3,244 +3,226 @@ * * Run the interactive setup wizard of a framework or platform: it installs * the Sentry SDK, writes its config files, and sets up source map or debug - * file uploads in the current project. Ported from `@sentry/wizard`, whose - * `-i ` invocations keep working. + * file uploads in the current project. Ported from `@sentry/wizard`. * * The wizard logs in with the CLI's own login instead of the old browser - * hand-off, so `auth: false` here: a run in Spotlight mode, or with a - * preselected project, needs no login at all. + * hand-off, so `auth: false` here: a run in Spotlight mode needs no login at + * all. */ import type { SentryContext } from "../context.js"; -import { buildCommand } from "../lib/command.js"; +import { sentry } from "../lib/app-identity.js"; import { - parseOrgSlug, - parseProjectSlug, - parseText, - parseUrl, -} from "../lib/completion-target.js"; + type ParsedOrgProject, + parseOrgProjectInput, +} from "../lib/arg-parsing.js"; +import { buildCommand } from "../lib/command.js"; +import { ORG_PROJECT_TARGET } from "../lib/completion-target.js"; import { getEnv } from "../lib/env.js"; import { ValidationError, WizardExitError } from "../lib/errors.js"; +import { parseBoolValue } from "../lib/parse-bool.js"; import { - disableTelemetryForRun, - isTelemetryEnabled, -} from "../lib/telemetry.js"; -import { INTEGRATION_IDS, runWizard } from "../lib/wizard/run.js"; + type BoundArguments, + boundArguments, +} from "../lib/positional-parse.js"; +import { applySentryUrlContext } from "../lib/sentry-url-parser.js"; +import { isTelemetryEnabled } from "../lib/telemetry.js"; +import { + INTEGRATION_IDS, + runWizard, + type WizardIntegration, +} from "../lib/wizard/run.js"; import { topLevelBrief } from "../top-level-briefs.js"; +const USAGE = "[/] []"; +const usageHint = () => sentry`wizard ${USAGE}`; + type WizardFlags = { - readonly integration?: string; - readonly url?: string; - readonly org?: string; - readonly project?: string; - readonly saas: boolean; - readonly debug: boolean; - readonly spotlight: boolean; - readonly "disable-telemetry": boolean; - readonly "force-install": boolean; - readonly "ignore-git-changes": boolean; - readonly signup: boolean; - readonly "promo-code"?: string; - readonly "coming-from"?: string; - readonly "skip-connect": boolean; - readonly quiet: boolean; - readonly uninstall: boolean; + readonly force: boolean; }; +/** Parsed `sentry wizard` arguments. */ +export type WizardInput = { + /** The org and project to set up; auto-detect means the user picks */ + readonly target: ParsedOrgProject; + /** Server of a pasted Sentry URL, applied when the arguments resolve */ + readonly baseUrl?: string; + /** The integration to set up; the user picks when unset */ + readonly integration?: WizardIntegration; +}; + +/** The arguments of `sentry wizard`. */ +export type WizardArguments = BoundArguments; + +/** Whether `value` is exactly one of {@link INTEGRATION_IDS}. */ +function isIntegrationId(value: string): value is WizardIntegration { + return (INTEGRATION_IDS as readonly string[]).includes(value); +} + /** - * Fail on the `@sentry/wizard` sign-up and partner flags, which `sentry - * wizard` dropped: it logs in with the CLI's login, which has no sign-up or - * partner step. + * The error for an argument in the integration position that names none. * - * @throws {ValidationError} When one of them is passed + * @param hint - Extra line saying how to name a target instead */ -function rejectRemovedFlags(flags: WizardFlags): void { - const removed = [ - flags.signup ? "--signup" : undefined, - flags["promo-code"] === undefined ? undefined : "--promo-code", - flags["coming-from"] === undefined ? undefined : "--coming-from", - ].filter((flag) => flag !== undefined); - if (removed.length === 0) { - return; - } - throw new ValidationError( - `${removed.join(", ")} ${removed.length === 1 ? "is" : "are"} no longer supported. ` + - "Sign up at https://sentry.io/signup/ (and apply any promo code there), " + - "then run the wizard again without " + - `${removed.length === 1 ? "it" : "them"}.`, - removed[0], +function unknownIntegration(value: string, hint = ""): ValidationError { + return new ValidationError( + `Unknown integration '${value}'. Pick one of: ${INTEGRATION_IDS.join(", ")}.\n` + + `${hint} Usage: ${usageHint()}`, + "integration", ); } -/** The trimmed value of the environment variable `name`, unless empty. */ -function envValue(name: string): string | undefined { - return getEnv()[name]?.trim() || undefined; +/** + * Parse the positionals of `sentry wizard`: `[/] []`. + * Has no side effects. + * + * - No arguments: the user picks both. + * - One argument: a bare word is the integration. A target always has a `/` + * (`/`, `/`, `/`) or is a Sentry URL. + * - Two arguments: the target, then the integration. The first may be any + * target form, including a bare project or org slug, except an + * integration id. + * + * A bare integration id is never a target, in either position: an org or + * project spelled like one is written `/nextjs`, `nextjs/` or + * `/nextjs`. + * + * @throws {ValidationError} For more than two arguments, an unknown + * integration, two integrations, or a malformed target + */ +export function parseWizardArguments(args: readonly string[]): WizardInput { + const [first, second, ...extra] = args; + if (extra.length > 0) { + throw new ValidationError( + `Too many arguments: ${extra.join(" ")}. Expected: ${usageHint()}`, + "positional", + ); + } + if (first === undefined) { + return { target: { type: "auto-detect" } }; + } + if (second === undefined) { + if (isIntegrationId(first)) { + return { target: { type: "auto-detect" }, integration: first }; + } + if (!first.includes("/")) { + throw unknownIntegration( + first, + " To name an org or project instead, write it as /, / or /.\n", + ); + } + } else if (isIntegrationId(first)) { + throw new ValidationError( + `'${first}' is an integration, and the wizard sets up one at a time.\n` + + ` To name a project or org called '${first}', write it as /${first}, ${first}/ or /${first}.\n` + + ` Usage: ${usageHint()}`, + "integration", + ); + } else if (!isIntegrationId(second)) { + throw unknownIntegration(second); + } + const { parsed, baseUrl } = parseOrgProjectInput(first); + return { + target: parsed, + ...(baseUrl && { baseUrl }), + ...(second !== undefined && { integration: second }), + }; +} + +/** + * Whether `SENTRY_SPOTLIGHT` turns on Spotlight mode. Like the Sentry SDKs, + * any value but an empty or false-like one (`0`, `false`, `off`, …) counts, + * including a Spotlight URL. + */ +function isSpotlightEnabled(): boolean { + const value = getEnv()["SENTRY_SPOTLIGHT"]?.trim(); + return value ? parseBoolValue(value) !== false : false; } export const wizardCommand = buildCommand({ auth: false, - // The wizard picks the Sentry instance itself (`--url`, `--saas` or a - // prompt) before it logs in, like `sentry init`. - skipRcUrlCheck: true, docs: { brief: topLevelBrief("wizard"), + customUsage: [USAGE], fullDescription: "Set up Sentry in the project in the current directory. The wizard " + "asks you a few questions, installs the Sentry SDK for your framework, " + "writes its configuration, and sets up source map or debug file " + - "uploads. It logs in with your `sentry auth login` account (or starts " + - "a login), and lets you pick or create the Sentry project to send " + - "data to.\n\n" + - "Pass `-i` to skip the integration picker. It takes the same " + - "integrations and flags as `npx @sentry/wizard`, except the sign-up " + - "flags `--signup`, `--promo-code` and `--coming-from`, which fail: " + - "sign up at https://sentry.io/signup/ first.\n\n" + + "uploads.\n\n" + + "It logs in with your `sentry auth login` account (or starts a login) " + + "on the Sentry instance the rest of the CLI uses, and lets you pick or " + + "create the Sentry project to send data to. Pass `/` " + + "first to skip those questions, or `/` to pick only the project. " + + "Pass an integration, such as `nextjs`, to skip the integration " + + `picker. Integrations: ${INTEGRATION_IDS.join(", ")}.\n\n` + + "An integration id is never read as a project or org, and a single " + + "bare word is always read as an integration. To name a project or " + + "org, write it with a `/`: `my-org/my-project`, `my-org/`, or " + + "`/my-project` (for a project spelled like an integration, " + + "`my-org/nextjs`).\n\n" + + "Set `SENTRY_SPOTLIGHT=1` to set up Spotlight for local development " + + "instead, without a Sentry account or login. Use the global " + + "`--verbose` flag for the wizard's debug output.\n\n" + "The wizard changes files in your project. To have a coding agent set " + "up Sentry instead, run `sentry init`, which prints the agent's setup " + "guide and changes nothing.", examples: [ { - description: "Pick an integration and set it up", + description: "Pick an integration and a project, then set it up", run: "wizard", }, { - description: "Set up Next.js for a known org and project on sentry.io", - run: "wizard -i nextjs --saas --org my-org --project my-project", + description: "Set up Next.js, picking the project", + run: "wizard nextjs", + }, + { + description: "Set up Next.js for a known org and project", + run: "wizard my-org/my-project nextjs", }, { description: "Set up Next.js for Spotlight, without a Sentry account", - run: "wizard -i nextjs --spotlight", + run: { prefix: "SENTRY_SPOTLIGHT=1 ", args: "wizard nextjs" }, }, ], }, parameters: { + positional: boundArguments({ + placeholder: "org/project-or-integration", + brief: + "/ to set up (skips the project picker), then the integration (skips the integration picker)", + kind: ORG_PROJECT_TARGET, + parse: parseWizardArguments, + // The org and project resolve after the wizard logs in; only a pasted + // URL's server applies here, before the login picks an instance. + resolve: async (input) => { + if (input.baseUrl) { + applySentryUrlContext(input.baseUrl); + } + return input; + }, + }), flags: { - integration: { - kind: "enum", - values: INTEGRATION_IDS, - brief: "Integration to set up (skips the picker)", - optional: true, - }, - url: { - kind: "parsed", - parse: parseUrl, - brief: "URL of your self-hosted Sentry instance", - placeholder: "url", - optional: true, - }, - org: { - kind: "parsed", - parse: parseOrgSlug, - brief: "Slug of the Sentry organization to use", - placeholder: "org", - optional: true, - }, - project: { - kind: "parsed", - parse: parseProjectSlug, - brief: "Slug of the Sentry project to use", - placeholder: "project", - optional: true, - }, - saas: { - kind: "boolean", - brief: "Use Sentry SaaS (sentry.io) without asking", - default: false, - }, - spotlight: { + force: { kind: "boolean", brief: - "Set up Spotlight for local development, without a Sentry account", - default: false, - }, - "force-install": { - kind: "boolean", - brief: "Install the SDK even when the package manager's checks fail", - default: false, - }, - "ignore-git-changes": { - kind: "boolean", - brief: "Don't ask before changing a project with uncommitted changes", - default: false, - }, - "disable-telemetry": { - kind: "boolean", - brief: "Don't send telemetry about this run to Sentry", - default: false, - }, - debug: { - kind: "boolean", - brief: "Print the wizard's debug output", - default: false, - }, - // `@sentry/wizard`'s sign-up and partner flags. The wizard logs in - // with the CLI's login, which has no sign-up or partner step, so these - // fail with an explanation instead of being dropped silently. - signup: { - kind: "boolean", - brief: "Removed: sign up at https://sentry.io/signup/ first", - default: false, - hidden: true as const, - }, - "promo-code": { - kind: "parsed", - parse: parseText, - brief: "Removed: apply promo codes when you sign up", - placeholder: "code", - optional: true, - hidden: true as const, - }, - "coming-from": { - kind: "parsed", - parse: parseText, - brief: "Removed: partner sign-up is not supported", - placeholder: "partner", - optional: true, - hidden: true as const, - }, - // Flags `@sentry/wizard` accepted that no flow reads any more. Kept so - // copied commands still run. - "skip-connect": { - kind: "boolean", - brief: "Ignored", + "Change a project with uncommitted changes without asking, and install the SDK even when the package manager's checks fail", default: false, - hidden: true as const, - }, - quiet: { - kind: "boolean", - brief: "Ignored", - default: false, - hidden: true as const, - }, - uninstall: { - kind: "boolean", - brief: "Ignored: only the retired Cordova wizard could uninstall", - default: false, - hidden: true as const, }, }, - aliases: { i: "integration", u: "url", s: "signup" }, + aliases: { f: "force" }, }, // oxlint-disable-next-line require-yield -- The wizard prints its own interactive output; the command yields none. - async *func(this: SentryContext, flags: WizardFlags) { - rejectRemovedFlags(flags); - if (flags["disable-telemetry"]) { - disableTelemetryForRun(); - } - + async *func(this: SentryContext, flags: WizardFlags, args: WizardArguments) { + const { target, integration } = await args.resolved; try { await runWizard({ - integration: flags.integration ?? envValue("SENTRY_WIZARD_INTEGRATION"), - debug: flags.debug || envValue("SENTRY_WIZARD_DEBUG") === "true", + integration, wizardOptions: { - telemetryEnabled: !flags["disable-telemetry"] && isTelemetryEnabled(), - url: flags.url ?? envValue("SENTRY_WIZARD_URL"), - orgSlug: flags.org, - projectSlug: flags.project, - saas: flags.saas, - forceInstall: flags["force-install"], - ignoreGitChanges: flags["ignore-git-changes"], - spotlight: flags.spotlight, + telemetryEnabled: isTelemetryEnabled(), + target, + forceInstall: flags.force, + ignoreGitChanges: flags.force, + spotlight: isSpotlightEnabled(), }, }); } catch (error) { diff --git a/packages/cli/src/lib/env-registry.ts b/packages/cli/src/lib/env-registry.ts index b9b5edb556..52d355f748 100644 --- a/packages/cli/src/lib/env-registry.ts +++ b/packages/cli/src/lib/env-registry.ts @@ -139,24 +139,6 @@ export const ENV_VAR_REGISTRY: readonly EnvVarEntry[] = [ selfHosted: true, devGuide: "Sentry OAuth app client ID", }, - { - name: "SENTRY_WIZARD_INTEGRATION", - description: - "Integration for `sentry wizard` to set up when `-i` is not passed, such as `nextjs`. Kept from `@sentry/wizard`.", - example: "nextjs", - }, - { - name: "SENTRY_WIZARD_URL", - description: - "URL of the self-hosted Sentry instance for `sentry wizard` when `--url` is not passed. Kept from `@sentry/wizard`.", - example: "https://sentry.example.com", - }, - { - name: "SENTRY_WIZARD_DEBUG", - description: - "Set to `true` to print the debug output of `sentry wizard`, like `--debug`. Kept from `@sentry/wizard`.", - example: "true", - }, { name: "SENTRY_HANDOFF", description: @@ -220,6 +202,13 @@ export const ENV_VAR_REGISTRY: readonly EnvVarEntry[] = [ example: "1", installOnly: true, }, + // -- Local development -- + { + name: "SENTRY_SPOTLIGHT", + description: + "Turns on Spotlight, the local debugger, in Sentry SDKs. Set it to `1`, `true`, or a Spotlight URL when running `sentry wizard` to set up Spotlight for local development instead of a Sentry project, with no login. Empty, `0`, `false`, and `off` leave it off. `sentry local run` sets it for the app it runs.", + example: "1", + }, // -- Games -- { name: "SENTRY_GAMES_API_URL", diff --git a/packages/cli/src/lib/telemetry.ts b/packages/cli/src/lib/telemetry.ts index b4e32c1640..2467c3f349 100644 --- a/packages/cli/src/lib/telemetry.ts +++ b/packages/cli/src/lib/telemetry.ts @@ -176,19 +176,6 @@ export function isTelemetryEnabled(): boolean { return computeTelemetryEffective().enabled; } -/** - * Stop sending telemetry for the rest of this run, after `withTelemetry` - * already started it: the client drops every envelope from now on, including - * the command's own transaction. For flags such as `sentry wizard - * --disable-telemetry` that opt out of one run. - */ -export function disableTelemetryForRun(): void { - const client = Sentry.getClient(); - if (client) { - client.getOptions().enabled = false; - } -} - /** * Attributes a Snake score metric may carry. Everything else the SDK adds * (user.*, replay ids, ...) is dropped so a score cannot be linked to a user. diff --git a/packages/cli/src/lib/wizard/run.ts b/packages/cli/src/lib/wizard/run.ts index 8bd377980b..ebae262d08 100644 --- a/packages/cli/src/lib/wizard/run.ts +++ b/packages/cli/src/lib/wizard/run.ts @@ -9,12 +9,11 @@ import { ValidationError } from "../errors.js"; import { abortIfCancelled } from "./utils/clack/index.js"; import { clack } from "./utils/clack/prompts.js"; -import { enableDebugLogs } from "./utils/debug.js"; import type { WizardOptions } from "./utils/types.js"; import { CLI_VERSION } from "../constants.js"; /** - * The integrations `sentry wizard -i` accepts, in the order the picker lists + * The integrations `sentry wizard` accepts, in the order the picker lists * them. The ids are the ones `@sentry/wizard -i` took. */ export const WIZARD_INTEGRATIONS = [ @@ -33,12 +32,13 @@ export const WIZARD_INTEGRATIONS = [ { id: "sourcemaps", label: "Configure Source Maps Upload" }, ] as const; -/** An integration id `sentry wizard -i` accepts. */ +/** An integration id `sentry wizard` accepts. */ export type WizardIntegration = (typeof WIZARD_INTEGRATIONS)[number]["id"]; /** - * Every value `-i` accepts. The Cordova and Electron wizards of - * `@sentry/wizard` were retired; their setup guides are in the Sentry docs. + * Every integration id `sentry wizard` accepts. The Cordova and Electron + * wizards of `@sentry/wizard` were retired; their setup guides are in the + * Sentry docs. */ export const INTEGRATION_IDS: readonly WizardIntegration[] = WIZARD_INTEGRATIONS.map((integration) => integration.id); @@ -59,10 +59,8 @@ const WIZARD_RUNNERS: Partial> = { /** What `sentry wizard` passes to {@link runWizard}. */ export type RunWizardArgs = { - /** `-i`: the integration to set up; prompts for one when unset. */ - integration?: string | undefined; - /** `--debug`: print the wizard's debug output. */ - debug: boolean; + /** The integration to set up; prompts for one when unset. */ + integration?: WizardIntegration | undefined; /** The options every wizard flow takes. */ wizardOptions: WizardOptions; }; @@ -71,17 +69,11 @@ export type RunWizardArgs = { * Run the wizard of `args.integration`, after asking for one when it is * unset. * - * @throws {ValidationError} For an unknown integration, or one that has no - * flow in this version yet + * @throws {ValidationError} For an integration that has no flow in this + * version yet */ export async function runWizard(args: RunWizardArgs): Promise { - if (args.debug) { - enableDebugLogs(); - } - - const integration = args.integration - ? toWizardIntegration(args.integration) - : await askForIntegration(); + const integration = args.integration ?? (await askForIntegration()); const runner = WIZARD_RUNNERS[integration]; if (!runner) { @@ -93,25 +85,6 @@ export async function runWizard(args: RunWizardArgs): Promise { await runner(args.wizardOptions); } -/** - * `id` as one of {@link WIZARD_INTEGRATIONS}. `-i` already checks its - * value; `SENTRY_WIZARD_INTEGRATION` is checked here. - * - * @throws {ValidationError} When `id` names no integration - */ -function toWizardIntegration(id: string): WizardIntegration { - const match = WIZARD_INTEGRATIONS.find( - (integration) => integration.id === id, - ); - if (!match) { - throw new ValidationError( - `Unknown integration "${id}". Pick one of: ${INTEGRATION_IDS.join(", ")}.`, - "integration", - ); - } - return match.id; -} - /** Ask which integration to set up, out of the ones that have a flow. */ async function askForIntegration(): Promise { clack.intro(`Sentry Wizard ${CLI_VERSION}`); diff --git a/packages/cli/src/lib/wizard/telemetry.ts b/packages/cli/src/lib/wizard/telemetry.ts index 09a39e330d..e19324fcca 100644 --- a/packages/cli/src/lib/wizard/telemetry.ts +++ b/packages/cli/src/lib/wizard/telemetry.ts @@ -6,8 +6,7 @@ * wizard flow is a `wizard.flow` span under it and each step a `wizard.step` * span under that. Tags go on the same scope as the CLI's. Telemetry is off * when the CLI's is (`SENTRY_CLI_NO_TELEMETRY`, `DO_NOT_TRACK`, or - * `sentry cli defaults telemetry off`), and `--disable-telemetry` turns it - * off for the run. + * `sentry cli defaults telemetry off`). * * The old wizard sent its telemetry to a project of its own; the tag names * stay the same so its dashboards can move over. @@ -26,7 +25,7 @@ export const Sentry = { setTag, setUser }; /** * Run a wizard flow in a `wizard.flow` span, tagged with the integration and - * which of `--org`, `--project`, and `--saas` were passed. + * the kind of `/` target passed (`auto-detect` for none). */ export async function withTelemetry( options: { @@ -38,9 +37,7 @@ export async function withTelemetry( callback: () => F | Promise, ): Promise { setTag("integration", options.integration); - setTag("args.project", Boolean(options.wizardOptions.projectSlug)); - setTag("args.org", Boolean(options.wizardOptions.orgSlug)); - setTag("args.saas", Boolean(options.wizardOptions.saas)); + setTag("args.target", options.wizardOptions.target?.type ?? "auto-detect"); return await startSpan( { diff --git a/packages/cli/src/lib/wizard/utils/clack/index.ts b/packages/cli/src/lib/wizard/utils/clack/index.ts index a076b5049b..35282ec08e 100644 --- a/packages/cli/src/lib/wizard/utils/clack/index.ts +++ b/packages/cli/src/lib/wizard/utils/clack/index.ts @@ -169,8 +169,8 @@ export function printWelcome(options: { This wizard sends telemetry data and crash reports to Sentry. This helps us improve the Wizard. You can turn this off at any time by running ${chalk.cyanBright( - sentry`wizard --disable-telemetry`, - )}.`; + sentry`cli defaults telemetry off`, + )}, or by setting SENTRY_CLI_NO_TELEMETRY=1.`; } clack.note(welcomeText); @@ -200,7 +200,7 @@ export async function confirmContinueIfNoOrDirtyGitRepo({ ) { if (nonInteractive) { clack.log.error( - "Project is not inside a git repository in non-interactive mode. Run from a git repository or pass --ignore-git-changes to skip this safety check.", + "Project is not inside a git repository in non-interactive mode. Run from a git repository or pass --force to skip this safety check.", ); Sentry.setTag("continue-without-git", false); await abort(); @@ -237,7 +237,7 @@ The wizard will create and update files.`, if (nonInteractive) { clack.log.error( - "Project has uncommitted or untracked files in non-interactive mode. Commit or stash your changes, or pass --ignore-git-changes to skip this safety check.", + "Project has uncommitted or untracked files in non-interactive mode. Commit or stash your changes, or pass --force to skip this safety check.", ); Sentry.setTag("continue-with-dirty-repo", false); await abort(); diff --git a/packages/cli/src/lib/wizard/utils/debug.ts b/packages/cli/src/lib/wizard/utils/debug.ts index c8668c78ce..a8fb70f99a 100644 --- a/packages/cli/src/lib/wizard/utils/debug.ts +++ b/packages/cli/src/lib/wizard/utils/debug.ts @@ -1,32 +1,13 @@ /** - * Debug output of the setup wizards, shown with `sentry wizard --debug`. + * Debug output of the setup wizards, shown with the CLI's global `--verbose` + * or `--log-level debug`. */ -import chalk from "chalk"; -import { clack } from "./clack/prompts.js"; +import { logger } from "../../logger.js"; -let debugEnabled = false; +const log = logger.withTag("wizard"); -/** Render one debug argument: strings as-is, errors with their stack. */ -function prepareMessage(msg: unknown): string { - if (typeof msg === "string") { - return msg; - } - if (msg instanceof Error) { - return msg.stack ?? msg.message; - } - return JSON.stringify(msg, null, "\t"); -} - -/** Log `args` in the wizard's output when `--debug` is on. */ +/** Log `args` at the CLI logger's debug level. */ export function debug(...args: unknown[]): void { - if (!debugEnabled) { - return; - } - clack.log.info(chalk.dim(args.map((a) => prepareMessage(a)).join(" "))); -} - -/** Turn on {@link debug} output for the rest of the run. */ -export function enableDebugLogs(): void { - debugEnabled = true; + log.debug(...args); } diff --git a/packages/cli/src/lib/wizard/utils/project-data.ts b/packages/cli/src/lib/wizard/utils/project-data.ts index 0e4b856c32..c44faa30a0 100644 --- a/packages/cli/src/lib/wizard/utils/project-data.ts +++ b/packages/cli/src/lib/wizard/utils/project-data.ts @@ -9,8 +9,11 @@ * agent handoff from `SENTRY_HANDOFF`) when there is none. A new login asks * for `org:tokens` and `org:ci` too, so the auth token below needs no second * approval. - * - The org from `--org`, the handoff, or a prompt; then the project from - * `--project` or a prompt that can also create one for the wizard's + * - The Sentry instance the rest of the CLI uses: `SENTRY_URL`, or the + * stored login's. + * - The org and project of the `/` target, resolved like other + * commands' targets; else the org from the handoff or a prompt, then the + * project from a prompt that can also create one for the wizard's * platform, like the old browser page could. * - The project's DSN from its client keys. * - A new org auth token for the build plugins and `sentry` commands that @@ -33,21 +36,18 @@ import { MEMBER_PROJECT_CREATION_DISABLED_DETAIL, } from "../../api/projects.js"; import { assertAutoLoginHostTrusted } from "../../auto-auth.js"; -import { DEFAULT_SENTRY_URL } from "../../constants.js"; import { getAuthConfig } from "../../db/auth.js"; import { getEnv } from "../../env.js"; import { ApiError } from "../../errors.js"; import { runInteractiveLogin } from "../../interactive-login.js"; import { logger } from "../../logger.js"; import { OAUTH_SCOPES, resolveOAuthScopeString } from "../../oauth.js"; +import { resolveOrgOptionalTarget } from "../../resolve-target.js"; import { resolveOrCreateTeam } from "../../resolve-team.js"; import { ensureScopesForAction } from "../../scope-recovery.js"; import { isSentrySaasUrl } from "../../sentry-urls.js"; import { getApiBaseUrl } from "../../sentry-client.js"; -import { - isRequestOriginTrusted, - registerLoginTrustAnchor, -} from "../../token-host.js"; +import { isRequestOriginTrusted } from "../../token-host.js"; import { slugify } from "../../utils.js"; import { sentry } from "../../app-identity.js"; import type { @@ -104,7 +104,7 @@ export type WizardProjectData = * `options.preSelectedProject`, or one the user picks (or creates) after * logging in. * - * @param options - Wizard options (`--url`, `--saas`, `--org`, `--project`, …) + * @param options - Wizard options (the `/` target, Spotlight, …) * @param platform - Platform for a project the user creates */ export async function getOrAskForProjectData( @@ -122,29 +122,33 @@ export async function getOrAskForProjectData( if (options.preSelectedProject) { return { selfHosted: options.preSelectedProject.selfHosted, - sentryUrl: withTrailingSlash(options.url ?? DEFAULT_SENTRY_URL), + sentryUrl: withTrailingSlash(getApiBaseUrl()), authToken: options.preSelectedProject.authToken, selectedProject: options.preSelectedProject.project, spotlight: false, }; } - await traceStep("ask-self-hosted", () => - selectSentryUrl(options.url, options.saas), - ); const handoffOrg = await traceStep("login", ensureLoggedIn); - // The chosen instance, or the stored login's when none was chosen. + // `SENTRY_URL`, or the stored login's instance. const sentryUrl = withTrailingSlash(getApiBaseUrl()); const selfHosted = !isSentrySaasUrl(sentryUrl); Sentry.setTag("url", sentryUrl); Sentry.setTag("self-hosted", selfHosted); + const parsedTarget = options.target; + const target = + parsedTarget && parsedTarget.type !== "auto-detect" + ? await traceStep("resolve-target", () => + resolveOrgOptionalTarget(parsedTarget, process.cwd(), "wizard"), + ) + : undefined; const org = await traceStep("select-org", () => - selectOrganization(options.orgSlug ?? handoffOrg), + selectOrganization(target?.org ?? handoffOrg), ); const project = await traceStep("select-project", () => - selectProject(org, options.projectSlug, platform), + selectProject(org, target?.project, platform), ); Sentry.setTag("project", project.slug); Sentry.setUser({ id: org.slug }); @@ -168,90 +172,6 @@ export async function getOrAskForProjectData( }; } -/** - * Point this run at the Sentry instance the user chose: SaaS for `--saas`, - * the `--url` instance, or the answer to a SaaS/self-hosted prompt. Without - * any of them and with a stored login, the login's instance is used. - * - * An instance the user names here (flag or prompt) is trusted for login, the - * same as `sentry auth login --url`. - */ -async function selectSentryUrl( - urlFromArgs: string | undefined, - saas: boolean | undefined, -): Promise { - if (saas) { - useSentryUrl(DEFAULT_SENTRY_URL); - return; - } - if (!urlFromArgs && getAuthConfig()) { - return; - } - - if (!urlFromArgs) { - const choice = await abortIfCancelled( - clack.select({ - message: "Are you using Sentry SaaS or self-hosted Sentry?", - options: [ - { value: "saas", label: "Sentry SaaS (sentry.io)" }, - { - value: "self-hosted", - label: "Self-hosted/on-premise/single-tenant", - }, - ], - }), - ); - if (choice === "saas") { - useSentryUrl(DEFAULT_SENTRY_URL); - return; - } - } - - let pending = urlFromArgs; - for (;;) { - const url = - pending || - (await abortIfCancelled( - clack.text({ - message: `Please enter the URL of your ${ - urlFromArgs ? "" : "self-hosted " - }Sentry instance.`, - placeholder: "https://sentry.io/", - }), - )); - pending = undefined; - const origin = parseOrigin(url); - if (origin) { - useSentryUrl(origin); - return; - } - clack.log.error( - `Please enter a valid URL. (It should look something like "https://sentry.mydomain.com/", got ${url})`, - ); - } -} - -/** The origin of `url`, or `undefined` when it isn't an HTTP(S) URL. */ -function parseOrigin(url: string): string | undefined { - try { - const parsed = new URL(url); - return parsed.protocol === "https:" || parsed.protocol === "http:" - ? parsed.origin - : undefined; - } catch (error) { - log.debug(`Invalid Sentry URL ${url}`, error); - return; - } -} - -/** Send this run's API requests and login to `url`, trusted as user input. */ -function useSentryUrl(url: string): void { - const env = getEnv(); - env["SENTRY_HOST"] = url; - env["SENTRY_URL"] = url; - registerLoginTrustAnchor(url); -} - /** * Make sure the CLI has a login for the selected instance: claim the agent * handoff in `SENTRY_HANDOFF`, keep a stored login, or run the device flow. @@ -405,7 +325,7 @@ async function createProject( spinner.start("Creating your Sentry project"); try { const team = await resolveOrCreateTeam(orgSlug, { - usageHint: sentry`wizard --org `, + usageHint: sentry`wizard /`, autoCreateSlug: slugify(body.name), }); const { project } = await createProjectWithDsn(orgSlug, team.slug, body); diff --git a/packages/cli/src/lib/wizard/utils/types.ts b/packages/cli/src/lib/wizard/utils/types.ts index d349678578..1f53c0e364 100644 --- a/packages/cli/src/lib/wizard/utils/types.ts +++ b/packages/cli/src/lib/wizard/utils/types.ts @@ -3,6 +3,8 @@ * flow, the Sentry project a flow sets up, and feature prompts. */ +import type { ParsedOrgProject } from "../../arg-parsing.js"; + export interface SentryProjectData { id: string; slug: string; @@ -27,30 +29,11 @@ export type WizardOptions = { telemetryEnabled: boolean; /** - * The url of the Sentry instance to use. - * This can be passed via the `-u` or `--url` arg. - */ - url?: string | undefined; - - /** - * The org to pre-select in the wizard. - * This can be passed via the `--org` arg. - * Example: `--org my-org` - */ - orgSlug?: string | undefined; - - /** - * Project slug to pre-select in the wizard. - * This can be passed via the `--project` arg. - * Example: `--project my-project` - */ - projectSlug?: string | undefined; - - /** - * If this option is set, the wizard will skip the self-hosted or SaaS - * selection step and directly assume that the wizard is used for Sentry SaaS. + * The org and project from `sentry wizard /`, resolved after + * the login: an org and project skip both pickers, an org (`/`) skips + * the org picker. Unset or auto-detect: the user picks both. */ - saas?: boolean | undefined; + target?: ParsedOrgProject | undefined; /** * If this is set, the wizard will skip the login and project selection step. @@ -69,6 +52,7 @@ export type WizardOptions = { /** * If this is set, the wizard will ignore any git changes in the project and not prompt for confirmation. + * `sentry wizard --force` sets it, together with {@link forceInstall}. */ ignoreGitChanges?: boolean | undefined; @@ -78,7 +62,7 @@ export type WizardOptions = { * - Skips login and project selection * - Uses empty DSN * - Skips auth token file creation - * This can be passed via the `--spotlight` arg. + * `sentry wizard` turns it on when `SENTRY_SPOTLIGHT` is set. */ spotlight?: boolean | undefined; }; diff --git a/packages/cli/test/commands/wizard.test.ts b/packages/cli/test/commands/wizard.test.ts index 46be02ce14..3705740bb9 100644 --- a/packages/cli/test/commands/wizard.test.ts +++ b/packages/cli/test/commands/wizard.test.ts @@ -1,40 +1,38 @@ /** - * Tests for `sentry wizard`: integration selection, the flags it passes to a - * wizard flow, and how a stopped wizard sets the exit code. + * Tests for `sentry wizard`: its command line (`[/] + * []` and `--force`, nothing else), what it passes to a wizard + * flow, and how a stopped wizard sets the exit code. */ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; -const { runNextjsWizard } = vi.hoisted(() => ({ +const { runNextjsWizard, isTelemetryEnabled } = vi.hoisted(() => ({ runNextjsWizard: vi.fn<(options: unknown) => Promise>(), + isTelemetryEnabled: vi.fn<() => boolean>(), })); vi.mock("../../src/lib/wizard/nextjs/nextjs-wizard.js", () => ({ runNextjsWizard, })); +vi.mock("../../src/lib/telemetry.js", async (importOriginal) => ({ + ...(await importOriginal()), + isTelemetryEnabled, +})); -import { wizardCommand } from "../../src/commands/wizard.js"; +import { + parseWizardArguments, + wizardCommand, +} from "../../src/commands/wizard.js"; import type { SentryContext } from "../../src/context.js"; +import { buildCommand } from "../../src/lib/command.js"; import { ValidationError, WizardExitError } from "../../src/lib/errors.js"; import type { Writer } from "../../src/types/index.js"; import { loadCommand, useTestConfigDir } from "../helpers.js"; useTestConfigDir("wizard-test-"); -const DEFAULT_FLAGS = { - saas: false, - debug: false, - spotlight: false, - "disable-telemetry": false, - "force-install": false, - "ignore-git-changes": false, - signup: false, - "skip-connect": false, - quiet: false, - uninstall: false, -}; - async function runWizardCommand( flags: Record = {}, + ...args: string[] ): Promise { const context = { process, @@ -47,12 +45,21 @@ async function runWizardCommand( configDir: "/tmp", } as unknown as SentryContext; const func = await loadCommand(wizardCommand); - await func.call(context, { ...DEFAULT_FLAGS, ...flags }); + await func.call(context, { force: false, ...flags }, ...args); +} + +/** The options the Next.js flow was called with. */ +function nextjsOptions(): Record { + expect(runNextjsWizard).toHaveBeenCalledTimes(1); + return runNextjsWizard.mock.calls[0]?.[0] as Record; } beforeEach(() => { runNextjsWizard.mockReset(); runNextjsWizard.mockResolvedValue(undefined); + isTelemetryEnabled.mockReset(); + isTelemetryEnabled.mockReturnValue(true); + vi.stubEnv("SENTRY_SPOTLIGHT", ""); process.exitCode = undefined; }); @@ -61,72 +68,182 @@ afterEach(() => { process.exitCode = undefined; }); -describe("sentry wizard", () => { - test("runs the -i integration with the @sentry/wizard flags", async () => { - await runWizardCommand({ +describe("sentry wizard flags", () => { + /** Flags and aliases `buildCommand` adds to every command. */ + const injected = buildCommand({ + auth: false, + docs: { brief: "probe" }, + parameters: {}, + // oxlint-disable-next-line require-yield -- A probe; it never runs. + async *func() { + await Promise.resolve(); + }, + }).parameters; + + test("--force (-f) is the wizard's only flag, and it is not hidden", () => { + const { flags = {}, aliases = {} } = wizardCommand.parameters as { + flags?: Record; + aliases?: Record; + }; + const ownFlags = Object.keys(flags).filter( + (name) => !(name in (injected.flags ?? {})), + ); + const ownAliases = Object.entries(aliases).filter( + ([alias]) => !(alias in (injected.aliases ?? {})), + ); + + expect(ownFlags).toEqual(["force"]); + expect(flags["force"]?.hidden).toBeUndefined(); + expect(Object.fromEntries(ownAliases)).toEqual({ f: "force" }); + }); +}); + +describe("parseWizardArguments", () => { + test("no arguments: the user picks the integration and the project", () => { + expect(parseWizardArguments([])).toEqual({ + target: { type: "auto-detect" }, + }); + }); + + test("an integration alone", () => { + expect(parseWizardArguments(["nextjs"])).toEqual({ + target: { type: "auto-detect" }, integration: "nextjs", - org: "acme", - project: "web", - url: "https://sentry.example.com", - spotlight: true, - "force-install": true, - "ignore-git-changes": true, - "disable-telemetry": true, }); + }); - expect(runNextjsWizard).toHaveBeenCalledWith({ - telemetryEnabled: false, - url: "https://sentry.example.com", - orgSlug: "acme", - projectSlug: "web", - saas: false, - forceInstall: true, - ignoreGitChanges: true, - spotlight: true, + test("a target alone", () => { + expect(parseWizardArguments(["my-org/my-project"])).toEqual({ + target: { type: "explicit", org: "my-org", project: "my-project" }, + }); + expect(parseWizardArguments(["my-org/"])).toEqual({ + target: { type: "org-all", org: "my-org" }, + }); + expect(parseWizardArguments(["/my-project"])).toEqual({ + target: { type: "project-search", projectSlug: "my-project" }, }); }); - test.each([ - [{ signup: true }, "--signup is no longer supported."], - [{ "promo-code": "PROMO" }, "--promo-code is no longer supported."], - [{ "coming-from": "vercel" }, "--coming-from is no longer supported."], - [ - { signup: true, "promo-code": "PROMO" }, - "--signup, --promo-code are no longer supported.", - ], - ])("rejects the removed sign-up flags %o", async (flags, message) => { - const error = await runWizardCommand({ integration: "nextjs", ...flags }) - .then(() => undefined) - .catch((caught: unknown) => caught); - - expect(error).toBeInstanceOf(ValidationError); - expect((error as ValidationError).message).toContain(message); - expect((error as ValidationError).message).toContain( - "https://sentry.io/signup/", + test("a target, then an integration", () => { + expect(parseWizardArguments(["my-org/my-project", "nextjs"])).toEqual({ + target: { type: "explicit", org: "my-org", project: "my-project" }, + integration: "nextjs", + }); + }); + + test("a bare project or org slug before an integration is the target", () => { + expect(parseWizardArguments(["my-project", "nextjs"])).toEqual({ + target: { type: "project-search", projectSlug: "my-project" }, + integration: "nextjs", + }); + }); + + test("a bare slug alone is read as an integration, so it must be one", () => { + expect(() => parseWizardArguments(["my-project"])).toThrow( + new ValidationError( + "Unknown integration 'my-project'. Pick one of: reactNative, flutter, ios, appleSnapshots, angular, android, nextjs, nuxt, remix, reactRouter, sveltekit, cloudflare, sourcemaps.\n" + + " To name an org or project instead, write it as /, / or /.\n" + + " Usage: sentry wizard [/] []", + "integration", + ), + ); + }); + + test("a project named like an integration is written with its org", () => { + expect(parseWizardArguments(["my-org/nextjs"])).toEqual({ + target: { type: "explicit", org: "my-org", project: "nextjs" }, + }); + expect(parseWizardArguments(["my-org/nextjs", "nextjs"])).toEqual({ + target: { type: "explicit", org: "my-org", project: "nextjs" }, + integration: "nextjs", + }); + expect(parseWizardArguments(["/nextjs"])).toEqual({ + target: { type: "project-search", projectSlug: "nextjs" }, + }); + }); + + test("an unknown integration after a target", () => { + expect(() => parseWizardArguments(["my-org/my-project", "cobol"])).toThrow( + "Unknown integration 'cobol'.", ); - expect(runNextjsWizard).not.toHaveBeenCalled(); }); - test("reads the integration and URL from SENTRY_WIZARD_* variables", async () => { - vi.stubEnv("SENTRY_WIZARD_INTEGRATION", "nextjs"); - vi.stubEnv("SENTRY_WIZARD_URL", "https://self-hosted.example.com"); + test("integration ids are matched exactly", () => { + expect(() => parseWizardArguments(["NextJS"])).toThrow( + "Unknown integration 'NextJS'.", + ); + expect(() => parseWizardArguments(["nextjs,remix"])).toThrow( + "Unknown integration 'nextjs,remix'.", + ); + }); - await runWizardCommand(); + test("exactly one integration", () => { + expect(() => parseWizardArguments(["nextjs", "remix"])).toThrow( + "'nextjs' is an integration, and the wizard sets up one at a time.\n" + + " To name a project or org called 'nextjs', write it as /nextjs, nextjs/ or /nextjs.", + ); + }); - expect(runNextjsWizard).toHaveBeenCalledWith( - expect.objectContaining({ url: "https://self-hosted.example.com" }), + test("too many arguments", () => { + expect(() => + parseWizardArguments(["my-org/my-project", "nextjs", "remix"]), + ).toThrow( + "Too many arguments: remix. Expected: sentry wizard [/] []", ); }); +}); + +describe("sentry wizard", () => { + test("runs the integration for the target", async () => { + await runWizardCommand({}, "my-org/my-project", "nextjs"); + + expect(nextjsOptions()).toEqual({ + telemetryEnabled: true, + target: { type: "explicit", org: "my-org", project: "my-project" }, + forceInstall: false, + ignoreGitChanges: false, + spotlight: false, + }); + }); - test("rejects an unknown SENTRY_WIZARD_INTEGRATION", async () => { - vi.stubEnv("SENTRY_WIZARD_INTEGRATION", "cobol"); + test("--force both force-installs and skips the uncommitted changes prompt", async () => { + await runWizardCommand({ force: true }, "nextjs"); - await expect(runWizardCommand()).rejects.toThrow(ValidationError); - expect(runNextjsWizard).not.toHaveBeenCalled(); + expect(nextjsOptions()).toMatchObject({ + forceInstall: true, + ignoreGitChanges: true, + }); }); + test.each([ + ["1", true], + ["true", true], + ["http://localhost:8969/stream", true], + ["0", false], + ["false", false], + ["off", false], + ["", false], + ])("SENTRY_SPOTLIGHT=%j sets Spotlight mode to %s", async (value, on) => { + vi.stubEnv("SENTRY_SPOTLIGHT", value); + + await runWizardCommand({}, "nextjs"); + + expect(nextjsOptions()).toMatchObject({ spotlight: on }); + }); + + test.each([true, false])( + "telemetry follows isTelemetryEnabled() (%s)", + async (enabled) => { + isTelemetryEnabled.mockReturnValue(enabled); + + await runWizardCommand({}, "nextjs"); + + expect(nextjsOptions()).toMatchObject({ telemetryEnabled: enabled }); + }, + ); + test("reports an integration this version can't set up yet", async () => { - await expect(runWizardCommand({ integration: "remix" })).rejects.toThrow( + await expect(runWizardCommand({}, "remix")).rejects.toThrow( "The remix wizard is not available in this version yet.", ); }); @@ -134,7 +251,7 @@ describe("sentry wizard", () => { test("exits with the wizard's code when it stops", async () => { runNextjsWizard.mockRejectedValue(new WizardExitError(0)); - await runWizardCommand({ integration: "nextjs" }); + await runWizardCommand({}, "nextjs"); expect(process.exitCode).toBe(0); }); @@ -142,7 +259,7 @@ describe("sentry wizard", () => { test("exits with code 1 when the wizard can't continue", async () => { runNextjsWizard.mockRejectedValue(new WizardExitError(1)); - await runWizardCommand({ integration: "nextjs" }); + await runWizardCommand({}, "nextjs"); expect(process.exitCode).toBe(1); }); diff --git a/packages/cli/test/lib/wizard/utils/project-data.test.ts b/packages/cli/test/lib/wizard/utils/project-data.test.ts index 152d7adb29..b2baab05be 100644 --- a/packages/cli/test/lib/wizard/utils/project-data.test.ts +++ b/packages/cli/test/lib/wizard/utils/project-data.test.ts @@ -21,6 +21,7 @@ const mocks = vi.hoisted(() => ({ text: vi.fn(), isRequestOriginTrusted: vi.fn(), getApiBaseUrl: vi.fn(), + resolveOrgOptionalTarget: vi.fn(), warn: vi.fn(), })); @@ -73,6 +74,11 @@ vi.mock("../../../../src/lib/api/organizations.js", () => ({ vi.mock("../../../../src/lib/api/org-auth-tokens.js", () => ({ createOrgAuthToken: mocks.createOrgAuthToken, })); +// Target resolution has its own tests; these check what the wizard does +// with the resolved org and project. +vi.mock("../../../../src/lib/resolve-target.js", () => ({ + resolveOrgOptionalTarget: mocks.resolveOrgOptionalTarget, +})); vi.mock("../../../../src/lib/resolve-team.js", () => ({ resolveOrCreateTeam: mocks.resolveOrCreateTeam, })); @@ -87,6 +93,7 @@ vi.mock("../../../../src/lib/api/projects.js", async (importOriginal) => ({ createProjectWithAutoTeam: mocks.createProjectWithAutoTeam, })); +import type { ParsedOrgProject } from "../../../../src/lib/arg-parsing.js"; import { ApiError, WizardExitError } from "../../../../src/lib/errors.js"; import { DUMMY_AUTH_TOKEN, @@ -96,6 +103,11 @@ import type { SentryProjectData } from "../../../../src/lib/wizard/utils/types.j const ORG = { id: "1", slug: "acme", name: "Acme" }; const PROJECT = { id: "42", slug: "web", name: "web", platform: "javascript" }; +const ACME_WEB: ParsedOrgProject = { + type: "explicit", + org: "acme", + project: "web", +}; const KEY = { id: "k1", name: "Default", @@ -117,6 +129,20 @@ beforeEach(async () => { mocks.getProjectKeys.mockResolvedValue([KEY]); mocks.ensureScopesForAction.mockResolvedValue("ready"); mocks.createOrgAuthToken.mockResolvedValue({ token: "sntrys_new" }); + mocks.resolveOrgOptionalTarget.mockImplementation( + (parsed: ParsedOrgProject) => { + switch (parsed.type) { + case "explicit": + return Promise.resolve({ org: parsed.org, project: parsed.project }); + case "org-all": + return Promise.resolve({ org: parsed.org }); + case "project-search": + return Promise.resolve({ org: "acme", project: parsed.projectSlug }); + default: + return Promise.reject(new Error("auto-detect is not resolved")); + } + }, + ); }); describe("getOrAskForProjectData", () => { @@ -153,16 +179,19 @@ describe("getOrAskForProjectData", () => { expect(mocks.listOrganizations).not.toHaveBeenCalled(); }); - it("uses the stored login and the --org and --project slugs", async () => { + it("uses the stored login and the / target", async () => { const result = await getOrAskForProjectData({ telemetryEnabled: false, - saas: true, - orgSlug: "acme", - projectSlug: "web", + target: ACME_WEB, }); expect(mocks.runInteractiveLogin).not.toHaveBeenCalled(); expect(mocks.select).not.toHaveBeenCalled(); + expect(mocks.resolveOrgOptionalTarget).toHaveBeenCalledWith( + ACME_WEB, + process.cwd(), + "wizard", + ); expect(mocks.getProject).toHaveBeenCalledWith("acme", "web"); expect(result).toEqual({ spotlight: false, @@ -178,16 +207,14 @@ describe("getOrAskForProjectData", () => { }); }); - it("asks for the project when the --project slug is not found", async () => { + it("asks for the project when the target's project is not found", async () => { mocks.getProject.mockRejectedValue(new ApiError("Not found", 404)); mocks.listProjects.mockResolvedValue([PROJECT]); mocks.select.mockResolvedValueOnce(PROJECT); const result = await getOrAskForProjectData({ telemetryEnabled: false, - saas: true, - orgSlug: "acme", - projectSlug: "missing", + target: { type: "explicit", org: "acme", project: "missing" }, }); expect(mocks.listProjects).toHaveBeenCalledWith("acme"); @@ -207,7 +234,7 @@ describe("getOrAskForProjectData", () => { }); const result = await getOrAskForProjectData( - { telemetryEnabled: false, saas: true, orgSlug: "acme" }, + { telemetryEnabled: false, target: { type: "org-all", org: "acme" } }, "javascript-nextjs", ); @@ -223,9 +250,7 @@ describe("getOrAskForProjectData", () => { const result = await getOrAskForProjectData({ telemetryEnabled: false, - saas: true, - orgSlug: "acme", - projectSlug: "web", + target: ACME_WEB, }); expect(mocks.createOrgAuthToken).not.toHaveBeenCalled(); @@ -238,9 +263,7 @@ describe("getOrAskForProjectData", () => { await getOrAskForProjectData({ telemetryEnabled: false, - saas: true, - orgSlug: "acme", - projectSlug: "web", + target: ACME_WEB, }); expect(mocks.runInteractiveLogin).toHaveBeenCalledWith({ @@ -253,7 +276,7 @@ describe("getOrAskForProjectData", () => { mocks.runInteractiveLogin.mockResolvedValue(null); await expect( - getOrAskForProjectData({ telemetryEnabled: false, saas: true }), + getOrAskForProjectData({ telemetryEnabled: false }), ).rejects.toThrow(WizardExitError); }); @@ -263,9 +286,7 @@ describe("getOrAskForProjectData", () => { await getOrAskForProjectData({ telemetryEnabled: false, - url: "https://sentry.example.com", - orgSlug: "acme", - projectSlug: "web", + target: ACME_WEB, }); expect(mocks.runInteractiveLogin).toHaveBeenCalled(); @@ -276,8 +297,7 @@ describe("getOrAskForProjectData", () => { const result = await getOrAskForProjectData({ telemetryEnabled: false, - orgSlug: "acme", - projectSlug: "web", + target: ACME_WEB, }); expect(mocks.runInteractiveLogin).not.toHaveBeenCalled(); @@ -293,8 +313,7 @@ describe("getOrAskForProjectData", () => { await getOrAskForProjectData({ telemetryEnabled: false, - orgSlug: "acme", - projectSlug: "web", + target: ACME_WEB, }); expect(mocks.warn).toHaveBeenCalledWith( @@ -307,14 +326,68 @@ describe("getOrAskForProjectData", () => { it("claims an agent handoff and uses its org", async () => { vi.stubEnv("SENTRY_HANDOFF", "handoff-code"); mocks.completeAgentHandoff.mockResolvedValue({ organizationSlug: "acme" }); + mocks.listOrganizations.mockResolvedValue([ + ORG, + { id: "2", slug: "other", name: "Other" }, + ]); + mocks.listProjects.mockResolvedValue([PROJECT]); + mocks.select.mockResolvedValueOnce(PROJECT); - await getOrAskForProjectData({ + await getOrAskForProjectData({ telemetryEnabled: false }); + + expect(mocks.completeAgentHandoff).toHaveBeenCalledWith("handoff-code"); + expect(mocks.select).toHaveBeenCalledTimes(1); + expect(mocks.listProjects).toHaveBeenCalledWith("acme"); + }); + + it("asks for the org and project when no target is given", async () => { + const other = { id: "2", slug: "other", name: "Other" }; + mocks.listOrganizations.mockResolvedValue([ORG, other]); + mocks.listProjects.mockResolvedValue([PROJECT]); + mocks.select.mockResolvedValueOnce(ORG).mockResolvedValueOnce(PROJECT); + + const result = await getOrAskForProjectData({ telemetryEnabled: false, - saas: true, - projectSlug: "web", + target: { type: "auto-detect" }, }); - expect(mocks.completeAgentHandoff).toHaveBeenCalledWith("handoff-code"); + // Nothing is detected from the project's files or the CLI defaults. + expect(mocks.resolveOrgOptionalTarget).not.toHaveBeenCalled(); + expect(mocks.select).toHaveBeenCalledTimes(2); + expect(result).toMatchObject({ selectedProject: { slug: "web" } }); + }); + + it("resolves a bare project slug like other commands' targets", async () => { + const target: ParsedOrgProject = { + type: "project-search", + projectSlug: "web", + }; + + await getOrAskForProjectData({ telemetryEnabled: false, target }); + + expect(mocks.resolveOrgOptionalTarget).toHaveBeenCalledWith( + target, + process.cwd(), + "wizard", + ); + expect(mocks.select).not.toHaveBeenCalled(); expect(mocks.getProject).toHaveBeenCalledWith("acme", "web"); }); + + it("uses the CLI's instance for a preselected project", async () => { + mocks.getApiBaseUrl.mockReturnValue("https://sentry.example.com"); + const project: SentryProjectData = { + id: "7", + slug: "app", + organization: { id: "1", name: "Acme", slug: "acme" }, + keys: [{ dsn: { public: "https://k@sentry.example.com/7" } }], + }; + + const result = await getOrAskForProjectData({ + telemetryEnabled: false, + preSelectedProject: { project, authToken: "tok", selfHosted: true }, + }); + + expect(result).toMatchObject({ sentryUrl: "https://sentry.example.com/" }); + }); }); From 4c93aa845158ef8dff95134aa339c58c31b1af02 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:23:37 +0000 Subject: [PATCH 11/20] fix(cli): use the credential host for the project issues URL Re-export buildProjectIssuesUrl from lib/sentry-web-urls.ts through withSentryBaseUrl(getApiBaseUrl()), like the other user-facing link builders, so self-hosted and regional logins get links on the host they are authenticated against. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- packages/cli/src/lib/sentry-web-urls.ts | 8 ++++++++ packages/cli/test/lib/sentry-urls.credential.test.ts | 4 ++++ 2 files changed, 12 insertions(+) diff --git a/packages/cli/src/lib/sentry-web-urls.ts b/packages/cli/src/lib/sentry-web-urls.ts index 2207e6a9d1..f4805167f0 100644 --- a/packages/cli/src/lib/sentry-web-urls.ts +++ b/packages/cli/src/lib/sentry-web-urls.ts @@ -11,6 +11,7 @@ import { buildMetricAlertsUrl as buildMetricAlertsUrlPure, buildOrgSettingsUrl as buildOrgSettingsUrlPure, buildOrgUrl as buildOrgUrlPure, + buildProjectIssuesUrl as buildProjectIssuesUrlPure, buildProjectUrl as buildProjectUrlPure, buildReleaseUrl as buildReleaseUrlPure, buildReplayUrl as buildReplayUrlPure, @@ -56,6 +57,13 @@ export function buildEventSearchUrl(orgSlug: string, eventId: string): string { return render(() => buildEventSearchUrlPure(orgSlug, eventId)); } +export function buildProjectIssuesUrl( + orgSlug: string, + projectId: string, +): string { + return render(() => buildProjectIssuesUrlPure(orgSlug, projectId)); +} + export function buildOrgSettingsUrl(orgSlug: string, hash?: string): string { return render(() => buildOrgSettingsUrlPure(orgSlug, hash)); } diff --git a/packages/cli/test/lib/sentry-urls.credential.test.ts b/packages/cli/test/lib/sentry-urls.credential.test.ts index 38e9d87bed..e5000fe361 100644 --- a/packages/cli/test/lib/sentry-urls.credential.test.ts +++ b/packages/cli/test/lib/sentry-urls.credential.test.ts @@ -3,6 +3,7 @@ import { setAuthToken } from "../../src/lib/db/auth.js"; import { resetEnvTokenHostForTesting } from "../../src/lib/env-token-host.js"; import { buildOrgUrl, + buildProjectIssuesUrl, buildProjectUrl, getSentryBaseUrl, isSaaS, @@ -40,6 +41,9 @@ describe("web URLs for active credential hosts", () => { expect(buildProjectUrl("acme", "site")).toBe( "https://sentry.example.com/settings/acme/projects/site/", ); + expect(buildProjectIssuesUrl("acme", "42")).toBe( + "https://sentry.example.com/organizations/acme/issues/?project=42", + ); }); test("stored OAuth host wins over an inactive environment token", () => { From 2f2f91a2303211c1c149d250b86a1f076cfbdeba Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:40:46 +0000 Subject: [PATCH 12/20] =?UTF-8?q?fix(mcp):=20regenerate=20the=20chart=20ap?= =?UTF-8?q?p=20after=20the=20for=E2=80=A6of=20conversion?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- packages/mcp-core/src/server.ui-resources.test.ts | 2 +- packages/mcp-core/src/ui-resources.ts | 4 ++-- packages/mcp-core/src/ui/chart-app.generated.ts | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/mcp-core/src/server.ui-resources.test.ts b/packages/mcp-core/src/server.ui-resources.test.ts index bd31394ab0..b17369868f 100644 --- a/packages/mcp-core/src/server.ui-resources.test.ts +++ b/packages/mcp-core/src/server.ui-resources.test.ts @@ -15,7 +15,7 @@ vi.mock("@sentry/core/server", () => ({ wrapMcpServerWithSentry: vi.fn((server) => server), })); -const CHART_URI = "ui://sentry/chart/v5.html"; +const CHART_URI = "ui://sentry/chart/v6.html"; const MCP_APP_MIME_TYPE = "text/html;profile=mcp-app"; async function connect(skills: Skill[]) { diff --git a/packages/mcp-core/src/ui-resources.ts b/packages/mcp-core/src/ui-resources.ts index 4c19d2787a..590c9101ec 100644 --- a/packages/mcp-core/src/ui-resources.ts +++ b/packages/mcp-core/src/ui-resources.ts @@ -57,13 +57,13 @@ export interface UiResource { * chart-app/ by generate-chart-app. */ export const CHART_UI_RESOURCE: UiResource = { - uri: "ui://sentry/chart/v5.html", + uri: "ui://sentry/chart/v6.html", name: "sentry_chart", title: "Sentry Chart", description: "Interactive time series chart for render_sentry_chart and render_issue_chart results, with a range picker, fullscreen, and a link to Sentry.", htmlSha256: - "7957519bcbf3a3855250904467784362573af55eb36cc11bac53d0625c2d2d22", + "079fa3cb185c5fdf7ad4e5983657af34093d2a477963d10be7c6da909aeaeaf5", // About 1.5x the current view, so a new dependency cannot slip in. budgetBytes: 24 * 1024, loadHtml: async () => diff --git a/packages/mcp-core/src/ui/chart-app.generated.ts b/packages/mcp-core/src/ui/chart-app.generated.ts index ed6b4b9e2b..f1a79316dd 100644 --- a/packages/mcp-core/src/ui/chart-app.generated.ts +++ b/packages/mcp-core/src/ui/chart-app.generated.ts @@ -1,2 +1,2 @@ // Generated by scripts/generate-chart-app.ts from chart-app/. Do not edit. -export const CHART_APP_HTML = "Sentry chart"; +export const CHART_APP_HTML = "Sentry chart"; From e99e91c0ce04f7b44ec76123fa35ce3913d20b47 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:22:13 +0000 Subject: [PATCH 13/20] fix(cli): don't add a second source map upload when the build script already runs it When the production build script already ends with `sentry:sourcemaps`, `addSentryCommandToBuildCommand` left `addedToBuildCommand` false, so `setupNpmScriptInCI` still asked for a separate CI step and the upload would run twice. That branch now sets the flag too. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .../lib/wizard/sourcemaps/tools/sentry-cli.ts | 1 + .../sourcemaps/tools/sentry-cli.test.ts | 25 +++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts index b4669fda9e..33efad8a5b 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts @@ -433,6 +433,7 @@ Current command: ${chalk.dim(oldCommand)} Would have injected: ${chalk.dim(newCommand)}`, ); + addedToBuildCommand = true; return; } 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 index 22bea7aa46..882ce38432 100644 --- a/packages/cli/test/lib/wizard/sourcemaps/tools/sentry-cli.test.ts +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/sentry-cli.test.ts @@ -12,6 +12,10 @@ import { getPackageDotJson } from "../../../../../src/lib/wizard/utils/clack/ind import { vi, it, describe, expect, afterEach } from "vitest"; +const { selectMock } = vi.hoisted(() => ({ + selectMock: vi.fn().mockResolvedValue(true), +})); + const writeFileSpy = vi .spyOn(promises, "writeFile") .mockImplementation(() => Promise.resolve()); @@ -23,6 +27,7 @@ vi.mock("@clack/prompts", () => { success: vi.fn(), }, confirm: vi.fn().mockResolvedValue(true), + select: selectMock, isCancel: vi.fn().mockReturnValue(false), }; }); @@ -76,6 +81,26 @@ describe("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", () => { From 5b0ee008696303a038e16abf5b38cc2861cda0c3 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:52:37 +0000 Subject: [PATCH 14/20] fix(cli): use the shared sentry-cli.ts from the Nuxt and Angular wizards Takes `sourcemaps/tools/sentry-cli.ts` and its test from getsentry/toolkit#2525 (f5ca46ef) as they are, so both PRs carry the same copy. Its `.sentryclirc` writer is `addUploadTargetToSentryCliRc`, so the Wrangler tool and the `.sentryclirc` defaults test call it by that name. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .../lib/wizard/sourcemaps/tools/sentry-cli.ts | 45 +++++++++--- .../lib/wizard/sourcemaps/tools/wrangler.ts | 4 +- .../sourcemaps/tools/sentry-cli.test.ts | 70 ++++++++++++++++++- .../tools/sentryclirc-defaults.test.ts | 12 ++-- 4 files changed, 110 insertions(+), 21 deletions(-) diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts index 33efad8a5b..37854eea97 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts @@ -5,9 +5,9 @@ * Installs the `sentry` CLI package, adds a `sentry:sourcemaps` npm script * that runs `sentry sourcemap inject` and `sentry sourcemap upload` on the * build output, optionally appends it to the production build script, and - * writes the org, project, and auth token to `.sentryclirc`. v4 reads that - * file: `[defaults]` feeds org/project resolution and `[auth] token` becomes - * `SENTRY_AUTH_TOKEN`. + * 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 @@ -89,7 +89,9 @@ export async function configureSentryCLI( ); if (path.isAbsolute(rawArtifactPath)) { - relativeArtifactPath = path.relative(process.cwd(), rawArtifactPath); + // The project root itself is "" relative to cwd; the CLI needs ".". + relativeArtifactPath = + path.relative(process.cwd(), rawArtifactPath) || "."; } else { relativeArtifactPath = rawArtifactPath; } @@ -131,7 +133,7 @@ export async function configureSentryCLI( ); } - await addOrgAndProjectToSentryCliRc(options); + await addUploadTargetToSentryCliRc(options); await addSentryCliConfig({ authToken: options.authToken }); if (options.selfHosted) { @@ -185,16 +187,32 @@ export async function setupNpmScriptInCI(): Promise { /** * The `sentry:sourcemaps` script: inject debug IDs into the build output, * then upload it. `sentry sourcemap upload` reads the org and project from - * `.sentryclirc` locally and from `SENTRY_ORG` / `SENTRY_PROJECT` in CI, and - * the self-hosted URL from `SENTRY_URL`. + * `.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 inject ${relativePosixArtifactPath} && sentry sourcemap upload ${relativePosixArtifactPath}`; + return `sentry sourcemap inject ${artifactPath} && 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]`. */ @@ -265,8 +283,12 @@ export function setSentryCliRcDefaults( * 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 addOrgAndProjectToSentryCliRc( +export async function addUploadTargetToSentryCliRc( options: SourceMapUploadToolConfigurationOptions, ): Promise { const configPath = path.join(process.cwd(), SENTRY_CLI_RC_FILE); @@ -284,8 +306,8 @@ export async function addOrgAndProjectToSentryCliRc( }), ); } catch (error) { - // Not fatal, like the auth token write: the warning says how to set - // them instead. + // 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( @@ -433,6 +455,7 @@ 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; } diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/wrangler.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/wrangler.ts index 2e94763490..d35098f479 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/tools/wrangler.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/wrangler.ts @@ -25,7 +25,7 @@ import { import { clack } from "../../utils/clack/prompts.js"; import { hasPackageInstalled } from "../../utils/package-json.js"; import { NPM } from "../../utils/package-manager.js"; -import { addOrgAndProjectToSentryCliRc } from "./sentry-cli.js"; +import { addUploadTargetToSentryCliRc } from "./sentry-cli.js"; import type { SourceMapUploadToolConfigurationOptions } from "./types.js"; const SENTRY_NPM_SCRIPT_NAME = "sentry:sourcemaps"; @@ -97,7 +97,7 @@ Otherwise, let's proceed with the Wrangler setup.`, await modifyDeployCommand(deployCommand, outDir); - await addOrgAndProjectToSentryCliRc(options); + await addUploadTargetToSentryCliRc(options); await addSentryCliConfig({ authToken: options.authToken }); if (options.selfHosted) { 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 index 882ce38432..190e5818b8 100644 --- a/packages/cli/test/lib/wizard/sourcemaps/tools/sentry-cli.test.ts +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/sentry-cli.test.ts @@ -1,7 +1,10 @@ -import { promises } from "node:fs"; +import { mkdtempSync, promises, realpathSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; import { addSentryCommandToBuildCommand, + configureSentryCLI, getSentryCliNpmScript, setSentryCliRcDefaults, } from "../../../../../src/lib/wizard/sourcemaps/tools/sentry-cli.js"; @@ -12,8 +15,9 @@ import { getPackageDotJson } from "../../../../../src/lib/wizard/utils/clack/ind import { vi, it, describe, expect, afterEach } from "vitest"; -const { selectMock } = vi.hoisted(() => ({ +const { selectMock, textMock } = vi.hoisted(() => ({ selectMock: vi.fn().mockResolvedValue(true), + textMock: vi.fn(), })); const writeFileSpy = vi @@ -28,6 +32,7 @@ vi.mock("@clack/prompts", () => { }, confirm: vi.fn().mockResolvedValue(true), select: selectMock, + text: textMock, isCancel: vi.fn().mockReturnValue(false), }; }); @@ -35,6 +40,8 @@ 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", @@ -109,6 +116,65 @@ describe("getSentryCliNpmScript", () => { "sentry sourcemap inject ./dist && sentry sourcemap upload ./dist", ); }); + + it.each(["dist", ".", "./build/client"])( + "leaves the plain path %s unquoted", + (artifactPath) => { + expect(getSentryCliNpmScript(artifactPath)).toBe( + `sentry sourcemap inject ${artifactPath} && 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 inject ${quoted} && 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 inject . && sentry sourcemap upload ."', + ), + ); + } finally { + process.chdir(originalCwd); + rmSync(dir, { recursive: true, force: true }); + } + }); }); describe("setSentryCliRcDefaults", () => { diff --git a/packages/cli/test/lib/wizard/sourcemaps/tools/sentryclirc-defaults.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/sentryclirc-defaults.test.ts index 214b297bfb..bccc0d0606 100644 --- a/packages/cli/test/lib/wizard/sourcemaps/tools/sentryclirc-defaults.test.ts +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/sentryclirc-defaults.test.ts @@ -1,5 +1,5 @@ /** - * `addOrgAndProjectToSentryCliRc`, which the generic and Wrangler source + * `addUploadTargetToSentryCliRc`, which the generic and Wrangler source * maps flows call: the `[defaults]` it writes, read back the way v4 reads * `.sentryclirc`, next to the `[auth]` token and the user's other keys. */ @@ -14,7 +14,7 @@ import { clearSentryCliRcCache, loadSentryCliRc, } from "../../../../../src/lib/sentryclirc.js"; -import { addOrgAndProjectToSentryCliRc } from "../../../../../src/lib/wizard/sourcemaps/tools/sentry-cli.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", () => ({ @@ -65,9 +65,9 @@ const saasOptions = { authToken: "sntrys_tok", }; -describe("addOrgAndProjectToSentryCliRc", () => { +describe("addUploadTargetToSentryCliRc", () => { it("writes the org and project, but no url, for sentry.io", async () => { - await addOrgAndProjectToSentryCliRc(saasOptions); + await addUploadTargetToSentryCliRc(saasOptions); expect(readFileSync(rcPath(), "utf8")).toBe( "[defaults]\norg=my-org\nproject=my-project\n", @@ -75,7 +75,7 @@ describe("addOrgAndProjectToSentryCliRc", () => { }); it("writes the url for self-hosted Sentry", async () => { - await addOrgAndProjectToSentryCliRc({ + await addUploadTargetToSentryCliRc({ ...saasOptions, selfHosted: true, url: "https://sentry.example.com/", @@ -92,7 +92,7 @@ describe("addOrgAndProjectToSentryCliRc", () => { "# my settings\n[defaults]\norg=old-org\n\n[http]\nverify_ssl=false\n", ); await addSentryCliConfig({ authToken: "sntrys_tok" }); - await addOrgAndProjectToSentryCliRc(saasOptions); + await addUploadTargetToSentryCliRc(saasOptions); const contents = readFileSync(rcPath(), "utf8"); expect(contents).toContain("# my settings"); From 8506fd017e5b7ef70a3661f451efdd1c90bd9ade Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:54:14 +0000 Subject: [PATCH 15/20] fix(cli): sync sentry-cli and Angular source map tools with #2525 Takes `sourcemaps/tools/sentry-cli.ts`, `sourcemaps/tools/angular.ts` and their tests from getsentry/toolkit#2525 (370f74db) unchanged, so both PRs carry the same copies. This brings in the Angular snippet that sets `sourceMap` in the production configuration and the `forceInstall` option for the `sentry` install. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .../lib/wizard/sourcemaps/tools/angular.ts | 19 +++++--- .../lib/wizard/sourcemaps/tools/sentry-cli.ts | 3 ++ .../wizard/sourcemaps/tools/angular.test.ts | 20 ++++++++ .../sourcemaps/tools/sentry-cli.test.ts | 46 ++++++++++++++++++- 4 files changed, 81 insertions(+), 7 deletions(-) create mode 100644 packages/cli/test/lib/wizard/sourcemaps/tools/angular.test.ts diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/angular.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/angular.ts index 0a5a2485d3..5949281708 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/tools/angular.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/angular.ts @@ -7,17 +7,24 @@ 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. */ +/** + * 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': { + "your-project": { "architect": { "build": { - "options": { - ${plus(`"sourceMap": true`)} - }, - }, + "configurations": { + "production": { + ${plus(`"sourceMap": 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 index 37854eea97..80ec398af0 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts @@ -40,6 +40,8 @@ let addedToBuildCommand = false; type configureSentryCLIOptions = SourceMapUploadToolConfigurationOptions & { defaultArtifactPath?: string | undefined; + /** Passed to the package manager when installing the `sentry` CLI. */ + forceInstall?: boolean | undefined; }; /** @@ -63,6 +65,7 @@ export async function configureSentryCLI( packageName: "sentry@^4", alreadyInstalled: hasPackageInstalled("sentry", packageDotJson), devDependency: true, + forceInstall: options.forceInstall, }); let validPath = false; 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 0000000000..082add11d4 --- /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 index 190e5818b8..7f2f113928 100644 --- a/packages/cli/test/lib/wizard/sourcemaps/tools/sentry-cli.test.ts +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/sentry-cli.test.ts @@ -11,7 +11,10 @@ import { // 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 } from "../../../../../src/lib/wizard/utils/clack/index.js"; +import { + getPackageDotJson, + installPackage, +} from "../../../../../src/lib/wizard/utils/clack/index.js"; import { vi, it, describe, expect, afterEach } from "vitest"; @@ -177,6 +180,47 @@ describe("configureSentryCLI", () => { }); }); +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@^4", forceInstall }), + ); + } finally { + process.chdir(originalCwd); + rmSync(dir, { recursive: true, force: true }); + } + }, + ); +}); + describe("setSentryCliRcDefaults", () => { const values = { org: "my-org", project: "my-project" }; From c438f13258563981c6922e23f33519e938fd4713 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:05:15 +0000 Subject: [PATCH 16/20] fix(cli): fix small bugs in the source maps and Cloudflare wizards Fixes bugs carried over from sentry-wizard 9.1.0 that Warden and Bugbot found on review, without changing how the flows work: - Cloudflare: offer the data collection prompt when the installed SDK version is unknown, using the `^11` range the wizard installs - Cloudflare: stop the TOML `main` match at the closing quote - Vite: recognize quoted `build` and `sourcemap` keys, using the shared `getObjectProperty` helper - Webpack: link the webpack docs when creating a new config - Create React App: name the `GENERATE_SOURCEMAP` variable, and detect CRA from `react-scripts` - Wrangler: exit when the user keeps an existing `sentry:sourcemaps` script, as the prompt says, and read `--outdir` values after several spaces --- .../wizard/cloudflare/cloudflare-wizard.ts | 7 +- .../get-entry-point-from-wrangler-config.ts | 4 +- .../sourcemaps/tools/create-react-app.ts | 2 +- .../src/lib/wizard/sourcemaps/tools/vite.ts | 25 +---- .../lib/wizard/sourcemaps/tools/webpack.ts | 2 +- .../lib/wizard/sourcemaps/tools/wrangler.ts | 4 +- .../wizard/sourcemaps/utils/detect-tool.ts | 1 + .../cloudflare/cloudflare-wizard.test.ts | 98 +++++++++++++++++++ ...t-entry-point-from-wrangler-config.test.ts | 11 +++ .../sourcemaps/tools/create-react-app.test.ts | 21 ++++ .../lib/wizard/sourcemaps/tools/vite.test.ts | 34 +++++++ .../tools/webpack-new-config.test.ts | 43 ++++++++ .../sourcemaps/tools/wrangler-flow.test.ts | 55 +++++++++++ .../wizard/sourcemaps/tools/wrangler.test.ts | 6 ++ .../sourcemaps/utils/detect-tool.test.ts | 25 +++++ 15 files changed, 310 insertions(+), 28 deletions(-) create mode 100644 packages/cli/test/lib/wizard/cloudflare/cloudflare-wizard.test.ts create mode 100644 packages/cli/test/lib/wizard/sourcemaps/tools/create-react-app.test.ts create mode 100644 packages/cli/test/lib/wizard/sourcemaps/tools/webpack-new-config.test.ts create mode 100644 packages/cli/test/lib/wizard/sourcemaps/tools/wrangler-flow.test.ts create mode 100644 packages/cli/test/lib/wizard/sourcemaps/utils/detect-tool.test.ts diff --git a/packages/cli/src/lib/wizard/cloudflare/cloudflare-wizard.ts b/packages/cli/src/lib/wizard/cloudflare/cloudflare-wizard.ts index 51a28ee9ca..afef021f41 100644 --- a/packages/cli/src/lib/wizard/cloudflare/cloudflare-wizard.ts +++ b/packages/cli/src/lib/wizard/cloudflare/cloudflare-wizard.ts @@ -40,6 +40,9 @@ import { } from "./wrangler/get-entry-point-from-wrangler-config.js"; import { updateWranglerConfig } from "./wrangler/update-wrangler-config.js"; +/** The `@sentry/cloudflare` range the wizard installs. */ +const SDK_INSTALL_RANGE = "^11"; + /** Run the Cloudflare wizard (`sentry wizard -i cloudflare`). */ export async function runCloudflareWizard( options: WizardOptions, @@ -93,7 +96,7 @@ async function runCloudflareWizardWithTelemetry( printSdkV11MigrationGuideIfOutdated("@sentry/cloudflare", packageJson); await installPackage({ - packageName: "@sentry/cloudflare@^11", + packageName: `@sentry/cloudflare@${SDK_INSTALL_RANGE}`, packageNameDisplayLabel: "@sentry/cloudflare", alreadyInstalled: hasPackageInstalled("@sentry/cloudflare", packageJson), forceInstall, @@ -119,7 +122,7 @@ async function runCloudflareWizardWithTelemetry( // 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, "^10") && + sdkSupportsDataCollection(installedSdkVersion, SDK_INSTALL_RANGE) && (await askShouldReduceDataCollection()); await traceStep("Create Sentry initialization", async () => { diff --git a/packages/cli/src/lib/wizard/cloudflare/wrangler/get-entry-point-from-wrangler-config.ts b/packages/cli/src/lib/wizard/cloudflare/wrangler/get-entry-point-from-wrangler-config.ts index 07f01347ed..e244f72a1b 100644 --- a/packages/cli/src/lib/wizard/cloudflare/wrangler/get-entry-point-from-wrangler-config.ts +++ b/packages/cli/src/lib/wizard/cloudflare/wrangler/get-entry-point-from-wrangler-config.ts @@ -28,9 +28,9 @@ export function getEntryPointFromWranglerConfig(): string | undefined { switch (extname) { case ".toml": { - const mainMatch = configContent.match(/^main\s*=\s*["'](.+)["']/m); + const mainMatch = configContent.match(/^main\s*=\s*(["'])(.+?)\1/m); - return mainMatch?.[1]; + return mainMatch?.[2]; } case ".json": diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/create-react-app.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/create-react-app.ts index 44c6023238..dadf33c278 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/tools/create-react-app.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/create-react-app.ts @@ -10,7 +10,7 @@ import { clack } from "../../utils/clack/prompts.js"; export async function configureCRASourcemapGenerationFlow(): Promise { await abortIfCancelled( clack.select({ - message: `Verify that you are generating source maps when building your React app.\nGenerally this should already happen unless you set the GENERATE_SOURCEMAPS environment variable to false.`, + message: `Verify that you are generating source maps when building your React app.\nGenerally this should already happen unless you set the GENERATE_SOURCEMAP environment variable to false.`, options: [ { label: "I checked!", diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/vite.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/vite.ts index 5c243ab9f2..3b2f4350ba 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/tools/vite.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/vite.ts @@ -13,6 +13,7 @@ import recast from "recast"; import { Sentry } from "../../telemetry.js"; import { + getObjectProperty, hasSentryContent, preserveTrailingNewline, } from "../../utils/ast-utils.js"; @@ -190,7 +191,7 @@ function enableSourcemapGeneration(program: t.Program): boolean { const b = recast.types.builders; - const buildProp = findPropertyByName(configObj.properties, "build"); + const buildProp = getObjectProperty(configObj, "build"); // case 1: build property doesn't exist yet, so we can just add it if (!buildProp) { @@ -205,15 +206,12 @@ function enableSourcemapGeneration(program: t.Program): boolean { return true; } - if ( - buildProp.type !== "ObjectProperty" || - buildProp.value.type !== "ObjectExpression" - ) { + if (buildProp.value.type !== "ObjectExpression") { return false; } const buildObj = buildProp.value; - const sourceMapsProp = findPropertyByName(buildObj.properties, "sourcemap"); + const sourceMapsProp = getObjectProperty(buildObj, "sourcemap"); // case 2: build.sourcemap property doesn't exist yet, so we just add it if (!sourceMapsProp) { @@ -223,10 +221,6 @@ function enableSourcemapGeneration(program: t.Program): boolean { return true; } - if (sourceMapsProp.type !== "ObjectProperty") { - return false; - } - // case 3: build.sourcemap property exists, and it's set to 'hidden' if ( sourceMapsProp.value.type === "StringLiteral" && @@ -242,17 +236,6 @@ function enableSourcemapGeneration(program: t.Program): boolean { return true; } -/** The property of `properties` whose identifier key is `name`. */ -function findPropertyByName( - properties: t.ObjectExpression["properties"], - name: string, -): t.ObjectMethod | t.ObjectProperty | t.Property | undefined { - return properties.find( - (p): p is t.ObjectMethod | t.ObjectProperty | t.Property => - "key" in p && p.key.type === "Identifier" && p.key.name === name, - ); -} - function getViteConfigObject( program: t.Program, ): t.ObjectExpression | undefined { diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/webpack.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/webpack.ts index 1ba5d9c3aa..2d8706e880 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/tools/webpack.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/webpack.ts @@ -73,7 +73,7 @@ export const configureWebPackPlugin: SourceMapUploadToolConfigurationFunction = successfullyAdded = await createNewConfigFile( path.join(process.cwd(), "webpack.config.js"), getCodeSnippet(options, false, importPath), - "More information about Webpack configs: https://vitejs.dev/config/", + "More information about Webpack configs: https://webpack.js.org/configuration/", ); Sentry.setTag( "created-new-config", diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/wrangler.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/wrangler.ts index d35098f479..b4a10efb9a 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/tools/wrangler.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/wrangler.ts @@ -81,6 +81,7 @@ Otherwise, let's proceed with the Wrangler setup.`, }); if (!(await askContinueIfHasSentrySourcemapsScript())) { + await abort("Exiting the wizard.", 0); return; } @@ -397,7 +398,8 @@ async function getWranglerOutDir(deployScript: string): Promise { export function findOutDir(deployCommand: string): string { const args = getWranglerDeployCommand(deployCommand) ?.split(" ") - .map((arg) => arg.trim()); + .map((arg) => arg.trim()) + .filter(Boolean); if (!args) { return DIST_DIR; diff --git a/packages/cli/src/lib/wizard/sourcemaps/utils/detect-tool.ts b/packages/cli/src/lib/wizard/sourcemaps/utils/detect-tool.ts index 7c0657ab38..79acf9925a 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/utils/detect-tool.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/utils/detect-tool.ts @@ -30,6 +30,7 @@ export type SupportedTools = */ const TOOL_PACKAGE_MAP: Record = { "@angular/core": "angular", + "react-scripts": "create-react-app", "create-react-app": "create-react-app", wrangler: "wrangler", webpack: "webpack", diff --git a/packages/cli/test/lib/wizard/cloudflare/cloudflare-wizard.test.ts b/packages/cli/test/lib/wizard/cloudflare/cloudflare-wizard.test.ts new file mode 100644 index 0000000000..755595f073 --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/cloudflare-wizard.test.ts @@ -0,0 +1,98 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { runCloudflareWizard } from "../../../../src/lib/wizard/cloudflare/cloudflare-wizard.js"; +import { askShouldReduceDataCollection } from "../../../../src/lib/wizard/utils/data-collection.js"; +import { getPackageVersion } from "../../../../src/lib/wizard/utils/package-json.js"; +import type { WizardOptions } from "../../../../src/lib/wizard/utils/types.js"; + +vi.mock("@clack/prompts", () => ({ + log: { info: vi.fn(), warn: vi.fn(), success: vi.fn() }, + outro: vi.fn(), +})); +vi.mock("../../../../src/lib/wizard/telemetry.js", () => ({ + withTelemetry: (_options: unknown, callback: () => unknown) => callback(), + traceStep: (_step: string, callback: () => unknown) => callback(), +})); +vi.mock("../../../../src/lib/wizard/utils/clack/index.js", () => ({ + confirmContinueIfNoOrDirtyGitRepo: vi.fn(), + ensurePackageIsInstalled: vi.fn(), + featureSelectionPrompt: vi + .fn() + .mockResolvedValue({ performance: false, logs: false }), + getOrAskForProjectData: vi.fn().mockResolvedValue({ + spotlight: false, + selectedProject: { + slug: "my-project", + organization: { slug: "my-org" }, + keys: [{ dsn: { public: "https://key@example.ingest.sentry.io/1" } }], + }, + }), + getPackageDotJson: vi.fn().mockResolvedValue({}), + installPackage: vi.fn(), + printSdkV11MigrationGuideIfOutdated: vi.fn(), + printWelcome: vi.fn(), + runPrettierIfInstalled: vi.fn(), +})); +vi.mock("../../../../src/lib/wizard/utils/clack/mcp-config.js", () => ({ + offerProjectScopedMcpConfig: vi.fn(), +})); +vi.mock("../../../../src/lib/wizard/utils/data-collection.js", async () => ({ + ...(await vi.importActual( + "../../../../src/lib/wizard/utils/data-collection.js", + )), + askShouldReduceDataCollection: vi.fn().mockResolvedValue(false), +})); +vi.mock("../../../../src/lib/wizard/utils/node-version.js", () => ({ + warnIfNodeVersionUnsupportedBySdkV11: vi.fn(), +})); +vi.mock("../../../../src/lib/wizard/utils/package-json.js", () => ({ + getPackageVersion: vi.fn(), + hasPackageInstalled: vi.fn().mockReturnValue(false), +})); +vi.mock("../../../../src/lib/wizard/cloudflare/sdk-setup.js", () => ({ + createSentryInitFile: vi.fn(), +})); +vi.mock( + "../../../../src/lib/wizard/cloudflare/wrangler/ensure-wrangler-config.js", + () => ({ ensureWranglerConfig: vi.fn() }), +); +vi.mock( + "../../../../src/lib/wizard/cloudflare/wrangler/get-entry-point-from-wrangler-config.js", + () => ({ + defaultEntryPoint: "src/index.ts", + getEntryPointFromWranglerConfig: vi.fn().mockReturnValue("src/index.ts"), + }), +); +vi.mock( + "../../../../src/lib/wizard/cloudflare/wrangler/update-wrangler-config.js", + () => ({ updateWranglerConfig: vi.fn() }), +); + +const options: WizardOptions = { + telemetryEnabled: false, + forceInstall: false, + ignoreGitChanges: true, +}; + +describe("runCloudflareWizard", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("offers to reduce data collection when the installed SDK version is unknown", async () => { + // e.g. `workspace:*`: the wizard falls back to the major it installs (v11) + vi.mocked(getPackageVersion).mockReturnValue(undefined); + + await runCloudflareWizard(options); + + expect(askShouldReduceDataCollection).toHaveBeenCalledTimes(1); + }); + + it("does not offer it when an older SDK stays installed", async () => { + vi.mocked(getPackageVersion).mockReturnValue("^10.5.0"); + + await runCloudflareWizard(options); + + expect(askShouldReduceDataCollection).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/cli/test/lib/wizard/cloudflare/get-entry-point-from-wrangler-config.test.ts b/packages/cli/test/lib/wizard/cloudflare/get-entry-point-from-wrangler-config.test.ts index e26fde579c..b5fdbac47a 100644 --- a/packages/cli/test/lib/wizard/cloudflare/get-entry-point-from-wrangler-config.test.ts +++ b/packages/cli/test/lib/wizard/cloudflare/get-entry-point-from-wrangler-config.test.ts @@ -44,6 +44,17 @@ compatibility_date = "2024-01-01"`, expect(result).toBe("src/worker.ts"); }); + it("stops at the closing quote of main in wrangler.toml", () => { + fs.writeFileSync( + path.join(tmpDir, "wrangler.toml"), + `main = "src/worker.ts" # see "docs" or 'more docs'`, + ); + + const result = getEntryPointFromWranglerConfig(); + + expect(result).toBe("src/worker.ts"); + }); + it("parses main from wrangler.json", () => { fs.writeFileSync( path.join(tmpDir, "wrangler.json"), diff --git a/packages/cli/test/lib/wizard/sourcemaps/tools/create-react-app.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/create-react-app.test.ts new file mode 100644 index 0000000000..c5d08728fd --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/create-react-app.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it, vi } from "vitest"; + +import { configureCRASourcemapGenerationFlow } from "../../../../../src/lib/wizard/sourcemaps/tools/create-react-app.js"; + +const { selectMock } = vi.hoisted(() => ({ + selectMock: vi.fn().mockResolvedValue(true), +})); + +vi.mock("@clack/prompts", () => ({ + select: selectMock, + isCancel: vi.fn().mockReturnValue(false), +})); + +describe("configureCRASourcemapGenerationFlow", () => { + it("names the variable Create React App reads", async () => { + await configureCRASourcemapGenerationFlow(); + + const message = String(selectMock.mock.calls[0]?.[0]?.message); + expect(message).toMatch(/\bGENERATE_SOURCEMAP\b/); + }); +}); diff --git a/packages/cli/test/lib/wizard/sourcemaps/tools/vite.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/vite.test.ts index 13385d3e19..d823ea38ce 100644 --- a/packages/cli/test/lib/wizard/sourcemaps/tools/vite.test.ts +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/vite.test.ts @@ -156,4 +156,38 @@ export default cfg; expect(addedCode).toBe(true); }, ); + + it("recognizes quoted build and sourcemap keys", async () => { + updateFileContent(` +export default defineConfig({ + plugins: [vue()], + "build": { + outDir: "out", + "sourcemap": "hidden", + }, +}) +`); + + const addedCode = await addVitePluginToConfig( + "", + { + authToken: "", + orgSlug: "my-org", + projectSlug: "my-project", + selfHosted: false, + url: "https://sentry.io/", + }, + "@sentry/bundler-plugins/vite", + ); + + expect(addedCode).toBe(true); + const written = writeFileSpy.mock.calls[0]?.[1]; + if (typeof written !== "string") { + throw new Error("expected the config to be written as a string"); + } + expect(written.match(/build/g)).toHaveLength(1); + expect(written).toContain('outDir: "out"'); + expect(written).toContain('"sourcemap": "hidden"'); + expect(written).not.toContain("sourcemap: true"); + }); }); diff --git a/packages/cli/test/lib/wizard/sourcemaps/tools/webpack-new-config.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/webpack-new-config.test.ts new file mode 100644 index 0000000000..9370b1ec2c --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/webpack-new-config.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it, vi } from "vitest"; + +import { configureWebPackPlugin } from "../../../../../src/lib/wizard/sourcemaps/tools/webpack.js"; +import { createNewConfigFile } from "../../../../../src/lib/wizard/utils/clack/index.js"; + +vi.mock("@clack/prompts", () => ({ + log: { info: vi.fn(), success: vi.fn() }, +})); +vi.mock("../../../../../src/lib/dsn/fs-utils.js", () => ({ + findFile: vi.fn().mockResolvedValue(undefined), +})); +vi.mock( + "../../../../../src/lib/wizard/sourcemaps/utils/bundler-plugin.js", + () => ({ + ensureBundlerPlugin: vi.fn().mockResolvedValue("@sentry/webpack-plugin"), + }), +); +vi.mock("../../../../../src/lib/wizard/utils/clack/index.js", async () => ({ + ...(await vi.importActual( + "../../../../../src/lib/wizard/utils/clack/index.js", + )), + addDotEnvSentryBuildPluginFile: vi.fn(), + askForToolConfigPath: vi.fn().mockResolvedValue(undefined), + createNewConfigFile: vi.fn().mockResolvedValue(true), +})); + +describe("configureWebPackPlugin", () => { + it("points to the webpack docs when it creates a new config", async () => { + await configureWebPackPlugin({ + authToken: "", + orgSlug: "my-org", + projectSlug: "my-project", + selfHosted: false, + url: "https://sentry.io/", + }); + + expect(createNewConfigFile).toHaveBeenCalledWith( + expect.stringContaining("webpack.config.js"), + expect.any(String), + expect.stringContaining("https://webpack.js.org/"), + ); + }); +}); diff --git a/packages/cli/test/lib/wizard/sourcemaps/tools/wrangler-flow.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/wrangler-flow.test.ts new file mode 100644 index 0000000000..0a749e2940 --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/wrangler-flow.test.ts @@ -0,0 +1,55 @@ +import { promises } from "node:fs"; + +import { describe, expect, it, vi } from "vitest"; + +import { WizardExitError } from "../../../../../src/lib/errors.js"; +import { configureWrangler } from "../../../../../src/lib/wizard/sourcemaps/tools/wrangler.js"; +import { getPackageDotJson } from "../../../../../src/lib/wizard/utils/clack/index.js"; + +const { selectMock } = vi.hoisted(() => ({ + selectMock: vi.fn(), +})); + +const writeFileSpy = vi + .spyOn(promises, "writeFile") + .mockImplementation(() => Promise.resolve()); + +vi.mock("@clack/prompts", () => ({ + log: { info: vi.fn(), warn: vi.fn(), success: vi.fn() }, + note: vi.fn(), + outro: vi.fn(), + confirm: vi.fn().mockResolvedValue(true), + select: selectMock, + 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(), +})); + +const options = { + authToken: "token", + orgSlug: "my-org", + projectSlug: "my-project", + selfHosted: false, + url: "https://sentry.io/", +}; + +describe("configureWrangler", () => { + it("exits when the user keeps the existing sentry:sourcemaps script", async () => { + vi.mocked(getPackageDotJson).mockResolvedValue({ + scripts: { + deploy: "wrangler deploy", + "sentry:sourcemaps": "echo existing", + }, + }); + selectMock.mockResolvedValueOnce(false); + + await expect(configureWrangler(options)).rejects.toThrow(WizardExitError); + expect(writeFileSpy).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/cli/test/lib/wizard/sourcemaps/tools/wrangler.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/wrangler.test.ts index 50e5538901..a0824dc866 100644 --- a/packages/cli/test/lib/wizard/sourcemaps/tools/wrangler.test.ts +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/wrangler.test.ts @@ -167,6 +167,12 @@ describe("findOutDir", () => { expect(outDir).toBe("someplace"); }); + it("handles more than one space before the outdir value", () => { + const outDir = findOutDir("wrangler deploy --outdir someplace"); + + expect(outDir).toBe("someplace"); + }); + it('handles --outdir "./someplace.js"', () => { const outDir = findOutDir('wrangler deploy --outdir "./someplace.js"'); diff --git a/packages/cli/test/lib/wizard/sourcemaps/utils/detect-tool.test.ts b/packages/cli/test/lib/wizard/sourcemaps/utils/detect-tool.test.ts new file mode 100644 index 0000000000..07f114a192 --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/utils/detect-tool.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it, vi } from "vitest"; + +import { detectUsedTool } from "../../../../../src/lib/wizard/sourcemaps/utils/detect-tool.js"; +import { getPackageDotJson } from "../../../../../src/lib/wizard/utils/clack/index.js"; + +vi.mock("../../../../../src/lib/wizard/utils/clack/index.js", () => ({ + getPackageDotJson: vi.fn(), +})); + +describe("detectUsedTool", () => { + it("detects Create React App from react-scripts before TypeScript", async () => { + vi.mocked(getPackageDotJson).mockResolvedValue({ + dependencies: { react: "^18.0.0", "react-scripts": "5.0.1" }, + devDependencies: { typescript: "^5.0.0" }, + }); + + await expect(detectUsedTool()).resolves.toBe("create-react-app"); + }); + + it("falls back to the generic flow", async () => { + vi.mocked(getPackageDotJson).mockResolvedValue({}); + + await expect(detectUsedTool()).resolves.toBe("sentry-cli"); + }); +}); From f3053febc676089baf6f0008b1b935a8c0849dc8 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:16:50 +0000 Subject: [PATCH 17/20] fix(cli): drop the redundant inject step from the sentry:sourcemaps script `sentry sourcemap upload` already injects missing debug IDs into the files on disk before it uploads them, the same way `sentry sourcemap inject` does, so the script ran injection twice. Run only the upload. --- .../cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts | 11 ++++++----- .../lib/wizard/sourcemaps/tools/sentry-cli.test.ts | 10 +++++----- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts index 80ec398af0..467cd71d5a 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts @@ -3,8 +3,8 @@ * Sentry bundler plugin (Angular, tsc, Create React App, …). * * Installs the `sentry` CLI package, adds a `sentry:sourcemaps` npm script - * that runs `sentry sourcemap inject` and `sentry sourcemap upload` on the - * build output, optionally appends it to the production build script, and + * 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`. @@ -188,8 +188,9 @@ export async function setupNpmScriptInCI(): Promise { } /** - * The `sentry:sourcemaps` script: inject debug IDs into the build output, - * then upload it. `sentry sourcemap upload` reads the org and project from + * 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. */ @@ -200,7 +201,7 @@ export function getSentryCliNpmScript( // 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 inject ${artifactPath} && sentry sourcemap upload ${artifactPath}`; + return `sentry sourcemap upload ${artifactPath}`; } /** Characters that make a shell split or expand an unquoted argument. */ 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 index 7f2f113928..706b6e26dc 100644 --- a/packages/cli/test/lib/wizard/sourcemaps/tools/sentry-cli.test.ts +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/sentry-cli.test.ts @@ -114,9 +114,9 @@ describe("addSentryCommandToBuildCommand", () => { }); describe("getSentryCliNpmScript", () => { - it("injects debug IDs and uploads with v4 sentry commands, without org or project flags", () => { + it("uploads with the v4 sentry command, without org or project flags", () => { expect(getSentryCliNpmScript("./dist")).toBe( - "sentry sourcemap inject ./dist && sentry sourcemap upload ./dist", + "sentry sourcemap upload ./dist", ); }); @@ -124,7 +124,7 @@ describe("getSentryCliNpmScript", () => { "leaves the plain path %s unquoted", (artifactPath) => { expect(getSentryCliNpmScript(artifactPath)).toBe( - `sentry sourcemap inject ${artifactPath} && sentry sourcemap upload ${artifactPath}`, + `sentry sourcemap upload ${artifactPath}`, ); }, ); @@ -136,7 +136,7 @@ describe("getSentryCliNpmScript", () => { ["dist/$HOME", '"dist/\\$HOME"'], ])("double-quotes %s as %s", (artifactPath, quoted) => { expect(getSentryCliNpmScript(artifactPath)).toBe( - `sentry sourcemap inject ${quoted} && sentry sourcemap upload ${quoted}`, + `sentry sourcemap upload ${quoted}`, ); }); }); @@ -170,7 +170,7 @@ describe("configureSentryCLI", () => { expect(writeFileSpy).toHaveBeenCalledWith( expect.stringContaining("package.json"), expect.stringContaining( - '"sentry:sourcemaps": "sentry sourcemap inject . && sentry sourcemap upload ."', + '"sentry:sourcemaps": "sentry sourcemap upload ."', ), ); } finally { From 03510b3c07eddb4c07a1bc58cf0cf3b6b035ed60 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:16:52 +0000 Subject: [PATCH 18/20] docs(cli): say the wizard's source map script only runs the upload --- apps/cli-docs/src/fragments/commands/wizard.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/apps/cli-docs/src/fragments/commands/wizard.md b/apps/cli-docs/src/fragments/commands/wizard.md index b84d9bf49d..7678d44316 100644 --- a/apps/cli-docs/src/fragments/commands/wizard.md +++ b/apps/cli-docs/src/fragments/commands/wizard.md @@ -53,9 +53,9 @@ 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 inject` and `sentry sourcemap upload` -on your build output. 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`, +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`. From 9bb011e3d2eb720e4bff92a31831404cd440500f Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:46:35 +0000 Subject: [PATCH 19/20] fix(cli): install the sentry CLI major the wizard runs on The wizard installed `sentry@^4`, which matches no published version, so source map setup stopped after the SDK and config changes. Install the major of the running CLI instead (`sentry@0.x` today), with no shell metacharacters, since installPackage runs the package manager through a shell. --- .../lib/wizard/sourcemaps/tools/sentry-cli.ts | 10 +++++++++- .../sourcemaps/tools/sentry-cli.test.ts | 20 ++++++++++++++++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts index 467cd71d5a..30c589fd6c 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts @@ -17,6 +17,7 @@ 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, @@ -36,6 +37,13 @@ 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 & { @@ -62,7 +70,7 @@ export async function configureSentryCLI( const packageDotJson = await getPackageDotJson(); await installPackage({ - packageName: "sentry@^4", + packageName: SENTRY_CLI_PACKAGE_SPEC, alreadyInstalled: hasPackageInstalled("sentry", packageDotJson), devDependency: true, forceInstall: options.forceInstall, 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 index 706b6e26dc..5568577277 100644 --- a/packages/cli/test/lib/wizard/sourcemaps/tools/sentry-cli.test.ts +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/sentry-cli.test.ts @@ -6,8 +6,10 @@ 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"; @@ -211,7 +213,10 @@ describe("configureSentryCLI forceInstall", () => { ); expect(installPackage).toHaveBeenLastCalledWith( - expect.objectContaining({ packageName: "sentry@^4", forceInstall }), + expect.objectContaining({ + packageName: SENTRY_CLI_PACKAGE_SPEC, + forceInstall, + }), ); } finally { process.chdir(originalCwd); @@ -221,6 +226,19 @@ describe("configureSentryCLI forceInstall", () => { ); }); +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" }; From 24ee6996ed75faa968169ddb8f9cba2b140af1b9 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:04:06 +0000 Subject: [PATCH 20/20] fix(cli): install the running sentry CLI major in the Wrangler flow The Wrangler flow still installed `sentry@^4`, which matches no published version, and `^` is a shell metacharacter for installPackage. Use SENTRY_CLI_PACKAGE_SPEC, as the generic flow does. --- .../lib/wizard/sourcemaps/tools/wrangler.ts | 7 +++++-- .../sourcemaps/tools/wrangler-flow.test.ts | 18 +++++++++++++++++- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/wrangler.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/wrangler.ts index b4a10efb9a..43b3d82547 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/tools/wrangler.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/wrangler.ts @@ -25,7 +25,10 @@ import { import { clack } from "../../utils/clack/prompts.js"; import { hasPackageInstalled } from "../../utils/package-json.js"; import { NPM } from "../../utils/package-manager.js"; -import { addUploadTargetToSentryCliRc } from "./sentry-cli.js"; +import { + addUploadTargetToSentryCliRc, + SENTRY_CLI_PACKAGE_SPEC, +} from "./sentry-cli.js"; import type { SourceMapUploadToolConfigurationOptions } from "./types.js"; const SENTRY_NPM_SCRIPT_NAME = "sentry:sourcemaps"; @@ -75,7 +78,7 @@ Otherwise, let's proceed with the Wrangler setup.`, } await installPackage({ - packageName: "sentry@^4", + packageName: SENTRY_CLI_PACKAGE_SPEC, alreadyInstalled: hasPackageInstalled("sentry", await getPackageDotJson()), devDependency: true, }); diff --git a/packages/cli/test/lib/wizard/sourcemaps/tools/wrangler-flow.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/wrangler-flow.test.ts index 0a749e2940..94cc7d8fa1 100644 --- a/packages/cli/test/lib/wizard/sourcemaps/tools/wrangler-flow.test.ts +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/wrangler-flow.test.ts @@ -3,8 +3,12 @@ import { promises } from "node:fs"; import { describe, expect, it, vi } from "vitest"; import { WizardExitError } from "../../../../../src/lib/errors.js"; +import { SENTRY_CLI_PACKAGE_SPEC } from "../../../../../src/lib/wizard/sourcemaps/tools/sentry-cli.js"; import { configureWrangler } from "../../../../../src/lib/wizard/sourcemaps/tools/wrangler.js"; -import { getPackageDotJson } from "../../../../../src/lib/wizard/utils/clack/index.js"; +import { + getPackageDotJson, + installPackage, +} from "../../../../../src/lib/wizard/utils/clack/index.js"; const { selectMock } = vi.hoisted(() => ({ selectMock: vi.fn(), @@ -52,4 +56,16 @@ describe("configureWrangler", () => { await expect(configureWrangler(options)).rejects.toThrow(WizardExitError); expect(writeFileSpy).not.toHaveBeenCalled(); }); + + it("installs the sentry CLI major the wizard runs on", async () => { + vi.mocked(getPackageDotJson).mockResolvedValue({ + scripts: { "sentry:sourcemaps": "echo existing" }, + }); + selectMock.mockResolvedValueOnce(false); + + await expect(configureWrangler(options)).rejects.toThrow(WizardExitError); + expect(installPackage).toHaveBeenCalledWith( + expect.objectContaining({ packageName: SENTRY_CLI_PACKAGE_SPEC }), + ); + }); });