diff --git a/apps/cli-docs/src/fragments/commands/wizard.md b/apps/cli-docs/src/fragments/commands/wizard.md index 5412b86ff..b396ea280 100644 --- a/apps/cli-docs/src/fragments/commands/wizard.md +++ b/apps/cli-docs/src/fragments/commands/wizard.md @@ -57,3 +57,12 @@ but not most of its flags or its `SENTRY_WIZARD_*` environment variables: The Cordova and Electron wizards were retired. Follow their setup guides in the Sentry docs instead. + +Flows that uploaded source maps with `@sentry/cli`, such as Angular, now +install the `sentry` package instead. The `sentry:sourcemaps` script they add +to `package.json` runs `sentry sourcemap upload` on your build output, which +injects debug IDs before it uploads. The wizard writes your org, project and, +on self-hosted Sentry, URL to the `[defaults]` section of the project's +`.sentryclirc`, next to the auth token, and adds the file to `.gitignore`. In +CI, set `SENTRY_AUTH_TOKEN`. On self-hosted Sentry, also set `SENTRY_ORG`, +`SENTRY_PROJECT` and `SENTRY_URL`. diff --git a/packages/cli/src/lib/wizard/cloudflare/cloudflare-wizard.ts b/packages/cli/src/lib/wizard/cloudflare/cloudflare-wizard.ts new file mode 100644 index 000000000..afef021f4 --- /dev/null +++ b/packages/cli/src/lib/wizard/cloudflare/cloudflare-wizard.ts @@ -0,0 +1,191 @@ +/** + * 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"; + +/** 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, +): Promise { + return await withTelemetry( + { + enabled: options.telemetryEnabled, + integration: "cloudflare", + wizardOptions: options, + }, + () => runCloudflareWizardWithTelemetry(options), + ); +} + +async function runCloudflareWizardWithTelemetry( + options: WizardOptions, +): Promise { + const { telemetryEnabled, forceInstall } = options; + + printWelcome({ + wizardName: "Sentry Cloudflare Wizard", + 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@${SDK_INSTALL_RANGE}`, + 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, SDK_INSTALL_RANGE) && + (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 000000000..f1dc97c1c --- /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 000000000..9c3655747 --- /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 000000000..e6b8e8ef5 --- /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 000000000..61f4cd6b3 --- /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 000000000..0272238c0 --- /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 000000000..e244f72a1 --- /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*(["'])(.+?)\1/m); + + return mainMatch?.[2]; + } + + 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 000000000..785cb9375 --- /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") { + for (const element of existingProperty.value.elements) { + 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 000000000..6023539c9 --- /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 0e2f411ec..1f98d3603 100644 --- a/packages/cli/src/lib/wizard/run.ts +++ b/packages/cli/src/lib/wizard/run.ts @@ -66,6 +66,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); + }, remix: async (options) => { const { runRemixWizard } = await import("./remix/remix-wizard.js"); await runRemixWizard(options); diff --git a/packages/cli/src/lib/wizard/sourcemaps/ci.ts b/packages/cli/src/lib/wizard/sourcemaps/ci.ts index ed73aa32c..136492b31 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/ci.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/ci.ts @@ -13,6 +13,7 @@ import { SENTRY_DOT_ENV_FILE, } from "../utils/clack/index.js"; import { clack } from "../utils/clack/prompts.js"; +import { setupNpmScriptInCI } from "./tools/sentry-cli.js"; /** Tools that upload with `sentry` commands and read `.sentryclirc`. */ const CLI_BASED_FLOW_TOOLS: readonly string[] = [ @@ -20,26 +21,44 @@ const CLI_BASED_FLOW_TOOLS: readonly string[] = [ "tsc", "angular", "create-react-app", + "wrangler", ]; /** - * Ask whether the user builds in CI and, if so, show the auth token to set - * there. + * Where `sentry sourcemap upload` sends source maps. On self-hosted Sentry, + * CI gets it from `SENTRY_ORG`, `SENTRY_PROJECT` and `SENTRY_URL`. + */ +export type SentryCliUploadTarget = { + org: string; + project: string; + /** The self-hosted Sentry URL. Unset for sentry.io. */ + url?: string | undefined; +}; + +/** + * Ask whether the user builds in CI and, if so, show the environment + * variables to set there. * * @param selectedTool - The build tool the wizard configured, such as `nextjs` * @param authToken - The token written to the local config file + * @param uploadTarget - For tools that upload with `sentry` commands, the + * org, project, and URL that CI needs as well on self-hosted Sentry */ export async function setupCI( selectedTool: string, authToken: string, + uploadTarget?: SentryCliUploadTarget, ): Promise { - await traceStep("configure-ci", () => configureCI(selectedTool, authToken)); + await traceStep("configure-ci", () => + configureCI(selectedTool, authToken, uploadTarget), + ); } -/** Ask about CI and show the auth token to set there. */ +/** Ask about CI and show the environment variables to set there. */ async function configureCI( selectedTool: string, authToken: string, + uploadTarget: SentryCliUploadTarget | undefined, ): Promise { const isUsingCI = await abortIfCancelled( clack.select({ @@ -62,7 +81,9 @@ async function configureCI( Sentry.setTag("using-ci", isUsingCI); - const authTokenFile = CLI_BASED_FLOW_TOOLS.includes(selectedTool) + const isCliBasedFlowTool = CLI_BASED_FLOW_TOOLS.includes(selectedTool); + + const authTokenFile = isCliBasedFlowTool ? SENTRY_CLI_RC_FILE : SENTRY_DOT_ENV_FILE; @@ -75,19 +96,52 @@ async function configureCI( return; } - await traceStep("ci-auth-token-setup", () => setupAuthTokenInCI(authToken)); + // Wrangler's `post` script already runs `sentry:sourcemaps` + if (isCliBasedFlowTool && selectedTool !== "wrangler") { + await traceStep("ci-npm-script-setup", setupNpmScriptInCI); + } + + await traceStep("ci-auth-token-setup", () => + setupAuthTokenInCI( + authToken, + isCliBasedFlowTool ? uploadTarget : undefined, + ), + ); } -/** Show the auth token to add to the CI environment. */ -async function setupAuthTokenInCI(authToken: string): Promise { +/** The `NAME=value` lines to add to the CI environment. */ +export function getCIEnvVars( + authToken: string, + uploadTarget: SentryCliUploadTarget | undefined, +): string[] { + const lines = [`SENTRY_AUTH_TOKEN=${authToken}`]; + // 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}`, + ); + } + return lines; +} + +/** Show the auth token, and the upload target if any, to add to CI. */ +async function setupAuthTokenInCI( + authToken: string, + uploadTarget: SentryCliUploadTarget | undefined, +): Promise { clack.log.step( - "Add the Sentry authentication token as an environment variable to your CI setup:", + uploadTarget?.url + ? "Add these environment variables to your CI setup:" + : "Add the Sentry authentication token as an environment variable to your CI setup:", ); // Printed outside clack's gutter so that it can be copied/pasted directly clack.rawOutput( chalk.greenBright(` -SENTRY_AUTH_TOKEN=${authToken} +${getCIEnvVars(authToken, uploadTarget).join("\n")} `), ); diff --git a/packages/cli/src/lib/wizard/sourcemaps/sourcemaps-wizard.ts b/packages/cli/src/lib/wizard/sourcemaps/sourcemaps-wizard.ts new file mode 100644 index 000000000..a9fd91350 --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/sourcemaps-wizard.ts @@ -0,0 +1,288 @@ +/** + * 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 { buildProjectIssuesUrl } from "../../sentry-web-urls.js"; +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 { 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 :)`, + 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, { + 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 + // skip it, if it's called from another wizard (e.g. angular) + await runPrettierIfInstalled({ cwd: process.cwd() }); + } + + if (!preSelectedTool) { + await traceStep("outro", () => + printOutro(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(orgSlug: string, projectId: string): Promise { + const packageManager = await getPackageManager(NPM); + + const issueStreamUrl = buildProjectIssuesUrl(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 000000000..594928170 --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/angular.ts @@ -0,0 +1,56 @@ +/** + * The source map generation step for Angular: shows the `angular.json` + * setting that turns on source maps and asks the user to check it. + */ + +import { clack } from "../../utils/clack/prompts.js"; +import chalk from "chalk"; +import { abortIfCancelled, makeCodeSnippet } from "../../utils/clack/index.js"; + +/** + * The `angular.json` change that turns on source maps. It goes in the + * production configuration, like the automatic `angular.json` edit, because + * Angular's default production configuration sets `sourceMap: false`, which + * overrides `options`. + */ +const angularJsonTemplate = makeCodeSnippet(true, (unchanged, plus) => + unchanged(`{ + "projects": { + "your-project": { + "architect": { + "build": { + "configurations": { + "production": { + ${plus(`"sourceMap": true`)} + } + } + } + } + } + } +}`), +); + +/** Show the `angular.json` change and wait until the user confirms it. */ +export async function configureAngularSourcemapGenerationFlow(): Promise { + clack.log.info( + `Enable generating source maps in your ${chalk.bold("angular.json")} file:`, + ); + + // Printed outside clack's gutter so that it can be copied/pasted directly + clack.rawOutput(angularJsonTemplate); + + await abortIfCancelled( + clack.select({ + message: `Verify that you are generating source maps when building your Angular app.`, + options: [ + { + label: "I checked!", + hint: "My build output folder contains .js.map files after a build.", + value: true, + }, + ], + initialValue: true, + }), + ); +} diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/create-react-app.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/create-react-app.ts new file mode 100644 index 000000000..dadf33c27 --- /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_SOURCEMAP 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 000000000..92a4c2cac --- /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 000000000..bc581065f --- /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 000000000..30c589fd6 --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts @@ -0,0 +1,501 @@ +/** + * Source map upload with `sentry` commands, for build tools that have no + * Sentry bundler plugin (Angular, tsc, Create React App, …). + * + * Installs the `sentry` CLI package, adds a `sentry:sourcemaps` npm script + * that runs `sentry sourcemap upload` on the build output, optionally + * appends it to the production build script, and + * writes the org, project, self-hosted URL, and auth token to `.sentryclirc`. + * v4 reads that file: `[defaults]` feeds org/project/url resolution and + * `[auth] token` becomes `SENTRY_AUTH_TOKEN`. + * + * Ported from sentry-wizard's `src/sourcemaps/tools/sentry-cli.ts`, which + * installed `@sentry/cli`, ran `sentry-cli sourcemaps …`, and also wrote the + * token to `.sentryclirc`. + */ + +import { existsSync, promises, readFileSync } from "node:fs"; +import path from "node:path"; +import chalk from "chalk"; +import { CLI_VERSION } from "../../../constants.js"; +import { Sentry, traceStep } from "../../telemetry.js"; +import { + abortIfCancelled, + addSentryCliConfig, + artifactsExist, + askToRunBuildOrEnterPathOrProceed, + getPackageDotJson, + getPackageManager, + installPackage, + SENTRY_CLI_RC_FILE, +} from "../../utils/clack/index.js"; +import { clack } from "../../utils/clack/prompts.js"; +import { debug } from "../../utils/debug.js"; +import { hasPackageInstalled } from "../../utils/package-json.js"; +import { NPM } from "../../utils/package-manager.js"; +import type { SourceMapUploadToolConfigurationOptions } from "./types.js"; + +const SENTRY_NPM_SCRIPT_NAME = "sentry:sourcemaps"; + +/** + * The `sentry` package to install: the major this wizard runs on. The + * package manager runs through a shell, so the spec must not hold shell + * metacharacters such as `>`, `<`, `|` or `^`. + */ +export const SENTRY_CLI_PACKAGE_SPEC = `sentry@${CLI_VERSION.split(".")[0]}.x`; + +let addedToBuildCommand = false; + +type configureSentryCLIOptions = SourceMapUploadToolConfigurationOptions & { + defaultArtifactPath?: string | undefined; + /** Passed to the package manager when installing the `sentry` CLI. */ + forceInstall?: boolean | undefined; +}; + +/** + * Set up source map upload with `sentry sourcemap` commands. + * + * @param options - The Sentry project to upload to, and the build output + * path to suggest + * @param configureSourcemapGenerationFlow - Asks the user to turn on source + * map generation in their build tool + * @param skipValidation - Skip `configureSourcemapGenerationFlow`, for flows + * that already turned source maps on + */ +export async function configureSentryCLI( + options: configureSentryCLIOptions, + configureSourcemapGenerationFlow: () => Promise = defaultConfigureSourcemapGenerationFlow, + skipValidation = false, +): Promise { + const packageDotJson = await getPackageDotJson(); + + await installPackage({ + packageName: SENTRY_CLI_PACKAGE_SPEC, + alreadyInstalled: hasPackageInstalled("sentry", packageDotJson), + devDependency: true, + forceInstall: options.forceInstall, + }); + + let validPath = false; + let relativeArtifactPath: string | undefined; + do { + const rawArtifactPath = await abortIfCancelled( + clack.text({ + message: "Where are your build artifacts located?", + placeholder: + relativeArtifactPath ?? + options.defaultArtifactPath ?? + `.${path.sep}out`, + initialValue: + relativeArtifactPath ?? + options.defaultArtifactPath ?? + `.${path.sep}out`, + validate(value) { + if (!value) { + return "Please enter a path."; + } + return undefined; + }, + }), + ); + + if (path.isAbsolute(rawArtifactPath)) { + // The project root itself is "" relative to cwd; the CLI needs ".". + relativeArtifactPath = + path.relative(process.cwd(), rawArtifactPath) || "."; + } else { + relativeArtifactPath = rawArtifactPath; + } + + if (artifactsExist(relativeArtifactPath)) { + validPath = true; + continue; + } + + const runBuildOrEnterPathOrProceed = + await askToRunBuildOrEnterPathOrProceed({ + relativeArtifactPath, + }); + + validPath = runBuildOrEnterPathOrProceed.validPath; + relativeArtifactPath = + runBuildOrEnterPathOrProceed.relativeArtifactPath ?? relativeArtifactPath; + } while (!validPath); + + const relativePosixArtifactPath = relativeArtifactPath + .split(path.sep) + .join(path.posix.sep); + + if (!skipValidation) { + await configureSourcemapGenerationFlow(); + } + + await createAndAddNpmScript(relativePosixArtifactPath); + + if (await askShouldAddToBuildCommand()) { + await traceStep("sentry-cli-add-to-build-cmd", () => + addSentryCommandToBuildCommand(), + ); + } else { + clack.log.info( + `No problem, just make sure to run this script ${chalk.bold( + "after", + )} building your application but ${chalk.bold("before")} deploying!`, + ); + } + + await addUploadTargetToSentryCliRc(options); + await addSentryCliConfig({ authToken: options.authToken }); + + if (options.selfHosted) { + clack.log.info( + `Set ${chalk.cyan(`SENTRY_URL=${options.url}`)} wherever ${chalk.cyan( + SENTRY_NPM_SCRIPT_NAME, + )} runs, such as in CI, so that it uploads to your Sentry instance.`, + ); + } +} + +/** + * Ask the user to run the `sentry:sourcemaps` script in CI, unless the + * wizard already appended it to the build script. + */ +export async function setupNpmScriptInCI(): Promise { + if (addedToBuildCommand) { + // No need to tell users to add it manually to their CI + // if the script is already added to the build command + return; + } + + const addedToCI = await abortIfCancelled( + clack.select({ + message: `Add a step to your CI pipeline that runs the ${chalk.cyan( + SENTRY_NPM_SCRIPT_NAME, + )} script ${chalk.bold("right after")} building your application.`, + options: [ + { label: "I did, continue!", value: true }, + { + label: "I'll do it later...", + value: false, + hint: chalk.yellow( + `You need to run ${chalk.cyan( + SENTRY_NPM_SCRIPT_NAME, + )} after each build for source maps to work properly.`, + ), + }, + ], + initialValue: true, + }), + ); + + Sentry.setTag("added-ci-script", addedToCI); + + if (!addedToCI) { + clack.log.info("Don't forget! :)"); + } +} + +/** + * The `sentry:sourcemaps` script: upload the build output. `sentry sourcemap + * upload` injects missing debug IDs into the files first, so the deployed + * build carries them. It reads the org and project from + * `.sentryclirc` locally. In CI it resolves them from the DSN on sentry.io, + * and from `SENTRY_ORG`, `SENTRY_PROJECT` and `SENTRY_URL` for self-hosted. + */ +export function getSentryCliNpmScript( + relativePosixArtifactPath: string, +): string { + const artifactPath = quoteShellArg(relativePosixArtifactPath); + // The script runs the `sentry` binary of the package installed above, so + // it names `sentry` itself, not the program running the wizard. + // oxlint-disable-next-line sentry-cli/no-hardcoded-sentry-command -- a package.json script, not a hint. + return `sentry sourcemap upload ${artifactPath}`; +} + +/** Characters that make a shell split or expand an unquoted argument. */ +const SHELL_SPECIAL_RE = /[\s"'`$&|;<>()*?[\]{}!#~\\]/; + +/** + * Double-quote `value` for the npm script shell when it has whitespace or + * shell metacharacters, escaping the characters that stay special inside + * double quotes. Plain paths such as `dist` stay as they are. + */ +function quoteShellArg(value: string): string { + if (!SHELL_SPECIAL_RE.test(value)) { + return value; + } + return `"${value.replace(/["\\$`]/g, "\\$&")}"`; +} + +/** An INI section header line, such as `[defaults]`. */ +const INI_SECTION_RE = /^\s*\[([^\]]*)\]\s*$/; + +/** The key of an INI `key = value` line. */ +const INI_KEY_RE = /^\s*([^=;#\s][^=]*?)\s*=/; + +/** + * Set `values` in the `[defaults]` section of `.sentryclirc` contents and + * keep every other line as it is. + * + * Existing keys are updated in every `[defaults]` section, since the last + * one wins when the file is read. Missing keys go into the first + * `[defaults]` section, which is appended when there is none. + * + * @param contents - The current file contents, empty for a new file + * @param values - Lowercase keys and their values, such as `{ org, project }` + */ +export function setSentryCliRcDefaults( + contents: string, + values: Record, +): string { + const lines = contents === "" ? [] : contents.split("\n"); + const missing = new Map(Object.entries(values)); + let firstDefaultsHeader = -1; + let inDefaults = false; + + for (const [index, line] of lines.entries()) { + const section = INI_SECTION_RE.exec(line); + if (section) { + inDefaults = section[1]?.trim().toLowerCase() === "defaults"; + if (inDefaults && firstDefaultsHeader === -1) { + firstDefaultsHeader = index; + } + continue; + } + const key = inDefaults + ? INI_KEY_RE.exec(line)?.[1]?.toLowerCase() + : undefined; + const value = key === undefined ? undefined : values[key]; + if (key !== undefined && value !== undefined) { + lines[index] = `${key}=${value}${line.endsWith("\r") ? "\r" : ""}`; + missing.delete(key); + } + } + + const newLines = [...missing].map(([key, value]) => `${key}=${value}`); + if (newLines.length === 0) { + return lines.join("\n"); + } + if (firstDefaultsHeader !== -1) { + lines.splice(firstDefaultsHeader + 1, 0, ...newLines); + return lines.join("\n"); + } + + const prefix = lines.join("\n"); + let separator = "\n\n"; + if (prefix === "") { + separator = ""; + } else if (prefix.endsWith("\n")) { + separator = "\n"; + } + return `${prefix}${separator}[defaults]\n${newLines.join("\n")}\n`; +} + +/** + * Write the org, project and, for self-hosted Sentry, the URL to the + * project's `.sentryclirc`, so that `sentry sourcemap upload` finds them + * when the script runs locally. + * + * v4 reads a self-hosted `[defaults] url` only once the CLI trusts an + * `[auth] token` from the same file for it. Until that same-file trust fix + * lands, `assertRcUrlTrusted` refuses it and users set `SENTRY_URL`. + */ +export async function addUploadTargetToSentryCliRc( + options: SourceMapUploadToolConfigurationOptions, +): Promise { + const configPath = path.join(process.cwd(), SENTRY_CLI_RC_FILE); + const contents = existsSync(configPath) + ? readFileSync(configPath, "utf8") + : ""; + + try { + await promises.writeFile( + configPath, + setSentryCliRcDefaults(contents, { + org: options.orgSlug, + project: options.projectSlug, + ...(options.selfHosted ? { url: options.url } : {}), + }), + ); + } catch (error) { + // Not fatal, like the auth token write: CI sets SENTRY_ORG and + // SENTRY_PROJECT anyway, and the warning says what to do locally. + debug(error); + clack.log.warning( + `Failed to add the org and project to ${chalk.cyan( + SENTRY_CLI_RC_FILE, + )}. Set ${chalk.cyan("SENTRY_ORG")} and ${chalk.cyan( + "SENTRY_PROJECT", + )} wherever ${chalk.cyan(SENTRY_NPM_SCRIPT_NAME)} runs.`, + ); + return; + } + + clack.log.success( + `Added the org and project to ${chalk.cyan(SENTRY_CLI_RC_FILE)}.`, + ); +} + +async function createAndAddNpmScript( + relativePosixArtifactPath: string, +): Promise { + const sentryCliNpmScript = getSentryCliNpmScript(relativePosixArtifactPath); + + const packageDotJson = await getPackageDotJson(); + + packageDotJson.scripts = packageDotJson.scripts || {}; + packageDotJson.scripts[SENTRY_NPM_SCRIPT_NAME] = sentryCliNpmScript; + + await promises.writeFile( + path.join(process.cwd(), "package.json"), + JSON.stringify(packageDotJson, null, 2), + ); + + clack.log.info( + `Added a ${chalk.cyan(SENTRY_NPM_SCRIPT_NAME)} script to your ${chalk.cyan( + "package.json", + )}.`, + ); +} + +async function askShouldAddToBuildCommand(): Promise { + const shouldAddToBuildCommand = await abortIfCancelled( + clack.select({ + message: `Do you want to automatically run the ${chalk.cyan( + SENTRY_NPM_SCRIPT_NAME, + )} script after each production build?`, + options: [ + { + label: "Yes", + value: true, + hint: "This will modify your prod build command", + }, + { label: "No", value: false }, + ], + initialValue: true, + }), + ); + + Sentry.setTag("modify-build-command", shouldAddToBuildCommand); + + return shouldAddToBuildCommand; +} + +/** + * Add the sentry:sourcemaps command to the prod build command in the package.json + * - Detect the user's build command + * - Append the sentry:sourcemaps command to it + * + * @param packageDotJson The package.json which will be modified. + */ +export async function addSentryCommandToBuildCommand(): Promise { + const packageDotJson = await getPackageDotJson(); + // This usually shouldn't happen because earlier we added the + // SENTRY_NPM_SCRIPT_NAME script but just to be sure + packageDotJson.scripts = packageDotJson.scripts || {}; + + const allNpmScripts = Object.keys(packageDotJson.scripts).filter( + (s) => s !== SENTRY_NPM_SCRIPT_NAME, + ); + + const packageManager = await getPackageManager(NPM); + + // Heuristic to pre-select the build command: + // Often, 'build' is the prod build command, so we favour it. + // If it's not there, commands that include 'build' might be the prod build command. + let buildCommand = + typeof packageDotJson.scripts["build"] === "string" + ? "build" + : allNpmScripts.find((s) => s.toLocaleLowerCase().includes("build")); + + const isProdBuildCommand = + !!buildCommand && + (await abortIfCancelled( + clack.confirm({ + message: `Is ${chalk.cyan( + `${packageManager.runScriptCommand} ${buildCommand}`, + )} your production build command?`, + }), + )); + + if (allNpmScripts.length && (!buildCommand || !isProdBuildCommand)) { + buildCommand = await abortIfCancelled( + clack.select({ + message: `Which ${packageManager.name} command in your ${chalk.cyan( + "package.json", + )} builds your application for production?`, + options: [ + ...allNpmScripts.map((script) => ({ + label: script, + value: script, + })), + { label: "None of the above", value: "none" }, + ], + }), + ); + } + + if (!buildCommand || buildCommand === "none") { + clack.log.warn( + `We can only add the ${chalk.cyan( + SENTRY_NPM_SCRIPT_NAME, + )} script to another \`script\` in your ${chalk.cyan("package.json")}. +Please add it manually to your prod build command.`, + ); + return; + } + + const oldCommand = packageDotJson.scripts[buildCommand]; + if (!oldCommand) { + // very unlikely to happen but nevertheless + clack.log.warn( + `\`${buildCommand}\` doesn't seem to be part of your package.json scripts`, + ); + return; + } + + const newCommand = `${oldCommand} && ${packageManager.runScriptCommand} ${SENTRY_NPM_SCRIPT_NAME}`; + + if (oldCommand.endsWith(SENTRY_NPM_SCRIPT_NAME)) { + clack.log.info( + `It seems like ${chalk.cyan( + SENTRY_NPM_SCRIPT_NAME, + )} is already part of your ${chalk.cyan( + buildCommand, + )} command. Will not add it again. +Current command: ${chalk.dim(oldCommand)} +Would have injected: ${chalk.dim(newCommand)}`, + ); + + // The build already runs the script, so CI needs no separate step. + addedToBuildCommand = true; + return; + } + + packageDotJson.scripts[buildCommand] = newCommand; + + await promises.writeFile( + path.join(process.cwd(), "package.json"), + JSON.stringify(packageDotJson, null, 2), + ); + + addedToBuildCommand = true; + + clack.log.info( + `Added ${chalk.cyan(SENTRY_NPM_SCRIPT_NAME)} script to your ${chalk.cyan( + buildCommand, + )} command.`, + ); +} + +async function defaultConfigureSourcemapGenerationFlow(): Promise { + await abortIfCancelled( + clack.select({ + message: `Verify that your build tool is generating source maps. ${chalk.dim( + "(Your build output folder should contain .js.map files after a build)", + )}`, + options: [{ label: "I checked. Continue!", value: true }], + initialValue: true, + }), + ); +} diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/tsc.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/tsc.ts new file mode 100644 index 000000000..7633b3b11 --- /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 { + getOrSetObjectProperty, + parseJsonC, + printJsonC, + setOrUpdateObjectProperty, +} from "../../utils/ast-utils.js"; +import { findFile } from "../../../dsn/fs-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 = + (await 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 000000000..a36ff55e9 --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/types.ts @@ -0,0 +1,15 @@ +/** + * Options the source map upload tool setups take. + */ + +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 000000000..3b2f4350b --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/vite.ts @@ -0,0 +1,289 @@ +/** + * 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 { + getObjectProperty, + hasSentryContent, + preserveTrailingNewline, +} from "../../utils/ast-utils.js"; +import { findFile } from "../../../dsn/fs-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 = + (await 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 = getObjectProperty(configObj, "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.value.type !== "ObjectExpression") { + return false; + } + + const buildObj = buildProp.value; + const sourceMapsProp = getObjectProperty(buildObj, "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; + } + + // 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; +} + +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 000000000..2d8706e88 --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/webpack.ts @@ -0,0 +1,383 @@ +/** + * 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 } from "../../../dsn/fs-utils.js"; +import { 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 = + (await 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://webpack.js.org/configuration/", + ); + 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 000000000..b4a10efb9 --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/wrangler.ts @@ -0,0 +1,501 @@ +/** + * 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, which read the org and + * project from `.sentryclirc`. + */ + +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 { addUploadTargetToSentryCliRc } 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@^4", + alreadyInstalled: hasPackageInstalled("sentry", await getPackageDotJson()), + devDependency: true, + }); + + if (!(await askContinueIfHasSentrySourcemapsScript())) { + await abort("Exiting the wizard.", 0); + return; + } + + const deployCommand = await getDeployCommand(); + if (!deployCommand) { + return; + } + + const outDir = await getWranglerOutDir(deployCommand); + + await createAndAddSentrySourcemapsScript(outDir); + + await writePostDeployCommand(deployCommand); + + await modifyDeployCommand(deployCommand, outDir); + + await addUploadTargetToSentryCliRc(options); + await addSentryCliConfig({ authToken: options.authToken }); + + if (options.selfHosted) { + clack.log.info( + `Set ${chalk.cyan(`SENTRY_URL=${options.url}`)} wherever ${chalk.cyan( + SENTRY_NPM_SCRIPT_NAME, + )} runs, such as in CI, so that it uploads to your Sentry instance.`, + ); + } +} + +async function createAndAddSentrySourcemapsScript( + outDir: string, +): Promise { + const pkgJson = await getPackageDotJson(); + pkgJson.scripts = pkgJson.scripts ?? {}; + pkgJson.scripts[SENTRY_NPM_SCRIPT_NAME] = getSentryCliCommand(outDir); + + 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. 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(outDir: string): string { + return [ + `_SENTRY_RELEASE=${PROPOSE_VERSION}`, + // 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(" && "); +} + +// 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()) + .filter(Boolean); + + 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 000000000..14d8ae73d --- /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 000000000..79acf9925 --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/utils/detect-tool.ts @@ -0,0 +1,59 @@ +/** + * 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", + "react-scripts": "create-react-app", + "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 000000000..9cc77bcc9 --- /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, 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 000000000..84ecbda36 --- /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/vendor/is-unicorn-supported.ts b/packages/cli/src/lib/wizard/utils/vendor/is-unicorn-supported.ts new file mode 100644 index 000000000..311dfbcba --- /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 000000000..e686701af --- /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 000000000..1db8c1397 --- /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/cloudflare-wizard.test.ts b/packages/cli/test/lib/wizard/cloudflare/cloudflare-wizard.test.ts new file mode 100644 index 000000000..755595f07 --- /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/create-wrangler-config.test.ts b/packages/cli/test/lib/wizard/cloudflare/create-wrangler-config.test.ts new file mode 100644 index 000000000..5fc68d762 --- /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 000000000..d34239ed1 --- /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 000000000..db72ad3af --- /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 000000000..7f298ade7 --- /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 000000000..a8854ce16 --- /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 000000000..e4e0f2bc4 --- /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 000000000..ca1697964 --- /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 000000000..01d21af42 --- /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 000000000..ae35cc569 --- /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 000000000..bf2c62061 --- /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 000000000..3eb7287e2 --- /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 000000000..822a73bd1 --- /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 000000000..3e5556174 --- /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 000000000..50e102247 --- /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 000000000..d0d8416d4 --- /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 000000000..7a73a41bf --- /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 000000000..7904d2256 --- /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 000000000..fb605c823 --- /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 000000000..322404fbd --- /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 000000000..6c0d3ecd1 --- /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 000000000..ecbd21b0e --- /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 000000000..22164f422 --- /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 000000000..25b343eb0 --- /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 000000000..b5fdbac47 --- /dev/null +++ b/packages/cli/test/lib/wizard/cloudflare/get-entry-point-from-wrangler-config.test.ts @@ -0,0 +1,103 @@ +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("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"), + 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 000000000..4417368ce --- /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 000000000..0e833890a --- /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 000000000..463dba558 --- /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 000000000..68530bbb1 --- /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/ci-setup.test.ts b/packages/cli/test/lib/wizard/sourcemaps/ci-setup.test.ts new file mode 100644 index 000000000..fb2c7a984 --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/ci-setup.test.ts @@ -0,0 +1,88 @@ +/** + * `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" }; + +const selfHostedTarget = { + ...uploadTarget, + url: "https://sentry.example.com/", +}; + +describe("setupCI", () => { + 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).not.toContain("SENTRY_ORG"); + expect(stdout).not.toContain("SENTRY_PROJECT"); + expect(stdout).not.toContain("SENTRY_URL"); + }); + + 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/"); + }); + + 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", selfHostedTarget); + + expect(clackMocks.select).toHaveBeenCalledTimes(3); + expect(stdout).toContain("SENTRY_ORG=my-org"); + }); + + 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 new file mode 100644 index 000000000..f82fdaa1b --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/ci.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from "vitest"; + +import { getCIEnvVars } from "../../../../src/lib/wizard/sourcemaps/ci.js"; + +describe("getCIEnvVars", () => { + it("lists only the auth token without an upload target", () => { + expect(getCIEnvVars("tok", undefined)).toEqual(["SENTRY_AUTH_TOKEN=tok"]); + }); + + it("lists only the auth token for sentry.io", () => { + expect( + getCIEnvVars("tok", { org: "my-org", project: "my-project" }), + ).toEqual(["SENTRY_AUTH_TOKEN=tok"]); + }); + + it("adds the org, project and 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/angular.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/angular.test.ts new file mode 100644 index 000000000..082add11d --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/angular.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it, vi } from "vitest"; + +import { configureAngularSourcemapGenerationFlow } from "../../../../../src/lib/wizard/sourcemaps/tools/angular.js"; +import { clack } from "../../../../../src/lib/wizard/utils/clack/prompts.js"; + +describe("configureAngularSourcemapGenerationFlow", () => { + it("shows sourceMap under the production configuration, like the automatic angular.json edit", async () => { + vi.spyOn(clack.log, "info").mockImplementation(() => {}); + vi.spyOn(clack, "select").mockResolvedValue(true); + const rawOutput = vi.spyOn(clack, "rawOutput").mockImplementation(() => {}); + + await configureAngularSourcemapGenerationFlow(); + + const snippet = rawOutput.mock.calls.map(([value]) => value).join("\n"); + expect(snippet).toMatch( + /"configurations": \{\s*"production": \{[\s\S]*"sourceMap": true/, + ); + expect(snippet).not.toContain('"options"'); + }); +}); diff --git a/packages/cli/test/lib/wizard/sourcemaps/tools/create-react-app.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/create-react-app.test.ts new file mode 100644 index 000000000..c5d08728f --- /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/sentry-cli.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/sentry-cli.test.ts new file mode 100644 index 000000000..556857727 --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/sentry-cli.test.ts @@ -0,0 +1,309 @@ +import { mkdtempSync, promises, realpathSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { + addSentryCommandToBuildCommand, + configureSentryCLI, + getSentryCliNpmScript, + SENTRY_CLI_PACKAGE_SPEC, + setSentryCliRcDefaults, +} from "../../../../../src/lib/wizard/sourcemaps/tools/sentry-cli.js"; +import { CLI_VERSION } from "../../../../../src/lib/constants.js"; + +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as packageManagerHelpers from "../../../../../src/lib/wizard/utils/package-manager.js"; +import { + getPackageDotJson, + installPackage, +} from "../../../../../src/lib/wizard/utils/clack/index.js"; + +import { vi, it, describe, expect, afterEach } from "vitest"; + +const { selectMock, textMock } = vi.hoisted(() => ({ + selectMock: vi.fn().mockResolvedValue(true), + textMock: vi.fn(), +})); + +const writeFileSpy = vi + .spyOn(promises, "writeFile") + .mockImplementation(() => Promise.resolve()); + +vi.mock("@clack/prompts", () => { + return { + log: { + info: vi.fn(), + success: vi.fn(), + }, + confirm: vi.fn().mockResolvedValue(true), + select: selectMock, + text: textMock, + isCancel: vi.fn().mockReturnValue(false), + }; +}); +vi.mock("../../../../../src/lib/wizard/utils/clack/index.js", async () => ({ + ...(await vi.importActual( + "../../../../../src/lib/wizard/utils/clack/index.js", + )), + installPackage: vi.fn().mockResolvedValue(undefined), + addSentryCliConfig: vi.fn().mockResolvedValue(undefined), + getPackageDotJson: vi.fn().mockResolvedValue({ + scripts: { + build: "tsc", + }, + version: "1.0.0", + }), +})); + +describe("addSentryCommandToBuildCommand", () => { + afterEach(() => { + vi.clearAllMocks(); + }); + it.each([ + [ + packageManagerHelpers.NPM, + packageManagerHelpers.PNPM, + packageManagerHelpers.YARN_V1, + packageManagerHelpers.YARN_V2, + packageManagerHelpers.BUN, + packageManagerHelpers.DENO, + ], + ])("adds the cli command to the script command (%s)", async (_, pacMan) => { + vi.spyOn(packageManagerHelpers, "_detectPackageManger").mockReturnValue( + pacMan, + ); + await addSentryCommandToBuildCommand(); + expect(writeFileSpy).toHaveBeenCalledWith( + expect.stringContaining("package.json"), + expect.stringContaining( + `tsc && ${pacMan.runScriptCommand} sentry:sourcemaps`, + ), + ); + }); + + it("does not add the cli command to the script command if it is already in there", async () => { + vi.mocked(getPackageDotJson).mockResolvedValue({ + scripts: { + build: "tsc && sentry:sourcemaps", + }, + version: "1.0.0", + }); + + await addSentryCommandToBuildCommand(); + + expect(writeFileSpy).not.toHaveBeenCalled(); + }); + + it("does not ask for a CI step when the build command already runs the script", async () => { + // A fresh module, so `addedToBuildCommand` starts out false + vi.resetModules(); + const { getPackageDotJson: freshGetPackageDotJson } = + await import("../../../../../src/lib/wizard/utils/clack/index.js"); + vi.mocked(freshGetPackageDotJson).mockResolvedValue({ + scripts: { + build: "tsc && sentry:sourcemaps", + }, + version: "1.0.0", + }); + const sentryCli = + await import("../../../../../src/lib/wizard/sourcemaps/tools/sentry-cli.js"); + + await sentryCli.addSentryCommandToBuildCommand(); + await sentryCli.setupNpmScriptInCI(); + + expect(selectMock).not.toHaveBeenCalled(); + }); +}); + +describe("getSentryCliNpmScript", () => { + it("uploads with the v4 sentry command, without org or project flags", () => { + expect(getSentryCliNpmScript("./dist")).toBe( + "sentry sourcemap upload ./dist", + ); + }); + + it.each(["dist", ".", "./build/client"])( + "leaves the plain path %s unquoted", + (artifactPath) => { + expect(getSentryCliNpmScript(artifactPath)).toBe( + `sentry sourcemap upload ${artifactPath}`, + ); + }, + ); + + it.each([ + ["dist/my app", '"dist/my app"'], + ["out/(client)", '"out/(client)"'], + ['dist/a"b', '"dist/a\\"b"'], + ["dist/$HOME", '"dist/\\$HOME"'], + ])("double-quotes %s as %s", (artifactPath, quoted) => { + expect(getSentryCliNpmScript(artifactPath)).toBe( + `sentry sourcemap upload ${quoted}`, + ); + }); +}); + +describe("configureSentryCLI", () => { + it("uses . for an absolute artifact path that is the project root", async () => { + const dir = realpathSync(mkdtempSync(path.join(tmpdir(), "sentry-cli-"))); + const originalCwd = process.cwd(); + try { + process.chdir(dir); + textMock.mockResolvedValueOnce(dir); + // Don't append the script to the build command. + selectMock.mockResolvedValueOnce(false); + vi.mocked(getPackageDotJson).mockResolvedValue({ + scripts: { build: "tsc" }, + version: "1.0.0", + }); + + await configureSentryCLI( + { + orgSlug: "my-org", + projectSlug: "my-project", + selfHosted: false, + url: "https://sentry.io/", + authToken: "token", + }, + () => Promise.resolve(), + true, + ); + + expect(writeFileSpy).toHaveBeenCalledWith( + expect.stringContaining("package.json"), + expect.stringContaining( + '"sentry:sourcemaps": "sentry sourcemap upload ."', + ), + ); + } finally { + process.chdir(originalCwd); + rmSync(dir, { recursive: true, force: true }); + } + }); +}); + +describe("configureSentryCLI forceInstall", () => { + it.each([true, false])( + "passes forceInstall=%s to the sentry CLI install", + async (forceInstall) => { + const dir = realpathSync( + mkdtempSync(path.join(tmpdir(), "sentry-cli-force-")), + ); + const originalCwd = process.cwd(); + try { + process.chdir(dir); + textMock.mockResolvedValueOnce(dir); + selectMock.mockResolvedValueOnce(false); + vi.mocked(getPackageDotJson).mockResolvedValue({ + scripts: { build: "tsc" }, + version: "1.0.0", + }); + + await configureSentryCLI( + { + orgSlug: "my-org", + projectSlug: "my-project", + selfHosted: false, + url: "https://sentry.io/", + authToken: "token", + forceInstall, + }, + () => Promise.resolve(), + true, + ); + + expect(installPackage).toHaveBeenLastCalledWith( + expect.objectContaining({ + packageName: SENTRY_CLI_PACKAGE_SPEC, + forceInstall, + }), + ); + } finally { + process.chdir(originalCwd); + rmSync(dir, { recursive: true, force: true }); + } + }, + ); +}); + +describe("SENTRY_CLI_PACKAGE_SPEC", () => { + it("installs the CLI major the wizard runs on", () => { + expect(SENTRY_CLI_PACKAGE_SPEC).toBe( + `sentry@${CLI_VERSION.split(".")[0]}.x`, + ); + expect(SENTRY_CLI_PACKAGE_SPEC).toMatch(/^sentry@\d+\.x$/); + }); + + it("has no shell metacharacters", () => { + expect(SENTRY_CLI_PACKAGE_SPEC).not.toMatch(/[<>|&;^$`'" ]/); + }); +}); + +describe("setSentryCliRcDefaults", () => { + const values = { org: "my-org", project: "my-project" }; + + it("creates a [defaults] section in an empty file", () => { + expect(setSentryCliRcDefaults("", values)).toBe( + "[defaults]\norg=my-org\nproject=my-project\n", + ); + }); + + it("appends [defaults] after other sections and keeps them", () => { + expect(setSentryCliRcDefaults("[auth]\ntoken=abc\n", values)).toBe( + "[auth]\ntoken=abc\n\n[defaults]\norg=my-org\nproject=my-project\n", + ); + expect(setSentryCliRcDefaults("[auth]\ntoken=abc", values)).toBe( + "[auth]\ntoken=abc\n\n[defaults]\norg=my-org\nproject=my-project\n", + ); + }); + + it("updates existing keys and keeps other keys, comments, and sections", () => { + const contents = [ + "; managed by hand", + "[defaults]", + "url = https://sentry.example.com/", + "org = old-org", + "", + "[auth]", + "token=abc", + "", + ].join("\n"); + + expect(setSentryCliRcDefaults(contents, values)).toBe( + [ + "; managed by hand", + "[defaults]", + "project=my-project", + "url = https://sentry.example.com/", + "org=my-org", + "", + "[auth]", + "token=abc", + "", + ].join("\n"), + ); + }); + + it("does not touch org or project keys outside [defaults]", () => { + expect( + setSentryCliRcDefaults("[other]\norg=keep\n[DEFAULTS]\n", values), + ).toBe("[other]\norg=keep\n[DEFAULTS]\norg=my-org\nproject=my-project\n"); + }); + + it("updates keys in every [defaults] section", () => { + expect( + setSentryCliRcDefaults( + "[defaults]\norg=a\n[auth]\ntoken=t\n[defaults]\nproject=b\n", + values, + ), + ).toBe( + "[defaults]\norg=my-org\n[auth]\ntoken=t\n[defaults]\nproject=my-project\n", + ); + }); + + it("keeps CRLF line endings on updated lines", () => { + expect( + setSentryCliRcDefaults("[defaults]\r\norg=a\r\nproject=b\r\n", values), + ).toBe("[defaults]\r\norg=my-org\r\nproject=my-project\r\n"); + }); +}); diff --git a/packages/cli/test/lib/wizard/sourcemaps/tools/sentryclirc-defaults.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/sentryclirc-defaults.test.ts new file mode 100644 index 000000000..bccc0d060 --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/sentryclirc-defaults.test.ts @@ -0,0 +1,107 @@ +/** + * `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. + */ + +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { + clearSentryCliRcCache, + loadSentryCliRc, +} from "../../../../../src/lib/sentryclirc.js"; +import { addUploadTargetToSentryCliRc } from "../../../../../src/lib/wizard/sourcemaps/tools/sentry-cli.js"; +import { addSentryCliConfig } from "../../../../../src/lib/wizard/utils/clack/index.js"; + +vi.mock("@clack/prompts", () => ({ + log: { + info: vi.fn(), + success: vi.fn(), + warn: vi.fn(), + warning: vi.fn(), + error: vi.fn(), + }, +})); + +let projectDir: string; +let configDir: string; +let originalCwd: string; +let originalConfigDir: string | undefined; + +beforeEach(() => { + originalCwd = process.cwd(); + originalConfigDir = process.env["SENTRY_CONFIG_DIR"]; + projectDir = mkdtempSync(path.join(tmpdir(), "wizard-rc-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("addUploadTargetToSentryCliRc", () => { + it("writes the org and project, but no url, for sentry.io", async () => { + await addUploadTargetToSentryCliRc(saasOptions); + + expect(readFileSync(rcPath(), "utf8")).toBe( + "[defaults]\norg=my-org\nproject=my-project\n", + ); + }); + + it("writes the url for self-hosted Sentry", async () => { + await addUploadTargetToSentryCliRc({ + ...saasOptions, + selfHosted: true, + url: "https://sentry.example.com/", + }); + + expect(readFileSync(rcPath(), "utf8")).toBe( + "[defaults]\norg=my-org\nproject=my-project\nurl=https://sentry.example.com/\n", + ); + }); + + 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 addUploadTargetToSentryCliRc(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 000000000..9411b2ed3 --- /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/tsc.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/tsc.test.ts new file mode 100644 index 000000000..76b35a23c --- /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 000000000..d823ea38c --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/vite.test.ts @@ -0,0 +1,193 @@ +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); + }, + ); + + 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 000000000..9370b1ec2 --- /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/webpack.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/webpack.test.ts new file mode 100644 index 000000000..b61d8108d --- /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-flow.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/wrangler-flow.test.ts new file mode 100644 index 000000000..0a749e294 --- /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 new file mode 100644 index 000000000..a0824dc86 --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/wrangler.test.ts @@ -0,0 +1,267 @@ +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); + + expect(runSentryCliCommand(getSentryCliCommand(outDir))).toEqual([ + "release", + "create", + "release with spaces", + "sourcemap", + "upload", + "--release=release with spaces", + "--no-rewrite", + outDir, + ]); + }); + + it("preserves quotes and shell syntax in paths", () => { + const outDir = "worker's dist;$(printf${IFS}INJECTED)"; + + expect(runSentryCliCommand(getSentryCliCommand(outDir))).toEqual([ + "release", + "create", + "release with spaces", + "sourcemap", + "upload", + "--release=release with spaces", + "--no-rewrite", + outDir, + ]); + }); + + 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\'', + ); + }); +}); + +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 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"'); + + 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') printf '%s\\n' "$@" ;; + esac +} +${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 000000000..ff9103a04 --- /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/detect-tool.test.ts b/packages/cli/test/lib/wizard/sourcemaps/utils/detect-tool.test.ts new file mode 100644 index 000000000..07f114a19 --- /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"); + }); +}); 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 000000000..b8aec8ebd --- /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"), + ); + }, + ); +});