diff --git a/.oxfmtrc.json b/.oxfmtrc.json index 9e34e9201..f7a7fe81d 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -14,6 +14,7 @@ "packages/mcp-server-mocks/src/fixtures/**", "packages/mcp-core/src/ui/chart-app.generated.ts", "packages/codemod-cli3to4/tests/**", + "packages/cli/test/lib/wizard/**/fixtures/**", "packages/cli/test/wizard-e2e/test-applications/**", "**/worker-configuration.d.ts", "**/tsconfig*.json" diff --git a/.oxlintrc.json b/.oxlintrc.json index a03f0b98e..152a664fb 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -15,6 +15,7 @@ "packages/mcp-server-mocks/src/fixtures/**", "packages/mcp-core/src/ui/chart-app.generated.ts", "packages/codemod-cli3to4/tests/**", + "packages/cli/test/lib/wizard/**/fixtures/**", "packages/cli/test/wizard-e2e/test-applications/**" ], "rules": { diff --git a/packages/cli/src/lib/wizard/react-router/codemods/client.entry.ts b/packages/cli/src/lib/wizard/react-router/codemods/client.entry.ts new file mode 100644 index 000000000..30d57487a --- /dev/null +++ b/packages/cli/src/lib/wizard/react-router/codemods/client.entry.ts @@ -0,0 +1,214 @@ +/** + * Adds `Sentry.init` and the HydratedRouter error handler to a React Router + * app's `entry.client` file. + */ + +import recast from "recast"; +import type { namedTypes as t } from "ast-types"; +import type { ExpressionKind } from "ast-types/lib/gen/kinds"; + +import { clack } from "../../utils/clack/prompts.js"; +import chalk from "chalk"; + +import { loadFile, writeFile } from "magicast"; +import { hasSentryContent } from "../../utils/ast-utils.js"; +import { getDataCollectionBlock } from "../templates.js"; +import { getAfterImportsInsertionIndex } from "./utils.js"; + +// oxlint-disable-next-line max-params -- positional like the sentry-wizard original and its tests +export async function instrumentClientEntry( + clientEntryPath: string, + dsn: string, + enableTracing: boolean, + enableReplay: boolean, + reduceDataCollection: boolean, + useInstrumentationAPI = false, + useOnError = false, +): Promise { + const clientEntryAst = await loadFile(clientEntryPath); + + const alreadyHasSentry = hasSentryContent(clientEntryAst.$ast as t.Program); + + if (!alreadyHasSentry) { + clientEntryAst.imports.$add({ + from: "@sentry/react-router", + imported: "*", + local: "Sentry", + }); + + let initContent: string; + + if (useInstrumentationAPI && enableTracing) { + const integrations = ["tracing"]; + if (enableReplay) { + integrations.push("Sentry.replayIntegration()"); + } + + initContent = ` +const tracing = Sentry.reactRouterTracingIntegration(); + +Sentry.init({ + dsn: "${dsn}", +${getDataCollectionBlock(reduceDataCollection)} + integrations: [${integrations.join(", ")}], + tracesSampleRate: 1.0, + tracePropagationTargets: [/^\\//, /^https:\\/\\/yourserver\\.io\\/api/],${ + enableReplay + ? "\n replaysSessionSampleRate: 0.1,\n replaysOnErrorSampleRate: 1.0," + : "" + } +});`; + } else { + const integrations = []; + if (enableTracing) { + integrations.push("Sentry.reactRouterTracingIntegration()"); + } + if (enableReplay) { + integrations.push("Sentry.replayIntegration()"); + } + + initContent = ` +Sentry.init({ + dsn: "${dsn}", +${getDataCollectionBlock(reduceDataCollection)} + integrations: [${integrations.join(", ")}], + tracesSampleRate: ${enableTracing ? "1.0" : "0"},${ + enableTracing + ? "\n tracePropagationTargets: [/^\\//, /^https:\\/\\/yourserver\\.io\\/api/]," + : "" + }${ + enableReplay + ? "\n replaysSessionSampleRate: 0.1,\n replaysOnErrorSampleRate: 1.0," + : "" + } +});`; + } + + (clientEntryAst.$ast as t.Program).body.splice( + getAfterImportsInsertionIndex(clientEntryAst.$ast as t.Program), + 0, + ...recast.parse(initContent).program.body, + ); + } + + const useInstrAPI = useInstrumentationAPI && enableTracing; + const addInstrProp = useInstrAPI && !alreadyHasSentry; + + if (addInstrProp) { + addInstrumentationPropsToHydratedRouter(clientEntryAst.$ast as t.Program); + } + + if (useOnError) { + addOnErrorToHydratedRouter(clientEntryAst.$ast as t.Program); + } + + // Emit a single warning if HydratedRouter wasn't found for any prop we tried to add + if ( + (addInstrProp || useOnError) && + !hasHydratedRouter(clientEntryAst.$ast as t.Program) + ) { + const props: string[] = []; + if (useOnError) { + props.push("onError={Sentry.sentryOnError}"); + } + if (addInstrProp) { + props.push("instrumentations={[tracing.clientInstrumentation]}"); + } + clack.log.warn( + `Could not find ${chalk.cyan( + "HydratedRouter", + )} component in your client entry file.\n` + + `Manually add the following props:\n` + + ` ${chalk.green(``)}`, + ); + } + + await writeFile(clientEntryAst.$ast, clientEntryPath); +} + +function hasHydratedRouter(ast: t.Program): boolean { + let found = false; + recast.visit(ast, { + visitJSXElement(path) { + const name = path.node.openingElement.name; + if (name.type === "JSXIdentifier" && name.name === "HydratedRouter") { + found = true; + return false; + } + this.traverse(path); + return undefined; + }, + }); + return found; +} + +function addPropToHydratedRouter( + ast: t.Program, + propName: string, + propValue: ExpressionKind, +): boolean { + let found = false; + + recast.visit(ast, { + visitJSXElement(path) { + const openingElement = path.node.openingElement; + + if ( + openingElement.name.type === "JSXIdentifier" && + openingElement.name.name === "HydratedRouter" + ) { + found = true; + + const hasProp = openingElement.attributes?.some( + (attr) => + attr.type === "JSXAttribute" && + attr.name.type === "JSXIdentifier" && + attr.name.name === propName, + ); + + if (!hasProp) { + const prop = recast.types.builders.jsxAttribute( + recast.types.builders.jsxIdentifier(propName), + recast.types.builders.jsxExpressionContainer(propValue), + ); + + if (!openingElement.attributes) { + openingElement.attributes = []; + } + openingElement.attributes.push(prop); + } + + return false; + } + + this.traverse(path); + return undefined; + }, + }); + + return found; +} + +function addOnErrorToHydratedRouter(ast: t.Program): boolean { + return addPropToHydratedRouter( + ast, + "onError", + recast.types.builders.memberExpression( + recast.types.builders.identifier("Sentry"), + recast.types.builders.identifier("sentryOnError"), + ), + ); +} + +function addInstrumentationPropsToHydratedRouter(ast: t.Program): boolean { + return addPropToHydratedRouter( + ast, + "instrumentations", + recast.types.builders.arrayExpression([ + recast.types.builders.memberExpression( + recast.types.builders.identifier("tracing"), + recast.types.builders.identifier("clientInstrumentation"), + ), + ]), + ); +} diff --git a/packages/cli/src/lib/wizard/react-router/codemods/react-router-config.ts b/packages/cli/src/lib/wizard/react-router/codemods/react-router-config.ts new file mode 100644 index 000000000..7a923b180 --- /dev/null +++ b/packages/cli/src/lib/wizard/react-router/codemods/react-router-config.ts @@ -0,0 +1,254 @@ +/** + * Edits `react-router.config.(js|ts)`: turns on SSR and adds the + * `sentryOnBuildEnd` hook that uploads source maps after a build. + */ + +import type { namedTypes as t } from "ast-types"; +import recast from "recast"; +import path from "node:path"; +import { existsSync, promises } from "node:fs"; + +import { parseModule, generateCode } from "magicast"; + +import { clack } from "../../utils/clack/prompts.js"; +import chalk from "chalk"; + +import { preserveTrailingNewline } from "../../utils/ast-utils.js"; +import { getSentryReactRouterVitePluginImportPath } from "../sdk-version.js"; + +/** + * Extracts the ObjectExpression from various export patterns. + * Supports: direct object, `satisfies Config`, and `as Config` patterns. + */ +function extractConfigObject( + declaration: t.Declaration | t.Expression, +): t.ObjectExpression | undefined { + if (declaration.type === "ObjectExpression") { + return declaration as t.ObjectExpression; + } + + if ( + declaration.type === "TSSatisfiesExpression" || + declaration.type === "TSAsExpression" + ) { + const expr = (declaration as t.TSSatisfiesExpression | t.TSAsExpression) + .expression; + return expr.type === "ObjectExpression" ? expr : undefined; + } + + return undefined; +} + +/** + * Creates an identifier property for object literals. + */ +function createIdentifierProperty(name: string): t.Property { + const b = recast.types.builders; + return b.property("init", b.identifier(name), b.identifier(name)); +} + +export function addSentryBuildEndToReactRouterConfig(program: t.Program): { + success: boolean; + ssrWasChanged: boolean; +} { + const b = recast.types.builders; + let ssrWasChanged = false; + + const defaultExport = program.body.find( + (node): node is t.ExportDefaultDeclaration => + node.type === "ExportDefaultDeclaration", + ); + + if (!defaultExport) { + return { success: false, ssrWasChanged: false }; + } + + const configObj = extractConfigObject(defaultExport.declaration); + + if (!configObj) { + return { success: false, ssrWasChanged: false }; + } + + if (findConfigProperty(configObj, "buildEnd")) { + throw new Error( + "A buildEnd hook already exists in your React Router config.", + ); + } + + const ssrProp = findConfigProperty(configObj, "ssr"); + + if (!ssrProp) { + const ssrProperty = b.objectProperty( + b.identifier("ssr"), + b.booleanLiteral(true), + ); + ssrProperty.comments = [ + b.commentLine( + " SSR is required for Sentry sourcemap uploads to work correctly", + true, + false, + ), + ]; + configObj.properties.unshift(ssrProperty); + ssrWasChanged = true; + } else if ( + ssrProp.type === "ObjectProperty" && + (ssrProp.value.type === "BooleanLiteral" || + ssrProp.value.type === "Literal") + ) { + const wasExplicitlyFalse = ssrProp.value.value === false; + + if (wasExplicitlyFalse) { + ssrWasChanged = true; + } + + ssrProp.value = b.booleanLiteral(true); + + if (wasExplicitlyFalse) { + ssrProp.comments = [ + b.commentLine( + " Changed to true - SSR is required for Sentry sourcemap uploads", + true, + false, + ), + ]; + } + } + + const paramNames = ["viteConfig", "reactRouterConfig", "buildManifest"]; + + const buildEndFunction = b.arrowFunctionExpression( + [b.objectPattern(paramNames.map(createIdentifierProperty))], + b.blockStatement([ + b.expressionStatement( + b.awaitExpression( + b.callExpression(b.identifier("sentryOnBuildEnd"), [ + b.objectExpression(paramNames.map(createIdentifierProperty)), + ]), + ), + ), + ]), + ); + buildEndFunction.async = true; + + configObj.properties.push( + b.objectProperty(b.identifier("buildEnd"), buildEndFunction), + ); + + return { success: true, ssrWasChanged }; +} + +export function hasReactRouterSentryContent(program: t.Program): boolean { + let hasSentry = false; + + recast.visit(program, { + visitIdentifier(path) { + if (path.node.name === "sentryOnBuildEnd") { + hasSentry = true; + return false; // stop traversal + } + this.traverse(path); + return undefined; + }, + }); + + return hasSentry; +} + +/** + * The project's React Router config filename. Prefers an existing config with + * either extension, so a `.js` config in a TypeScript project is updated + * instead of shadowed by a new `.ts` file. + */ +export function getReactRouterConfigFilename(isTS: boolean): string { + const preferred = `react-router.config.${isTS ? "ts" : "js"}`; + const other = `react-router.config.${isTS ? "js" : "ts"}`; + return ( + [preferred, other].find((candidate) => + existsSync(path.join(process.cwd(), candidate)), + ) ?? preferred + ); +} + +export async function instrumentReactRouterConfig( + isTS: boolean, + vitePluginImportPath: string = getSentryReactRouterVitePluginImportPath( + undefined, + ), +): Promise<{ ssrWasChanged: boolean }> { + const configFilename = getReactRouterConfigFilename(isTS); + const configPath = path.join(process.cwd(), configFilename); + + if (!existsSync(configPath)) { + const defaultConfig = isTS + ? `import type { Config } from "@react-router/dev/config"; +import { sentryOnBuildEnd } from "${vitePluginImportPath}"; + +export default { + ssr: true, + buildEnd: async ({ viteConfig, reactRouterConfig, buildManifest }) => { + await sentryOnBuildEnd({ viteConfig, reactRouterConfig, buildManifest }); + }, +} satisfies Config; +` + : `import { sentryOnBuildEnd } from "${vitePluginImportPath}"; + +export default { + ssr: true, + buildEnd: async ({ viteConfig, reactRouterConfig, buildManifest }) => { + await sentryOnBuildEnd({ viteConfig, reactRouterConfig, buildManifest }); + }, +}; +`; + await promises.writeFile(configPath, defaultConfig); + return { ssrWasChanged: false }; + } + + const configContent = await promises.readFile(configPath, "utf-8"); + const filename = chalk.cyan(configFilename); + + const mod = parseModule(configContent); + + if (hasReactRouterSentryContent(mod.$ast as t.Program)) { + clack.log.info(`${filename} already contains sentryOnBuildEnd.`); + return { ssrWasChanged: false }; + } + + mod.imports.$add({ + from: vitePluginImportPath, + imported: "sentryOnBuildEnd", + local: "sentryOnBuildEnd", + }); + + const { success, ssrWasChanged } = addSentryBuildEndToReactRouterConfig( + mod.$ast as t.Program, + ); + + if (!success) { + throw new Error("Failed to modify React Router config structure"); + } + + const code = preserveTrailingNewline( + configContent, + generateCode(mod.$ast).code, + ); + await promises.writeFile(configPath, code); + + return { ssrWasChanged }; +} + +/** + * A config key, whether written `key`, `"key"` or as a method (`key() {}`), so + * an existing entry is updated or detected instead of shadowed by a new one. + */ +function findConfigProperty( + configObj: t.ObjectExpression, + name: string, +): t.ObjectProperty | t.ObjectMethod | undefined { + return configObj.properties.find( + (p): p is t.ObjectProperty | t.ObjectMethod => + (p.type === "ObjectProperty" || p.type === "ObjectMethod") && + ((p.key.type === "Identifier" && p.key.name === name) || + (p.key.type === "StringLiteral" && p.key.value === name)), + ); +} diff --git a/packages/cli/src/lib/wizard/react-router/codemods/routes-config.ts b/packages/cli/src/lib/wizard/react-router/codemods/routes-config.ts new file mode 100644 index 000000000..b0deee5a6 --- /dev/null +++ b/packages/cli/src/lib/wizard/react-router/codemods/routes-config.ts @@ -0,0 +1,115 @@ +/** + * Adds the example page and API routes to a React Router `routes.ts`. + */ + +import recast from "recast"; +import { existsSync } from "node:fs"; +import type { namedTypes as t } from "ast-types"; + +import { loadFile, writeFile } from "magicast"; + +export async function addRoutesToConfig( + routesConfigPath: string, + isTS: boolean, +): Promise { + // Check if file exists first + if (!existsSync(routesConfigPath)) { + return; + } + + const routesAst = await loadFile(routesConfigPath); + + // Check if routes are already added + const routesCode = routesAst.$code; + if ( + routesCode.includes("sentry-example-page") && + routesCode.includes("sentry-example-api") + ) { + return; + } + + // Add route import if not already present + const hasRouteImport = routesAst.imports.$items.some( + (item) => + item.imported === "route" && item.from === "@react-router/dev/routes", + ); + + if (!hasRouteImport) { + routesAst.imports.$add({ + from: "@react-router/dev/routes", + imported: "route", + local: "route", + }); + } + + // Set up the new routes + const routeExtension = isTS ? "tsx" : "jsx"; + const apiExtension = isTS ? "ts" : "js"; + + const pageRouteCode = `route("/sentry-example-page", "routes/sentry-example-page.${routeExtension}")`; + const apiRouteCode = `route("/api/sentry-example-api", "routes/api.sentry-example-api.${apiExtension}")`; + + let foundDefaultExport = false; + + // Get the AST program + const program = routesAst.$ast as t.Program; + + // Find the default export + for (let i = 0; i < program.body.length; i++) { + const node = program.body[i]; + if (!node) { + continue; + } + + if (node.type === "ExportDefaultDeclaration") { + foundDefaultExport = true; + + const declaration = node.declaration; + + let arrayExpression = null; + + if (declaration.type === "ArrayExpression") { + arrayExpression = declaration; + } else if ( + declaration.type === "TSSatisfiesExpression" || + declaration.type === "TSAsExpression" + ) { + // Handle `[...] satisfies RouteConfig` and `[...] as RouteConfig` + if (declaration.expression.type === "ArrayExpression") { + arrayExpression = declaration.expression; + } + } + + if (!arrayExpression) { + // The caller turns this into manual instructions for the user. + throw new Error( + "The default export of the routes config is not an array literal", + ); + } + + // Parse and add the new route calls directly to the elements array + const pageRouteCall = + recast.parse(pageRouteCode).program.body[0].expression; + const apiRouteCall = + recast.parse(apiRouteCode).program.body[0].expression; + + arrayExpression.elements.push(pageRouteCall); + arrayExpression.elements.push(apiRouteCall); + break; + } + } + + // If no default export found, add one + if (!foundDefaultExport) { + // Create a simple array export without satisfies for now + const newExportCode = `export default [ + ${pageRouteCode}, + ${apiRouteCode}, +];`; + + const newExport = recast.parse(newExportCode).program.body[0]; + program.body.push(newExport); + } + + await writeFile(routesAst.$ast, routesConfigPath); +} diff --git a/packages/cli/src/lib/wizard/react-router/codemods/server-entry.ts b/packages/cli/src/lib/wizard/react-router/codemods/server-entry.ts new file mode 100644 index 000000000..dc4be67ef --- /dev/null +++ b/packages/cli/src/lib/wizard/react-router/codemods/server-entry.ts @@ -0,0 +1,437 @@ +/** + * Instruments a React Router `entry.server` file: wraps `handleRequest`, + * captures errors in `handleError`, and exports the instrumentation API hooks. + */ + +import type { ProxifiedModule } from "magicast"; + +import recast from "recast"; +import type { namedTypes as t } from "ast-types"; + +import { clack } from "../../utils/clack/prompts.js"; +import chalk from "chalk"; + +import { generateCode, loadFile, writeFile } from "magicast"; +import { debug } from "../../utils/debug.js"; +import { + hasSentryContent, + safeCalleeIdentifierMatch, + safeGetIdentifierName, +} from "../../utils/ast-utils.js"; +import { getAfterImportsInsertionIndex } from "./utils.js"; + +export async function instrumentServerEntry( + serverEntryPath: string, + useInstrumentationAPI = false, +): Promise { + const serverEntryAst = await loadFile(serverEntryPath); + + if (!hasSentryContent(serverEntryAst.$ast as t.Program)) { + serverEntryAst.imports.$add({ + from: "@sentry/react-router", + imported: "*", + local: "Sentry", + }); + } + + instrumentHandleError(serverEntryAst); + instrumentHandleRequest(serverEntryAst); + + if (useInstrumentationAPI) { + instrumentInstrumentations(serverEntryAst); + } + + await writeFile(serverEntryAst.$ast, serverEntryPath); +} + +function instrumentInstrumentations( + originalEntryServerMod: ProxifiedModule, +): void { + const originalEntryServerModAST = originalEntryServerMod.$ast as t.Program; + + const hasInstrumentations = originalEntryServerModAST.body.some((node) => { + if ( + node.type !== "ExportNamedDeclaration" || + node.declaration?.type !== "VariableDeclaration" + ) { + return false; + } + + const declarations = node.declaration.declarations; + if (declarations.length === 0) { + return false; + } + + const firstDeclaration = declarations[0]; + if (firstDeclaration?.type !== "VariableDeclarator") { + return false; + } + + const id = firstDeclaration.id; + return ( + id.type === "Identifier" && + (id.name === "instrumentations" || + id.name === "unstable_instrumentations") + ); + }); + + if (hasInstrumentations) { + debug("instrumentations export already exists, skipping adding it again"); + return; + } + + const instrumentationsExport = recast.parse( + `export const instrumentations = [Sentry.createSentryServerInstrumentation()];`, + ).program.body[0]; + + originalEntryServerModAST.body.push(instrumentationsExport); +} + +export function instrumentHandleRequest( + originalEntryServerMod: ProxifiedModule, +): void { + const originalEntryServerModAST = originalEntryServerMod.$ast as t.Program; + + const defaultServerEntryExport = originalEntryServerModAST.body.find( + (node) => { + return node.type === "ExportDefaultDeclaration"; + }, + ); + + if (!defaultServerEntryExport) { + clack.log.warn( + `Could not find function ${chalk.cyan( + "handleRequest", + )} in your server entry file. Creating one for you.`, + ); + + let foundServerRouterImport = false as boolean; + let foundRenderToPipeableStreamImport = false as boolean; + let foundCreateReadableStreamFromReadableImport = false as boolean; + + for (const item of originalEntryServerMod.imports.$items) { + if (item.imported === "ServerRouter" && item.from === "react-router") { + foundServerRouterImport = true; + } + if ( + item.imported === "renderToPipeableStream" && + item.from === "react-dom/server" + ) { + foundRenderToPipeableStreamImport = true; + } + if ( + item.imported === "createReadableStreamFromReadable" && + item.from === "@react-router/node" + ) { + foundCreateReadableStreamFromReadableImport = true; + } + } + + if (!foundServerRouterImport) { + originalEntryServerMod.imports.$add({ + from: "react-router", + imported: "ServerRouter", + local: "ServerRouter", + }); + } + + if (!foundRenderToPipeableStreamImport) { + originalEntryServerMod.imports.$add({ + from: "react-dom/server", + imported: "renderToPipeableStream", + local: "renderToPipeableStream", + }); + } + + if (!foundCreateReadableStreamFromReadableImport) { + originalEntryServerMod.imports.$add({ + from: "@react-router/node", + imported: "createReadableStreamFromReadable", + local: "createReadableStreamFromReadable", + }); + } + + const implementation = + recast.parse(`const handleRequest = Sentry.createSentryHandleRequest({ + ServerRouter, + renderToPipeableStream, + createReadableStreamFromReadable, +})`).program.body[0]; + + try { + originalEntryServerModAST.body.splice( + getAfterImportsInsertionIndex(originalEntryServerModAST), + 0, + implementation, + ); + + originalEntryServerModAST.body.push({ + type: "ExportDefaultDeclaration", + declaration: { + type: "Identifier", + name: "handleRequest", + }, + }); + } catch (error) { + debug("Failed to insert handleRequest implementation:", error); + throw new Error( + "Could not automatically instrument handleRequest. Please add it manually.", + ); + } + } else if ( + // @ts-expect-error - StatementKind works here because the AST is proxified by magicast + generateCode(defaultServerEntryExport).code.includes( + "wrapSentryHandleRequest", + ) + ) { + debug("wrapSentryHandleRequest is already used, skipping wrapping again"); + clack.log.info( + "Sentry handleRequest wrapper already detected, skipping instrumentation.", + ); + } else { + let defaultExportNode = null as t.ExportDefaultDeclaration | null; + const defaultExportIndex = originalEntryServerModAST.body.findIndex( + (node) => { + const found = node.type === "ExportDefaultDeclaration"; + + if (found) { + defaultExportNode = node; + } + + return found; + }, + ); + + if (defaultExportIndex !== -1 && defaultExportNode !== null) { + recast.visit(defaultExportNode, { + visitCallExpression(path) { + if ( + safeCalleeIdentifierMatch(path.value.callee, "pipe") && + path.value.arguments.length && + path.value.arguments[0].type === "Identifier" && + safeGetIdentifierName(path.value.arguments[0]) === "body" + ) { + const wrapped = recast.types.builders.callExpression( + recast.types.builders.memberExpression( + recast.types.builders.identifier("Sentry"), + recast.types.builders.identifier("getMetaTagTransformer"), + ), + [path.value.arguments[0]], + ); + + path.value.arguments[0] = wrapped; + } + + this.traverse(path); + }, + }); + + // Replace the existing default export with the unwrapped function declaration + const funcDeclaration = defaultExportNode.declaration; + // Make non-async functions async so the return type matches wrapSentryHandleRequest + if ( + funcDeclaration.type === "FunctionDeclaration" && + !funcDeclaration.async + ) { + funcDeclaration.async = true; + } + originalEntryServerModAST.body.splice( + defaultExportIndex, + 1, + // @ts-expect-error - an expression works here because the AST is proxified by magicast + funcDeclaration, + ); + + // Adding our wrapped export + originalEntryServerModAST.body.push( + recast.types.builders.exportDefaultDeclaration( + recast.types.builders.callExpression( + recast.types.builders.memberExpression( + recast.types.builders.identifier("Sentry"), + recast.types.builders.identifier("wrapSentryHandleRequest"), + ), + [recast.types.builders.identifier("handleRequest")], + ), + ), + ); + } + } +} + +export function instrumentHandleError( + originalEntryServerMod: ProxifiedModule, +): void { + const originalEntryServerModAST = originalEntryServerMod.$ast as t.Program; + + const handleErrorFunctionExport = originalEntryServerModAST.body.find( + (node) => { + return ( + node.type === "ExportNamedDeclaration" && + node.declaration?.type === "FunctionDeclaration" && + node.declaration.id?.name === "handleError" + ); + }, + ); + + const handleErrorFunctionVariableDeclarationExport = + originalEntryServerModAST.body.find((node) => { + if ( + node.type !== "ExportNamedDeclaration" || + node.declaration?.type !== "VariableDeclaration" + ) { + return false; + } + + const declarations = node.declaration.declarations; + if (declarations.length === 0) { + return false; + } + + const firstDeclaration = declarations[0]; + if (firstDeclaration?.type !== "VariableDeclarator") { + return false; + } + + const id = firstDeclaration.id; + return id.type === "Identifier" && id.name === "handleError"; + }); + + if ( + !handleErrorFunctionExport && + !handleErrorFunctionVariableDeclarationExport + ) { + clack.log.warn( + `Could not find function ${chalk.cyan( + "handleError", + )} in your server entry file. Creating one for you.`, + ); + + const implementation = + recast.parse(`const handleError = Sentry.createSentryHandleError({ + logErrors: false +})`).program.body[0]; + + originalEntryServerModAST.body.splice( + getAfterImportsInsertionIndex(originalEntryServerModAST), + 0, + recast.types.builders.exportNamedDeclaration(implementation), + ); + } else if ( + (handleErrorFunctionExport && + // @ts-expect-error - StatementKind works here because the AST is proxified by magicast + generateCode(handleErrorFunctionExport).code.includes( + "captureException", + )) || + (handleErrorFunctionVariableDeclarationExport && + // @ts-expect-error - StatementKind works here because the AST is proxified by magicast + generateCode(handleErrorFunctionVariableDeclarationExport).code.includes( + "captureException", + )) + ) { + debug( + "Found captureException inside handleError, skipping adding it again", + ); + } else if ( + (handleErrorFunctionExport && + // @ts-expect-error - StatementKind works here because the AST is proxified by magicast + generateCode(handleErrorFunctionExport).code.includes( + "createSentryHandleError", + )) || + (handleErrorFunctionVariableDeclarationExport && + // @ts-expect-error - StatementKind works here because the AST is proxified by magicast + generateCode(handleErrorFunctionVariableDeclarationExport).code.includes( + "createSentryHandleError", + )) + ) { + debug("createSentryHandleError is already used, skipping adding it again"); + } else if (handleErrorFunctionExport) { + // Create the Sentry captureException call as an IfStatement + const sentryCall = recast.parse(`if (!request.signal.aborted) { + Sentry.captureException(error); +}`).program.body[0]; + + // Safely insert the Sentry call at the beginning of the handleError function body + // @ts-expect-error - declaration works here because the AST is proxified by magicast + const declaration = handleErrorFunctionExport.declaration; + if (declaration?.body?.body && Array.isArray(declaration.body.body)) { + declaration.body.body.unshift(sentryCall); + } else { + debug( + "Cannot safely access handleError function body, skipping instrumentation", + ); + } + } else if (handleErrorFunctionVariableDeclarationExport) { + // Create the Sentry captureException call as an IfStatement + const sentryCall = recast.parse(`if (!request.signal.aborted) { + Sentry.captureException(error); +}`).program.body[0]; + + // Safe access to existing handle error implementation with proper null checks + // We know this is ExportNamedDeclaration with VariableDeclaration from the earlier find + const exportDeclaration = handleErrorFunctionVariableDeclarationExport; + if ( + exportDeclaration.type !== "ExportNamedDeclaration" || + exportDeclaration.declaration?.type !== "VariableDeclaration" || + exportDeclaration.declaration.declarations.length === 0 + ) { + debug( + "Cannot safely access handleError variable declaration, skipping instrumentation", + ); + return; + } + + const firstDeclaration = exportDeclaration.declaration.declarations[0]; + const existingHandleErrorImplementation = + firstDeclaration?.type === "VariableDeclarator" + ? firstDeclaration.init + : undefined; + if ( + (existingHandleErrorImplementation?.type !== "ArrowFunctionExpression" && + existingHandleErrorImplementation?.type !== "FunctionExpression") || + existingHandleErrorImplementation.body.type !== "BlockStatement" + ) { + debug( + "Cannot safely access handleError variable declarator init, skipping instrumentation", + ); + return; + } + + const existingParams = existingHandleErrorImplementation.params; + const existingBody = existingHandleErrorImplementation.body; + + const requestParam = { + ...recast.types.builders.property( + "init", + recast.types.builders.identifier("request"), // key + recast.types.builders.identifier("request"), // value + ), + shorthand: true, + }; + // Add error and {request} parameters to handleError function if not present + // When none of the parameters exist + if (existingParams.length === 0) { + existingParams.push( + recast.types.builders.identifier("error"), + recast.types.builders.objectPattern([requestParam]), + ); + // When only error parameter exists + } else if (existingParams.length === 1) { + existingParams.push(recast.types.builders.objectPattern([requestParam])); + // When both parameters exist, but request is not destructured + } else { + const secondParam = existingParams[1]; + if ( + secondParam?.type === "ObjectPattern" && + !secondParam.properties.some( + (prop) => + "key" in prop && safeGetIdentifierName(prop.key) === "request", + ) + ) { + secondParam.properties.push(requestParam); + } + } + + // Add the Sentry call to the function body + existingBody.body.push(sentryCall); + } +} diff --git a/packages/cli/src/lib/wizard/react-router/codemods/utils.ts b/packages/cli/src/lib/wizard/react-router/codemods/utils.ts new file mode 100644 index 000000000..24a646830 --- /dev/null +++ b/packages/cli/src/lib/wizard/react-router/codemods/utils.ts @@ -0,0 +1,17 @@ +/** + * AST helpers shared by the React Router codemods. + */ + +import type { namedTypes as t } from "ast-types"; + +export function getAfterImportsInsertionIndex( + originalEntryServerModAST: t.Program, +): number { + for (let x = originalEntryServerModAST.body.length - 1; x >= 0; x--) { + if (originalEntryServerModAST.body[x]?.type === "ImportDeclaration") { + return x + 1; + } + } + + return 0; +} diff --git a/packages/cli/src/lib/wizard/react-router/codemods/vite.ts b/packages/cli/src/lib/wizard/react-router/codemods/vite.ts new file mode 100644 index 000000000..3c1554148 --- /dev/null +++ b/packages/cli/src/lib/wizard/react-router/codemods/vite.ts @@ -0,0 +1,279 @@ +/** + * Adds the Sentry React Router Vite plugin to `vite.config.(js|ts)`. + */ + +import type { namedTypes as t } from "ast-types"; +import recast from "recast"; +import path from "node:path"; +import { existsSync, promises } from "node:fs"; + +import { parseModule, generateCode } from "magicast"; + +import { clack } from "../../utils/clack/prompts.js"; +import chalk from "chalk"; + +import { + hasSentryContent, + findProperty, + preserveTrailingNewline, +} from "../../utils/ast-utils.js"; +import { debug } from "../../utils/debug.js"; +import { getSentryReactRouterVitePluginImportPath } from "../sdk-version.js"; + +/** + * Extracts ObjectExpression from function body. + * Handles both arrow functions with object returns and block statements with explicit returns. + * + * - Arrow with object-return: (config) => ({ ... }) + * - Arrow with block: (config) => { return { ... }; } + * - Function with block: function(config) { return { ... }; } + * + * @param body - The function body to extract from + * @returns The ObjectExpression if found, undefined otherwise + */ +function extractFromFunctionBody( + body: t.Expression | t.BlockStatement, +): t.ObjectExpression | undefined { + if (body.type === "ObjectExpression") { + return body as t.ObjectExpression; + } + + if (body.type === "BlockStatement") { + const blockBody = body as t.BlockStatement; + const returnStatement = blockBody.body.find( + (stmt: t.Statement): stmt is t.ReturnStatement => + stmt.type === "ReturnStatement", + ); + + return returnStatement?.argument?.type === "ObjectExpression" + ? returnStatement.argument + : undefined; + } + + return undefined; +} + +/** + * Creates the sentryReactRouter Vite plugin call expression. + * + * Generates AST for: + * sentryReactRouter({ + * org: "...", + * project: "...", + * authToken: process.env.SENTRY_AUTH_TOKEN + * }, config) + * + * @param orgSlug - Sentry organization slug + * @param projectSlug - Sentry project slug + * @returns CallExpression node for the Sentry Vite plugin + */ +function createSentryPluginCall( + orgSlug: string, + projectSlug: string, +): t.CallExpression { + const b = recast.types.builders; + return b.callExpression(b.identifier("sentryReactRouter"), [ + b.objectExpression([ + b.objectProperty(b.identifier("org"), b.stringLiteral(orgSlug)), + b.objectProperty(b.identifier("project"), b.stringLiteral(projectSlug)), + b.objectProperty( + b.identifier("authToken"), + b.memberExpression( + b.memberExpression(b.identifier("process"), b.identifier("env")), + b.identifier("SENTRY_AUTH_TOKEN"), + ), + ), + ]), + b.identifier("config"), + ]); +} + +/** Adds @sentry/react-router to optimizeDeps.exclude to prevent 504 errors during dev. */ +function addOptimizeDepsExclude(configObj: t.ObjectExpression): void { + const b = recast.types.builders; + + const optimizeDeps = findProperty(configObj, "optimizeDeps"); + const optimizeDepsObj = + optimizeDeps?.type === "ObjectProperty" && + optimizeDeps.value.type === "ObjectExpression" + ? optimizeDeps.value + : null; + + let targetDepsObj: t.ObjectExpression; + if (!optimizeDepsObj) { + if (optimizeDeps) { + debug("optimizeDeps is not a static object, skipping exclude"); + return; + } + targetDepsObj = b.objectExpression([]); + configObj.properties.push( + b.objectProperty(b.identifier("optimizeDeps"), targetDepsObj), + ); + } else { + targetDepsObj = optimizeDepsObj; + } + + const excludeProp = findProperty(targetDepsObj, "exclude"); + const excludeArr = + excludeProp?.type === "ObjectProperty" && + excludeProp.value.type === "ArrayExpression" + ? excludeProp.value + : null; + + let targetArr: t.ArrayExpression; + if (!excludeArr) { + if (excludeProp) { + debug("optimizeDeps.exclude is not a static array, skipping"); + return; + } + targetArr = b.arrayExpression([]); + targetDepsObj.properties.push( + b.objectProperty(b.identifier("exclude"), targetArr), + ); + } else { + targetArr = excludeArr; + } + + const isAlreadyExcluded = targetArr.elements.some( + (el) => el?.type === "StringLiteral" && el.value === "@sentry/react-router", + ); + if (!isAlreadyExcluded) { + targetArr.elements.push(b.stringLiteral("@sentry/react-router")); + } +} + +export function addReactRouterPluginToViteConfig( + program: t.Program, + orgSlug: string, + projectSlug: string, +): { success: boolean; wasConverted: boolean } { + const b = recast.types.builders; + let wasConverted = false; + + const defaultExport = program.body.find( + (node): node is t.ExportDefaultDeclaration => + node.type === "ExportDefaultDeclaration", + ); + + if (!defaultExport) { + return { success: false, wasConverted: false }; + } + + let configObj: t.ObjectExpression | undefined; + let defineConfigCall: t.CallExpression | undefined; + + if ( + defaultExport.declaration.type === "CallExpression" && + defaultExport.declaration.callee.type === "Identifier" && + defaultExport.declaration.callee.name === "defineConfig" + ) { + defineConfigCall = defaultExport.declaration; + + const arg = defineConfigCall.arguments[0]; + + // Early exit if not single argument + if (defineConfigCall.arguments.length !== 1 || !arg) { + return { success: false, wasConverted: false }; + } + + if (arg.type === "ObjectExpression") { + configObj = arg; + // Convert to function form + const arrowFunction = b.arrowFunctionExpression( + [b.identifier("config")], + configObj, + ); + defineConfigCall.arguments[0] = arrowFunction; + wasConverted = true; + } else if ( + arg.type === "ArrowFunctionExpression" || + arg.type === "FunctionExpression" + ) { + configObj = extractFromFunctionBody(arg.body); + } + } + + if (!configObj) { + return { success: false, wasConverted }; + } + + const pluginsProp = findProperty(configObj, "plugins"); + const sentryPluginCall = createSentryPluginCall(orgSlug, projectSlug); + + if (!pluginsProp) { + configObj.properties.push( + b.objectProperty( + b.identifier("plugins"), + b.arrayExpression([sentryPluginCall]), + ), + ); + } else if (pluginsProp.value.type === "ArrayExpression") { + pluginsProp.value.elements.push(sentryPluginCall); + } else { + return { success: false, wasConverted }; + } + + // Prevent 504 "Outdated Optimize Dep" errors in dev (https://github.com/vitejs/vite/issues/13506) + addOptimizeDepsExclude(configObj); + + return { success: true, wasConverted }; +} + +/** + * The project's Vite config filename: an existing `vite.config.ts`, else an + * existing `vite.config.js`, else the one matching the project's language. + */ +export function getViteConfigFilename(isTS: boolean): string { + const existing = ["vite.config.ts", "vite.config.js"].find((name) => + existsSync(path.join(process.cwd(), name)), + ); + return existing ?? `vite.config.${isTS ? "ts" : "js"}`; +} + +export async function instrumentViteConfig( + orgSlug: string, + projectSlug: string, + vitePluginImportPath: string = getSentryReactRouterVitePluginImportPath( + undefined, + ), +): Promise<{ wasConverted: boolean }> { + const configPath = path.join(process.cwd(), getViteConfigFilename(true)); + + if (!existsSync(configPath)) { + throw new Error("Could not find vite.config.ts or vite.config.js"); + } + + const configContent = await promises.readFile(configPath, "utf-8"); + const filename = chalk.cyan(path.basename(configPath)); + + const mod = parseModule(configContent); + + if (hasSentryContent(mod.$ast as t.Program)) { + clack.log.info(`${filename} already contains sentryReactRouter plugin.`); + return { wasConverted: false }; + } + + mod.imports.$add({ + from: vitePluginImportPath, + imported: "sentryReactRouter", + local: "sentryReactRouter", + }); + + const { success, wasConverted } = addReactRouterPluginToViteConfig( + mod.$ast as t.Program, + orgSlug, + projectSlug, + ); + + if (!success) { + throw new Error("Failed to modify Vite config structure"); + } + + const code = preserveTrailingNewline( + configContent, + generateCode(mod.$ast).code, + ); + await promises.writeFile(configPath, code); + + return { wasConverted }; +} diff --git a/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts b/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts new file mode 100644 index 000000000..9a11de511 --- /dev/null +++ b/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts @@ -0,0 +1,501 @@ +/** + * The React Router (framework mode) setup wizard: installs + * `@sentry/react-router`, instruments the client and server entries, the + * Vite and React Router configs, and optionally adds an example page. + */ + +import { clack } from "../utils/clack/prompts.js"; +import chalk from "chalk"; +import { Sentry } from "../telemetry.js"; + +import type { WizardOptions } from "../utils/types.js"; +import { withTelemetry, traceStep } from "../telemetry.js"; +import { + askShouldCreateExamplePage, + confirmContinueIfNoOrDirtyGitRepo, + featureSelectionPrompt, + getOrAskForProjectData, + getPackageDotJson, + isUsingTypeScript, + printWelcome, + installPackage, + printSdkV11MigrationGuideIfOutdated, + addDotEnvSentryBuildPluginFile, + showCopyPasteInstructions, + runPrettierIfInstalled, +} from "../utils/clack/index.js"; +import { offerProjectScopedMcpConfig } from "../utils/clack/mcp-config.js"; +import { + getPackageVersion, + hasPackageInstalled, +} from "../utils/package-json.js"; +import { + MIN_REACT_ROUTER_VERSION_FOR_SDK_V11, + SENTRY_REACT_ROUTER_SDK_RANGE, + getProfilingNodeRange, + getSentryReactRouterVitePluginImportPath, +} from "./sdk-version.js"; +import { debug } from "../utils/debug.js"; +import { getReactRouterConfigFilename } from "./codemods/react-router-config.js"; +import { getViteConfigFilename } from "./codemods/vite.js"; +import { createExamplePage } from "./sdk-example.js"; +import { + isReactRouterV7, + getReactRouterVersion, + supportsInstrumentationAPI, + supportsOnError, + runReactRouterReveal, + initializeSentryOnEntryClient, + createServerInstrumentationFile, + updatePackageJsonScripts, + instrumentSentryOnEntryServer, + configureReactRouterConfig, + configureReactRouterVitePlugin, + getEntryFilename, +} from "./sdk-setup.js"; +import { + getManualClientEntryContent, + getManualServerEntryContent, + getManualServerInstrumentContent, + getManualReactRouterConfigContent, + getManualViteConfigContent, + getManualPackageJsonScriptsContent, +} from "./templates.js"; +import { abortIfSpotlightNotSupported } from "../utils/abort-if-sportlight-not-supported.js"; +import { + askShouldReduceDataCollection, + sdkSupportsDataCollection, +} from "../utils/data-collection.js"; +import { warnIfNodeVersionUnsupportedBySdkV11 } from "../utils/node-version.js"; + +export async function runReactRouterWizard( + options: WizardOptions, +): Promise { + return await withTelemetry( + { + enabled: options.telemetryEnabled, + integration: "reactRouter", + wizardOptions: options, + }, + () => runReactRouterWizardWithTelemetry(options), + ); +} + +async function runReactRouterWizardWithTelemetry( + options: WizardOptions, +): Promise { + printWelcome({ + wizardName: "Sentry React Router Wizard", + telemetryEnabled: options.telemetryEnabled, + }); + + const packageJson = await getPackageDotJson(); + + const typeScriptDetected = isUsingTypeScript(); + + if (!isReactRouterV7(packageJson)) { + clack.log.error( + "This wizard requires React Router v7. Please upgrade your React Router version to v7.0.0 or higher.\n\nFor upgrade instructions, visit: https://react-router.dev/upgrade/v7", + ); + return; + } + + warnIfNodeVersionUnsupportedBySdkV11(); + + await confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: options.ignoreGitChanges, + cwd: undefined, + }); + + const sentryAlreadyInstalled = hasPackageInstalled( + "@sentry/react-router", + packageJson, + ); + + const projectData = await getOrAskForProjectData( + options, + "javascript-react-router", + ); + + if (projectData.spotlight) { + return await abortIfSpotlightNotSupported("React Router"); + } + + const { selectedProject, authToken, selfHosted, sentryUrl } = projectData; + + printSdkV11MigrationGuideIfOutdated("@sentry/react-router", packageJson); + + await installPackage({ + packageName: `@sentry/react-router@${SENTRY_REACT_ROUTER_SDK_RANGE}`, + packageNameDisplayLabel: "@sentry/react-router", + alreadyInstalled: sentryAlreadyInstalled, + forceInstall: options.forceInstall, + }); + + // The install may have been skipped (user declined the update prompt), so + // re-read package.json to learn which SDK major is actually installed. + const installedSdkVersion = getPackageVersion( + "@sentry/react-router", + await getPackageDotJson(), + ); + const vitePluginImportPath = + getSentryReactRouterVitePluginImportPath(installedSdkVersion); + + // 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, + SENTRY_REACT_ROUTER_SDK_RANGE, + ) && (await askShouldReduceDataCollection()); + + if (!supportsInstrumentationAPI(packageJson)) { + clack.log.warn( + `${chalk.yellow( + `Version 11 of the Sentry React Router SDK requires React Router ${MIN_REACT_ROUTER_VERSION_FOR_SDK_V11} or newer, but this project uses ${chalk.bold( + `react-router@${getReactRouterVersion(packageJson) ?? "unknown"}`, + )}.`, + )} +The wizard will continue, but you may need to upgrade React Router before moving to SDK v11.`, + ); + } + + const featureSelection = await featureSelectionPrompt([ + { + id: "performance", + prompt: `Do you want to enable ${chalk.bold( + "Tracing", + )} to track the performance of your application?`, + enabledHint: "recommended", + }, + { + id: "replay", + prompt: `Do you want to enable ${chalk.bold( + "Session Replay", + )} to get a video-like reproduction of errors during a user session?`, + enabledHint: "recommended, but increases bundle size", + }, + { + id: "profiling", + prompt: `Do you want to enable ${chalk.bold( + "Profiling", + )} to track application performance in detail?`, + enabledHint: "recommended for production debugging", + }, + ] as const); + + // Only ask about Instrumentation API when Tracing is enabled, since it depends on it + let instrumentationAPISelected = false; + if (featureSelection.performance) { + const instrumentationAPISelection = await featureSelectionPrompt([ + { + id: "instrumentationAPI", + prompt: `Do you want to use the ${chalk.bold( + "Instrumentation API", + )} for automatic tracing of loaders, actions, and middleware?`, + enabledHint: "recommended", + }, + ] as const); + instrumentationAPISelected = instrumentationAPISelection.instrumentationAPI; + } + + if (featureSelection.profiling) { + const profilingAlreadyInstalled = hasPackageInstalled( + "@sentry/profiling-node", + packageJson, + ); + + await installPackage({ + packageName: `@sentry/profiling-node@${getProfilingNodeRange( + installedSdkVersion, + )}`, + packageNameDisplayLabel: "@sentry/profiling-node", + alreadyInstalled: profilingAlreadyInstalled, + forceInstall: options.forceInstall, + }); + } + + const createExamplePageSelection = await askShouldCreateExamplePage(); + + traceStep("Reveal missing entry files", () => { + try { + runReactRouterReveal(); + clack.log.success("Entry files are ready for instrumentation"); + } catch (e) { + clack.log.warn(`Could not run 'npx react-router reveal'. +Please create your entry files manually using React Router v7 commands.`); + debug(e); + } + }); + + Sentry.setTag("instrumentation-api-selected", instrumentationAPISelected); + + let useInstrumentationAPI = instrumentationAPISelected; + + if (useInstrumentationAPI && !supportsInstrumentationAPI(packageJson)) { + Sentry.setTag("instrumentation-api-version-guard", true); + const detectedVersion = getReactRouterVersion(packageJson) ?? "unknown"; + clack.log.warn( + `The Instrumentation API requires React Router ${chalk.cyan( + ">=7.15.0", + )} (detected ${chalk.cyan( + detectedVersion, + )}). Your version does not meet this requirement.\n` + + `Continuing without the Instrumentation API. Please upgrade React Router to use this feature:\n` + + chalk.dim( + "https://docs.sentry.io/platforms/javascript/guides/react-router/", + ), + ); + useInstrumentationAPI = false; + } + + Sentry.setTag("use-instrumentation-api", useInstrumentationAPI); + + let useOnError = true; + + if (!supportsOnError(packageJson)) { + Sentry.setTag("on-error-version-guard", true); + const detectedVersion = getReactRouterVersion(packageJson) ?? "unknown"; + clack.log.warn( + `The ${chalk.cyan( + "onError", + )} prop on HydratedRouter requires React Router ${chalk.cyan( + ">=7.11.0", + )} (detected ${chalk.cyan(detectedVersion)}).\n` + + `Skipping automatic error handler setup. Please upgrade React Router and follow the manual setup guide:\n` + + chalk.dim( + "https://docs.sentry.io/platforms/javascript/guides/react-router/", + ), + ); + useOnError = false; + } + + Sentry.setTag("use-on-error", useOnError); + + await traceStep("Initialize Sentry on client entry", async () => { + try { + await initializeSentryOnEntryClient( + selectedProject.keys[0].dsn.public, + featureSelection.performance, + featureSelection.replay, + typeScriptDetected, + reduceDataCollection, + useInstrumentationAPI, + useOnError, + ); + } catch (e) { + clack.log.warn( + `Could not initialize Sentry on client entry automatically.`, + ); + + const clientEntryFilename = getEntryFilename( + "entry.client", + typeScriptDetected, + ); + + const manualClientContent = getManualClientEntryContent( + selectedProject.keys[0].dsn.public, + featureSelection.performance, + featureSelection.replay, + reduceDataCollection, + useInstrumentationAPI, + useOnError, + ); + + await showCopyPasteInstructions({ + filename: clientEntryFilename, + codeSnippet: manualClientContent, + hint: "This enables error tracking and performance monitoring for your React Router app", + }); + + debug(e); + } + }); + + await traceStep("Instrument server entry", async () => { + try { + await instrumentSentryOnEntryServer( + typeScriptDetected, + useInstrumentationAPI, + ); + } catch (e) { + clack.log.warn( + `Could not initialize Sentry on server entry automatically.`, + ); + + const serverEntryFilename = getEntryFilename( + "entry.server", + typeScriptDetected, + ); + const manualServerContent = getManualServerEntryContent( + useInstrumentationAPI, + ); + + await showCopyPasteInstructions({ + filename: serverEntryFilename, + codeSnippet: manualServerContent, + hint: "This configures server-side request handling and error tracking", + }); + + debug(e); + } + }); + + await traceStep("Create server instrumentation file", async () => { + try { + createServerInstrumentationFile( + selectedProject.keys[0].dsn.public, + { + performance: featureSelection.performance, + replay: featureSelection.replay, + profiling: featureSelection.profiling, + }, + reduceDataCollection, + ); + } catch (e) { + clack.log.warn( + "Could not create a server instrumentation file automatically.", + ); + + const manualServerInstrumentContent = getManualServerInstrumentContent( + selectedProject.keys[0].dsn.public, + featureSelection.performance, + featureSelection.profiling, + reduceDataCollection, + ); + + await showCopyPasteInstructions({ + filename: "instrument.server.mjs", + codeSnippet: manualServerInstrumentContent, + hint: "Create the file if it does not exist - this initializes Sentry before your application starts", + }); + + debug(e); + } + }); + + await traceStep("Update package.json scripts", async () => { + try { + await updatePackageJsonScripts(); + } catch (e) { + clack.log.warn("Could not update start script automatically."); + + await showCopyPasteInstructions({ + filename: "package.json", + codeSnippet: getManualPackageJsonScriptsContent(), + }); + + debug(e); + } + }); + + await traceStep("Create build plugin env file", async () => { + try { + await addDotEnvSentryBuildPluginFile(authToken); + } catch (e) { + clack.log.warn( + "Could not create .env.sentry-build-plugin file. Please create it manually.", + ); + debug(e); + } + }); + + // Validate auth token before configuring sourcemap uploads + if (!authToken) { + clack.log.warn( + `${chalk.yellow( + "Warning:", + )} No auth token found. Sourcemap uploads will not work without ${chalk.cyan( + "SENTRY_AUTH_TOKEN", + )}.\n` + + `Please set ${chalk.cyan("SENTRY_AUTH_TOKEN")} in your ${chalk.cyan( + ".env.sentry-build-plugin", + )} file or environment variables.`, + ); + } + + // Configure Vite plugin for sourcemap uploads + await traceStep("Configure Vite plugin for sourcemap uploads", async () => { + try { + await configureReactRouterVitePlugin( + selectedProject.organization.slug, + selectedProject.slug, + vitePluginImportPath, + ); + } catch (e) { + clack.log.warn( + `Could not configure Vite plugin for sourcemap uploads automatically.`, + ); + + await showCopyPasteInstructions({ + filename: getViteConfigFilename(typeScriptDetected), + codeSnippet: getManualViteConfigContent( + selectedProject.organization.slug, + selectedProject.slug, + vitePluginImportPath, + ), + hint: "This enables automatic sourcemap uploads during build for better error tracking", + }); + + debug(e); + } + }); + + // Configure React Router config for build hook + await traceStep("Configure React Router build hook", async () => { + try { + await configureReactRouterConfig( + typeScriptDetected, + vitePluginImportPath, + ); + } catch (e) { + clack.log.warn( + `Could not configure React Router build hook automatically.`, + ); + + const configFilename = getReactRouterConfigFilename(typeScriptDetected); + await showCopyPasteInstructions({ + filename: configFilename, + codeSnippet: getManualReactRouterConfigContent( + configFilename.endsWith(".ts"), + vitePluginImportPath, + ), + hint: "This enables automatic sourcemap uploads at the end of the build process", + }); + + debug(e); + } + }); + + // Create example page if requested + if (createExamplePageSelection) { + await traceStep("Create example page", async () => { + await createExamplePage({ + selfHosted, + orgSlug: selectedProject.organization.slug, + projectId: selectedProject.id, + url: sentryUrl, + isTS: typeScriptDetected, + projectDir: process.cwd(), + }); + }); + } + + 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( + `${chalk.green("Successfully installed the Sentry React Router SDK!")}${ + createExamplePageSelection + ? `\n\nYou can validate your setup by visiting ${chalk.cyan( + '"/sentry-example-page"', + )} in your application.` + : "" + }`, + ); +} diff --git a/packages/cli/src/lib/wizard/react-router/sdk-example.ts b/packages/cli/src/lib/wizard/react-router/sdk-example.ts new file mode 100644 index 000000000..7a342febf --- /dev/null +++ b/packages/cli/src/lib/wizard/react-router/sdk-example.ts @@ -0,0 +1,345 @@ +/** + * Writes the example page and API route that throw a test error in a React + * Router app. + */ + +import { existsSync, mkdirSync, promises } from "node:fs"; +import path from "node:path"; + +import { clack } from "../utils/clack/prompts.js"; +import chalk from "chalk"; +import { addRoutesToConfig } from "./codemods/routes-config.js"; +import { getRouteFilePath } from "./sdk-setup.js"; + +export async function createExamplePage(options: { + selfHosted: boolean; + orgSlug: string; + projectId: string; + url: string; + isTS: boolean; + projectDir: string; +}) { + const routesPath = path.join(options.projectDir, "app", "routes"); + + if (!existsSync(routesPath)) { + mkdirSync(routesPath, { recursive: true }); + } + + const exampleRoutePath = getRouteFilePath( + "sentry-example-page", + options.isTS, + ); + + const exampleRouteRelative = path.join( + "app", + "routes", + `sentry-example-page.${options.isTS ? "tsx" : "jsx"}`, + ); + + if (existsSync(exampleRoutePath)) { + clack.log.warn( + `It seems like a sentry example page already exists (${path.basename( + exampleRoutePath, + )}). Skipping creation of example route.`, + ); + return; + } + + await promises.writeFile( + exampleRoutePath, + getSentryExamplePageContents(options), + ); + + // Create the API route for backend error testing + const apiRoutePath = path.join( + routesPath, + `api.sentry-example-api.${options.isTS ? "ts" : "js"}`, + ); + + const apiRouteRelative = path.join( + "app", + "routes", + `api.sentry-example-api.${options.isTS ? "ts" : "js"}`, + ); + + if (!existsSync(apiRoutePath)) { + await promises.writeFile( + apiRoutePath, + getSentryExampleApiContents(options), + ); + clack.log.info(`Created ${chalk.cyan(apiRouteRelative)}.`); + } + + // Check if there's a routes.(ts|js) configuration file and add the route using codemod + const routesConfigPath = ["routes.ts", "routes.js"] + .map((filename) => path.join(options.projectDir, "app", filename)) + .find((candidate) => existsSync(candidate)); + if (routesConfigPath) { + try { + await addRoutesToConfig(routesConfigPath, options.isTS); + } catch (e) { + clack.log.warn( + `Could not update ${path.basename(routesConfigPath)} configuration: ${ + e instanceof Error ? e.message : String(e) + }`, + ); + clack.log.info( + `Please manually add these routes to your ${path.basename( + routesConfigPath, + )} file: route("/sentry-example-page", "routes/sentry-example-page.${ + options.isTS ? "tsx" : "jsx" + }") and route("/api/sentry-example-api", "routes/api.sentry-example-api.${ + options.isTS ? "ts" : "js" + }")`, + ); + } + } + + clack.log.info(`Created ${chalk.cyan(exampleRouteRelative)}.`); +} + +export function getSentryExamplePageContents(options: { + selfHosted: boolean; + orgSlug: string; + projectId: string; + url: string; + isTS?: boolean; +}) { + const issuesPageLink = options.selfHosted + ? `${options.url}organizations/${options.orgSlug}/issues/?project=${options.projectId}` + : `https://${options.orgSlug}.sentry.io/issues/?project=${options.projectId}`; + + return `import * as Sentry from '@sentry/react-router'; +import { useState, useEffect } from 'react'; + +class SentryExampleFrontendError extends Error { + constructor(message${options.isTS ? ": string | undefined" : ""}) { + super(message); + this.name = "SentryExampleFrontendError"; + } +} + +export const meta = () => { + return [ + { title: "sentry-example-page" }, + ]; +} + +export default function SentryExamplePage() { + const [hasSentError, setHasSentError] = useState(false); + const [isConnected, setIsConnected] = useState(true); + + useEffect(() => { + async function checkConnectivity() { + const result = await Sentry.diagnoseSdkConnectivity(); + setIsConnected(result !== 'sentry-unreachable'); + } + checkConnectivity(); + }, [setIsConnected]); + + return ( +
+
+
+ + + +

+ sentry-example-page +

+ +

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

+ + + + {hasSentError ? ( +

+ Sample error was sent to Sentry. +

+ ) : !isConnected ? ( +
+

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

+
+ ) : ( +
+ )} + +
+
+ + {/* Not for production use! We're just saving you from having to delete an extra CSS file ;) */} + +
+ ); +} + +const styles = \` + main { + display: flex; + min-height: 100vh; + flex-direction: column; + justify-content: center; + align-items: center; + gap: 16px; + padding: 16px; + font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", sans-serif; + } + + h1 { + padding: 0px 4px; + border-radius: 4px; + background-color: rgba(24, 20, 35, 0.03); + font-family: monospace; + font-size: 20px; + line-height: 1.2; + } + + p { + margin: 0; + font-size: 20px; + } + + a { + color: #6341F0; + text-decoration: underline; + cursor: pointer; + + @media (prefers-color-scheme: dark) { + color: #B3A1FF; + } + } + + button { + border-radius: 8px; + color: white; + cursor: pointer; + background-color: #553DB8; + border: none; + padding: 0; + margin-top: 4px; + + & > span { + display: inline-block; + padding: 12px 16px; + border-radius: inherit; + font-size: 20px; + font-weight: bold; + line-height: 1; + background-color: #7553FF; + border: 1px solid #553DB8; + transform: translateY(-4px); + } + + &:hover > span { + transform: translateY(-8px); + } + + &:active > span { + transform: translateY(0); + } + + &:disabled { + cursor: not-allowed; + opacity: 0.6; + + & > span { + transform: translateY(0); + border: none; + } + } + } + + .description { + text-align: center; + color: #6E6C75; + max-width: 500px; + line-height: 1.5; + font-size: 20px; + + @media (prefers-color-scheme: dark) { + color: #A49FB5; + } + } + + .flex-spacer { + flex: 1; + } + + .success { + padding: 12px 16px; + border-radius: 8px; + font-size: 20px; + line-height: 1; + background-color: #00F261; + border: 1px solid #00BF4D; + color: #181423; + } + + .success_placeholder { + height: 46px; + } + + .connectivity-error { + padding: 12px 16px; + background-color: #E50045; + border-radius: 8px; + width: 500px; + color: #FFFFFF; + border: 1px solid #A80033; + text-align: center; + margin: 0; + } + + .connectivity-error a { + color: #FFFFFF; + text-decoration: underline; + } +\`; +`; +} + +export function getSentryExampleApiContents(options: { isTS?: boolean }) { + return `import * as Sentry from '@sentry/react-router'; + +class SentryExampleBackendError extends Error { + constructor(message${options.isTS ? ": string | undefined" : ""}) { + super(message); + this.name = "SentryExampleBackendError"; + } +} + +export async function loader() { + await Sentry.startSpan({ + name: 'Example Backend Span', + op: 'test' + }, async () => { + // Simulate some backend work + await new Promise(resolve => setTimeout(resolve, 100)); + }); + + throw new SentryExampleBackendError("This error is raised on the backend API route."); +} +`; +} diff --git a/packages/cli/src/lib/wizard/react-router/sdk-setup.ts b/packages/cli/src/lib/wizard/react-router/sdk-setup.ts new file mode 100644 index 000000000..9ef3c991e --- /dev/null +++ b/packages/cli/src/lib/wizard/react-router/sdk-setup.ts @@ -0,0 +1,458 @@ +/** + * Setup steps of the React Router wizard: revealing the entry files, + * writing the server instrumentation file, updating `package.json` scripts, + * and the config edits, each with copy-paste instructions as a fallback. + */ + +import { existsSync, promises, writeFileSync } from "node:fs"; +import path from "node:path"; +import { execSync } from "node:child_process"; + +import { clack } from "../utils/clack/prompts.js"; +import chalk from "chalk"; +import { gte, minVersion, coerce } from "semver"; + +import type { PackageDotJson } from "../utils/package-json.js"; +import { getPackageVersion } from "../utils/package-json.js"; +import { debug } from "../utils/debug.js"; +import { getSentryInstrumentationServerContent } from "./templates.js"; +import { instrumentServerEntry } from "./codemods/server-entry.js"; +import { abortIfCancelled, getPackageDotJson } from "../utils/clack/index.js"; +import { instrumentClientEntry } from "./codemods/client.entry.js"; +import { + getReactRouterConfigFilename, + instrumentReactRouterConfig, +} from "./codemods/react-router-config.js"; +import { + getViteConfigFilename, + instrumentViteConfig, +} from "./codemods/vite.js"; + +const REACT_ROUTER_REVEAL_COMMAND = "npx react-router reveal"; +const INSTRUMENTATION_FILE = "instrument.server.mjs"; +const APP_DIRECTORY = "app"; +const ROUTES_DIRECTORY = "routes"; + +function _formatConfigErrorMessage( + filename: string, + errorMessage: string, + fallbackHint: string, +): string { + return ( + `Could not automatically configure ${filename}. ${errorMessage}\n` + + `This may happen if your config has an unusual format. ` + + fallbackHint + ); +} + +/** + * The filename of an `app/` entry such as `entry.client`: the `.tsx` or + * `.jsx` file that exists, else the one matching the project's language. + */ +export function getEntryFilename(name: string, isTS: boolean): string { + const preferred = `${name}.${isTS ? "tsx" : "jsx"}`; + const alternate = `${name}.${isTS ? "jsx" : "tsx"}`; + const exists = (file: string) => + existsSync(path.join(process.cwd(), APP_DIRECTORY, file)); + return !exists(preferred) && exists(alternate) ? alternate : preferred; +} + +function getAppFilePath(filename: string, isTS: boolean): string { + return path.join( + process.cwd(), + APP_DIRECTORY, + getEntryFilename(filename, isTS), + ); +} + +export function getRouteFilePath(filename: string, isTS: boolean): string { + const ext = isTS ? "tsx" : "jsx"; + return path.join( + process.cwd(), + APP_DIRECTORY, + ROUTES_DIRECTORY, + `${filename}.${ext}`, + ); +} + +export async function tryRevealAndGetManualInstructions( + missingFilename: string, + filePath: string, +): Promise { + const shouldTryReveal = await abortIfCancelled( + clack.confirm({ + message: `Would you like to try running ${chalk.cyan( + REACT_ROUTER_REVEAL_COMMAND, + )} to generate entry files?`, + initialValue: true, + }), + ); + + if (shouldTryReveal) { + try { + clack.log.info(`Running ${chalk.cyan(REACT_ROUTER_REVEAL_COMMAND)}...`); + const output = execSync(REACT_ROUTER_REVEAL_COMMAND, { + encoding: "utf8", + stdio: "pipe", + }); + clack.log.info(output); + + if (existsSync(filePath)) { + clack.log.success( + `Found ${chalk.cyan(missingFilename)} after running reveal.`, + ); + return true; + } + clack.log.warn( + `${chalk.cyan(missingFilename)} still not found after running reveal.`, + ); + } catch (e) { + debug("Failed to run React Router reveal command:", e); + clack.log.warn( + `Failed to run ${chalk.cyan( + REACT_ROUTER_REVEAL_COMMAND, + )}. This command generates entry files for React Router v7.`, + ); + } + } + + return false; // File still doesn't exist, manual intervention needed +} + +async function ensureEntryFileExists( + filename: string, + filePath: string, +): Promise { + if (existsSync(filePath)) { + return; // File exists, nothing to do + } + + clack.log.warn(`Could not find ${chalk.cyan(filename)}.`); + + const fileExists = await tryRevealAndGetManualInstructions( + filename, + filePath, + ); + + if (!fileExists) { + throw new Error( + `Failed to create or find ${filename}. Please create this file manually or ensure your React Router v7 project structure is correct.`, + ); + } +} + +export function runReactRouterReveal(): void { + if ( + !existsSync(path.join(process.cwd(), "app", "entry.client.tsx")) && + !existsSync(path.join(process.cwd(), "app", "entry.client.jsx")) + ) { + try { + execSync(REACT_ROUTER_REVEAL_COMMAND, { + encoding: "utf8", + stdio: "pipe", + }); + } catch (e) { + debug("Failed to run React Router reveal command:", e); + throw e; + } + } +} + +export function isReactRouterV7(packageJson: PackageDotJson): boolean { + const reactRouterVersion = getPackageVersion( + "@react-router/dev", + packageJson, + ); + if (!reactRouterVersion) { + return false; + } + + const minVer = minVersion(reactRouterVersion); + + if (!minVer) { + return false; + } + + return gte(minVer, "7.0.0"); +} + +export function getReactRouterVersion( + packageJson: PackageDotJson, +): string | undefined { + const rangeVersion = getPackageVersion("@react-router/dev", packageJson); + if (!rangeVersion) { + return undefined; + } + + const coerced = coerce(rangeVersion); + return coerced ? coerced.version : rangeVersion; +} + +export function supportsOnError(packageJson: PackageDotJson): boolean { + const reactRouterVersion = getPackageVersion( + "@react-router/dev", + packageJson, + ); + if (!reactRouterVersion) { + return false; + } + + const minVer = minVersion(reactRouterVersion); + + if (!minVer) { + return false; + } + + return gte(minVer, "7.11.0"); +} + +export function supportsInstrumentationAPI( + packageJson: PackageDotJson, +): boolean { + const reactRouterVersion = getPackageVersion( + "@react-router/dev", + packageJson, + ); + if (!reactRouterVersion) { + return false; + } + + const minVer = minVersion(reactRouterVersion); + + if (!minVer) { + return false; + } + + return gte(minVer, "7.15.0"); +} + +// oxlint-disable-next-line max-params -- positional like the sentry-wizard original and its tests +export async function initializeSentryOnEntryClient( + dsn: string, + enableTracing: boolean, + enableReplay: boolean, + isTS: boolean, + reduceDataCollection: boolean, + useInstrumentationAPI = false, + useOnError = false, +): Promise { + const clientEntryPath = getAppFilePath("entry.client", isTS); + const clientEntryFilename = path.basename(clientEntryPath); + + await ensureEntryFileExists(clientEntryFilename, clientEntryPath); + + await instrumentClientEntry( + clientEntryPath, + dsn, + enableTracing, + enableReplay, + reduceDataCollection, + useInstrumentationAPI, + useOnError, + ); + + clack.log.success( + `Updated ${chalk.cyan(clientEntryFilename)} with Sentry initialization.`, + ); +} + +export function createServerInstrumentationFile( + dsn: string, + selectedFeatures: { + performance: boolean; + replay: boolean; + profiling: boolean; + }, + reduceDataCollection: boolean, +): string { + const instrumentationPath = path.join(process.cwd(), INSTRUMENTATION_FILE); + + const content = getSentryInstrumentationServerContent( + dsn, + selectedFeatures.performance, + selectedFeatures.profiling, + reduceDataCollection, + ); + + writeFileSync(instrumentationPath, content); + clack.log.success(`Created ${chalk.cyan(INSTRUMENTATION_FILE)}.`); + return instrumentationPath; +} + +export async function updatePackageJsonScripts(): Promise { + const packageJson = await getPackageDotJson(); + + if (!packageJson.scripts) { + throw new Error( + "Could not find a `scripts` section in your package.json file. Please add scripts manually or ensure your package.json is valid.", + ); + } + + if (!packageJson.scripts["start"]) { + throw new Error( + 'Could not find a `start` script in your package.json. Please add: "start": "react-router-serve ./build/server/index.js" and re-run the wizard.', + ); + } + + function mergeNodeOptions( + scriptCommand: string, + instrumentPath = "./instrument.server.mjs", + ): string { + if (scriptCommand.includes(instrumentPath)) { + return scriptCommand; + } + + const quotedMatch = scriptCommand.match(/NODE_OPTIONS=(['"])([^'"]*)\1/); + if (quotedMatch) { + const existingOptions = quotedMatch[2]; + const mergedOptions = + `${existingOptions} --import ${instrumentPath}`.trim(); + return scriptCommand.replace( + /NODE_OPTIONS=(['"])([^'"]*)\1/, + `NODE_OPTIONS='${mergedOptions}'`, + ); + } + + const unquotedMatch = scriptCommand.match( + /NODE_OPTIONS=([^\s]+(?:\s+[^\s]+)*?)(\s+(?:react-router-serve|react-router|node|npx|tsx))/, + ); + if (unquotedMatch) { + const existingOptions = unquotedMatch[1]; + const commandPart = unquotedMatch[2]; + const mergedOptions = + `${existingOptions} --import ${instrumentPath}`.trim(); + return scriptCommand.replace( + /NODE_OPTIONS=([^\s]+(?:\s+[^\s]+)*?)(\s+(?:react-router-serve|react-router|node|npx|tsx))/, + `NODE_OPTIONS='${mergedOptions}'${commandPart}`, + ); + } + + return `NODE_OPTIONS='--import ${instrumentPath}' ${scriptCommand}`; + } + + if (packageJson.scripts["dev"]) { + packageJson.scripts["dev"] = mergeNodeOptions(packageJson.scripts["dev"]); + } + + const startScript = packageJson.scripts["start"]; + if ( + !startScript.includes(INSTRUMENTATION_FILE) && + !startScript.includes("NODE_OPTIONS") + ) { + packageJson.scripts["start"] = + `NODE_OPTIONS='--import ./${INSTRUMENTATION_FILE}' react-router-serve ./build/server/index.js`; + } else { + packageJson.scripts["start"] = mergeNodeOptions(startScript); + } + + // Prevent React CJS dev/prod bundle mismatch when --import loads react + // before react-router-serve sets NODE_ENV + if ( + packageJson.scripts["start"].includes("--import") && + !packageJson.scripts["start"].includes("NODE_ENV=") + ) { + packageJson.scripts["start"] = + `NODE_ENV=production ${packageJson.scripts["start"]}`; + } + + await promises.writeFile( + "package.json", + JSON.stringify(packageJson, null, 2), + ); +} + +export async function instrumentSentryOnEntryServer( + isTS: boolean, + useInstrumentationAPI = false, +): Promise { + const serverEntryPath = getAppFilePath("entry.server", isTS); + const serverEntryFilename = path.basename(serverEntryPath); + + await ensureEntryFileExists(serverEntryFilename, serverEntryPath); + + await instrumentServerEntry(serverEntryPath, useInstrumentationAPI); + + clack.log.success( + `Updated ${chalk.cyan(serverEntryFilename)} with Sentry error handling.`, + ); +} + +export async function configureReactRouterVitePlugin( + orgSlug: string, + projectSlug: string, + vitePluginImportPath: string, +): Promise { + const filename = chalk.cyan(getViteConfigFilename(true)); + + try { + const { wasConverted } = await instrumentViteConfig( + orgSlug, + projectSlug, + vitePluginImportPath, + ); + + clack.log.success(`Updated ${filename} with sentryReactRouter plugin.`); + + if (wasConverted) { + clack.log.info( + `Converted your Vite config to function form ${chalk.dim( + "(defineConfig(config => ({ ... })))", + )} to support the Sentry React Router plugin.`, + ); + } + } catch (e) { + debug("Failed to modify vite config:", e); + const errorMessage = e instanceof Error ? e.message : String(e); + throw new Error( + _formatConfigErrorMessage( + filename, + errorMessage, + "You may need to add the plugin manually.", + ), + ); + } +} + +export async function configureReactRouterConfig( + isTS: boolean, + vitePluginImportPath: string, +): Promise { + const configFilename = getReactRouterConfigFilename(isTS); + const configPath = path.join(process.cwd(), configFilename); + const filename = chalk.cyan(configFilename); + + try { + const fileExistedBefore = existsSync(configPath); + + const { ssrWasChanged } = await instrumentReactRouterConfig( + isTS, + vitePluginImportPath, + ); + + if (fileExistedBefore) { + clack.log.success(`Updated ${filename} with Sentry buildEnd hook.`); + } else { + clack.log.success(`Created ${filename} with Sentry buildEnd hook.`); + } + + if (ssrWasChanged) { + clack.log.warn( + `${chalk.yellow( + "Note:", + )} SSR has been enabled in your React Router config (${chalk.cyan( + "ssr: true", + )}). This is required for Sentry sourcemap uploads to work correctly.`, + ); + } + } catch (e) { + debug("Failed to modify react-router.config:", e); + const errorMessage = e instanceof Error ? e.message : String(e); + throw new Error( + _formatConfigErrorMessage( + filename, + errorMessage, + "You may need to add the buildEnd hook manually.", + ), + ); + } +} diff --git a/packages/cli/src/lib/wizard/react-router/sdk-version.ts b/packages/cli/src/lib/wizard/react-router/sdk-version.ts new file mode 100644 index 000000000..afb797710 --- /dev/null +++ b/packages/cli/src/lib/wizard/react-router/sdk-version.ts @@ -0,0 +1,50 @@ +import { getMajorVersion } from "../utils/semver.js"; + +/** + * Version range of `@sentry/react-router` (and `@sentry/profiling-node`) the + * wizard installs. Also decides the default import path of the Vite plugin + * helpers when the installed version is unknown. + */ +export const SENTRY_REACT_ROUTER_SDK_RANGE = "^11"; + +/** Root export. Exposes `sentryReactRouter` and `sentryOnBuildEnd` up to SDK v10 only. */ +export const SENTRY_REACT_ROUTER_ROOT_IMPORT_PATH = "@sentry/react-router"; + +/** Subpath that exposes the Vite plugin helpers from SDK v11 on. v10 does not ship it. */ +export const SENTRY_REACT_ROUTER_VITE_IMPORT_PATH = "@sentry/react-router/vite"; + +/** Minimum React Router version supported by SDK v11 in framework mode. */ +export const MIN_REACT_ROUTER_VERSION_FOR_SDK_V11 = "7.15.0"; + +/** + * Returns the module `sentryReactRouter` and `sentryOnBuildEnd` must be + * imported from for the installed SDK. v11 moved them to the `/vite` subpath + * and removed them from the root export, while v10 only has them on the root + * export. Unknown or unparseable versions fall back to whatever the wizard + * would install. + */ +export function getSentryReactRouterVitePluginImportPath( + installedSdkVersion: string | undefined, +): string { + const sdkMajor = + getMajorVersion(installedSdkVersion) ?? + getMajorVersion(SENTRY_REACT_ROUTER_SDK_RANGE) ?? + 0; + + return sdkMajor >= 11 + ? SENTRY_REACT_ROUTER_VITE_IMPORT_PATH + : SENTRY_REACT_ROUTER_ROOT_IMPORT_PATH; +} + +/** + * The `@sentry/profiling-node` range matching the installed SDK's major, so a + * kept v10 SDK doesn't get a v11 profiler. Falls back to the install range. + */ +export function getProfilingNodeRange( + installedSdkVersion: string | undefined, +): string { + const sdkMajor = getMajorVersion(installedSdkVersion); + return sdkMajor === undefined + ? SENTRY_REACT_ROUTER_SDK_RANGE + : `^${sdkMajor}`; +} diff --git a/packages/cli/src/lib/wizard/react-router/templates.ts b/packages/cli/src/lib/wizard/react-router/templates.ts new file mode 100644 index 000000000..19e146da3 --- /dev/null +++ b/packages/cli/src/lib/wizard/react-router/templates.ts @@ -0,0 +1,398 @@ +/** + * Code templates the React Router wizard writes or shows as copy-paste + * instructions. + */ + +import { makeCodeSnippet } from "../utils/clack/index.js"; +import { getDataCollectionSnippet } from "../utils/data-collection.js"; +import { getSentryReactRouterVitePluginImportPath } from "./sdk-version.js"; + +const DATA_COLLECTION_HINT = ` dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/react-router/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + },`; + +/** + * The active PII-reducing preset when the user opted in, the commented-out + * hint otherwise. + */ +export function getDataCollectionBlock(reduceDataCollection: boolean): string { + return reduceDataCollection + ? getDataCollectionSnippet(" ") + : DATA_COLLECTION_HINT; +} + +export const EXAMPLE_PAGE_TEMPLATE_TSX = `import type { Route } from "./+types/sentry-example-page"; + +export async function loader() { + throw new Error("some error thrown in a loader"); +} + +export default function SentryExamplePage() { + return
Loading this page will throw an error
; +}`; + +export const EXAMPLE_PAGE_TEMPLATE_JSX = `export async function loader() { + throw new Error("some error thrown in a loader"); +} + +export default function SentryExamplePage() { + return
Loading this page will throw an error
; +}`; + +function generateServerInstrumentationCode( + dsn: string, + enableTracing: boolean, + enableProfiling: boolean, + reduceDataCollection: boolean, +): string { + return `import * as Sentry from '@sentry/react-router';${ + enableProfiling + ? `\nimport { nodeProfilingIntegration } from '@sentry/profiling-node';` + : "" + } + +Sentry.init({ + dsn: "${dsn}", + +${getDataCollectionBlock(reduceDataCollection)}${ + enableProfiling ? "\n\n integrations: [nodeProfilingIntegration()]," : "" + } + tracesSampleRate: ${enableTracing ? "1.0" : "0"}, ${ + enableTracing ? "// Capture 100% of the traces" : "" + }${ + enableProfiling + ? `\n profileSessionSampleRate: 1.0, // profile every session\n profileLifecycle: "trace", // profile while a trace is active` + : "" + }${ + enableTracing + ? ` + + // Set up performance monitoring + beforeSend(event) { + // Filter out 404s from error reporting + if (event.exception) { + const error = event.exception.values?.[0]; + if (error?.type === "NotFoundException" || error?.value?.includes("404")) { + return null; + } + } + return event; + },` + : "" + } +});`; +} + +export const getSentryInstrumentationServerContent = ( + dsn: string, + enableTracing: boolean, + enableProfiling: boolean, + reduceDataCollection: boolean, +) => { + return generateServerInstrumentationCode( + dsn, + enableTracing, + enableProfiling, + reduceDataCollection, + ); +}; + +// oxlint-disable-next-line max-params -- positional like the sentry-wizard original and its tests +export const getManualClientEntryContent = ( + dsn: string, + enableTracing: boolean, + enableReplay: boolean, + reduceDataCollection: boolean, + useInstrumentationAPI = false, + useOnError = false, +) => { + if (useInstrumentationAPI && enableTracing) { + const integrations = ["tracing"]; + if (enableReplay) { + integrations.push("Sentry.replayIntegration()"); + } + + const integrationsStr = integrations.join(",\n "); + + return makeCodeSnippet(true, (unchanged, plus) => + unchanged(`${plus("import * as Sentry from '@sentry/react-router';")} +import { startTransition, StrictMode } from 'react'; +import { hydrateRoot } from 'react-dom/client'; +import { HydratedRouter } from 'react-router/dom'; + +${plus(`const tracing = Sentry.reactRouterTracingIntegration();`)} + +${plus(`Sentry.init({ + dsn: "${dsn}", + +${getDataCollectionBlock(reduceDataCollection)} + + integrations: [ + ${integrationsStr} + ], + + tracesSampleRate: 1.0, // Capture 100% of the traces + + // Set \`tracePropagationTargets\` to declare which URL(s) should have trace propagation enabled + // In production, replace "yourserver.io" with your actual backend domain + tracePropagationTargets: [/^\\//, /^https:\\/\\/yourserver\\.io\\/api/],${ + enableReplay + ? "\n\n // Capture Replay for 10% of all sessions,\n // plus 100% of sessions with an error\n replaysSessionSampleRate: 0.1,\n replaysOnErrorSampleRate: 1.0," + : "" + } +});`)} + +startTransition(() => { + hydrateRoot( + document, + + ${plus( + ``, + )} + + ); +});`), + ); + } + + const integrations = []; + + if (enableTracing) { + integrations.push("Sentry.reactRouterTracingIntegration()"); + } + + if (enableReplay) { + integrations.push("Sentry.replayIntegration()"); + } + + const integrationsStr = + integrations.length > 0 ? integrations.join(",\n ") : ""; + + return makeCodeSnippet(true, (unchanged, plus) => + unchanged(`${plus("import * as Sentry from '@sentry/react-router';")} +import { startTransition, StrictMode } from 'react'; +import { hydrateRoot } from 'react-dom/client'; +import { HydratedRouter } from 'react-router/dom'; + +${plus(`Sentry.init({ + dsn: "${dsn}", + +${getDataCollectionBlock(reduceDataCollection)} + + integrations: [ + ${integrationsStr} + ], + + tracesSampleRate: ${enableTracing ? "1.0" : "0"},${ + enableTracing ? " // Capture 100% of the traces" : "" + }${ + enableTracing + ? '\n\n // Set `tracePropagationTargets` to declare which URL(s) should have trace propagation enabled\n // In production, replace "yourserver.io" with your actual backend domain\n tracePropagationTargets: [/^\\//, /^https:\\/\\/yourserver\\.io\\/api/],' + : "" + }${ + enableReplay + ? "\n\n // Capture Replay for 10% of all sessions,\n // plus 100% of sessions with an error\n replaysSessionSampleRate: 0.1,\n replaysOnErrorSampleRate: 1.0," + : "" + } +});`)} + +startTransition(() => { + hydrateRoot( + document, + + ${plus( + ``, + )} + + ); +});`), + ); +}; + +export const getManualServerEntryContent = (useInstrumentationAPI = false) => { + if (useInstrumentationAPI) { + return makeCodeSnippet(true, (unchanged, plus) => + unchanged(`${plus("import * as Sentry from '@sentry/react-router';")} +import { createReadableStreamFromReadable } from '@react-router/node'; +import { renderToPipeableStream } from 'react-dom/server'; +import { ServerRouter } from 'react-router'; + +${plus(`const handleRequest = Sentry.createSentryHandleRequest({ + ServerRouter, + renderToPipeableStream, + createReadableStreamFromReadable, +});`)} + +export default handleRequest; + +${plus(`export const handleError = Sentry.createSentryHandleError({ + logErrors: false +});`)} + +${plus(`// Enable automatic server-side instrumentation for loaders, actions, middleware +export const instrumentations = [Sentry.createSentryServerInstrumentation()];`)} + +// ... rest of your server entry`), + ); + } + + return makeCodeSnippet(true, (unchanged, plus) => + unchanged(`${plus("import * as Sentry from '@sentry/react-router';")} +import { createReadableStreamFromReadable } from '@react-router/node'; +import { renderToPipeableStream } from 'react-dom/server'; +import { ServerRouter } from 'react-router'; + +${plus(`const handleRequest = Sentry.createSentryHandleRequest({ + ServerRouter, + renderToPipeableStream, + createReadableStreamFromReadable, +});`)} + +export default handleRequest; + +${plus(`export const handleError = Sentry.createSentryHandleError({ + logErrors: false +});`)} + +// ... rest of your server entry`), + ); +}; + +export const getManualHandleRequestContent = () => { + return makeCodeSnippet(true, (unchanged, plus) => + unchanged(`${plus("import * as Sentry from '@sentry/react-router';")} +import { createReadableStreamFromReadable } from '@react-router/node'; +import { renderToPipeableStream } from 'react-dom/server'; +import { ServerRouter } from 'react-router'; + +${plus(`// Replace your existing handleRequest function with this Sentry-wrapped version: +const handleRequest = Sentry.createSentryHandleRequest({ + ServerRouter, + renderToPipeableStream, + createReadableStreamFromReadable, +});`)} + +${plus(`// If you have a custom handleRequest implementation, wrap it like this: +// export default Sentry.wrapSentryHandleRequest(yourCustomHandleRequest);`)} + +export default handleRequest;`), + ); +}; + +export const getManualServerInstrumentContent = ( + dsn: string, + enableTracing: boolean, + enableProfiling: boolean, + reduceDataCollection: boolean, +) => { + return makeCodeSnippet(true, (_unchanged, plus) => + plus( + generateServerInstrumentationCode( + dsn, + enableTracing, + enableProfiling, + reduceDataCollection, + ), + ), + ); +}; + +export const getManualReactRouterConfigContent = ( + isTS = true, + vitePluginImportPath: string = getSentryReactRouterVitePluginImportPath( + undefined, + ), +) => { + return makeCodeSnippet(true, (unchanged, plus) => + isTS + ? unchanged(`${plus( + 'import type { Config } from "@react-router/dev/config";', + )} +${plus(`import { sentryOnBuildEnd } from '${vitePluginImportPath}';`)} + +export default { + ${plus("ssr: true,")} + ${plus(`buildEnd: async ({ viteConfig, reactRouterConfig, buildManifest }) => { + await sentryOnBuildEnd({ viteConfig, reactRouterConfig, buildManifest }); + },`)} +} satisfies Config; + +// If you already have a buildEnd hook, modify it to call sentryOnBuildEnd: +// buildEnd: async (args) => { +// await yourExistingLogic(args); +// await sentryOnBuildEnd(args); +// }`) + : unchanged(`${plus( + `import { sentryOnBuildEnd } from '${vitePluginImportPath}';`, + )} + +export default { + ${plus("ssr: true,")} + ${plus(`buildEnd: async ({ viteConfig, reactRouterConfig, buildManifest }) => { + await sentryOnBuildEnd({ viteConfig, reactRouterConfig, buildManifest }); + },`)} +}; + +// If you already have a buildEnd hook, modify it to call sentryOnBuildEnd: +// buildEnd: async (args) => { +// await yourExistingLogic(args); +// await sentryOnBuildEnd(args); +// }`), + ); +}; + +export const getManualViteConfigContent = ( + orgSlug: string, + projectSlug: string, + vitePluginImportPath: string = getSentryReactRouterVitePluginImportPath( + undefined, + ), +) => { + return makeCodeSnippet(true, (unchanged, plus) => + unchanged(`${plus( + `import { sentryReactRouter } from '${vitePluginImportPath}';`, + )} +import { defineConfig } from 'vite'; + +export default defineConfig(config => { + return { + plugins: [ + // ... your existing plugins + ${plus(`sentryReactRouter({ + org: "${orgSlug}", + project: "${projectSlug}", + authToken: process.env.SENTRY_AUTH_TOKEN, + }, config),`)} + ], + ${plus(`optimizeDeps: { + exclude: ['@sentry/react-router'], + },`)} + }; +});`), + ); +}; + +/** The `package.json` scripts change, shown when the automatic edit fails. */ +export const getManualPackageJsonScriptsContent = () => + makeCodeSnippet(true, (unchanged, plus, minus) => + unchanged(`{ + scripts: { + ${minus('"start": "react-router-serve ./build/server/index.js"')} + ${plus( + '"start": "NODE_ENV=production NODE_OPTIONS=\'--import ./instrument.server.mjs\' react-router-serve ./build/server/index.js"', + )} + ${minus('"dev": "react-router dev"')} + ${plus( + '"dev": "NODE_OPTIONS=\'--import ./instrument.server.mjs\' react-router dev"', + )} + }, + // ... rest of your package.json +}`), + ); diff --git a/packages/cli/src/lib/wizard/remix/codemods/express-server.ts b/packages/cli/src/lib/wizard/remix/codemods/express-server.ts new file mode 100644 index 000000000..5b7b0d535 --- /dev/null +++ b/packages/cli/src/lib/wizard/remix/codemods/express-server.ts @@ -0,0 +1,46 @@ +/** + * Finds a custom Express server in a Remix app, so the wizard can import + * the instrumentation file there. + */ + +import { loadFile } from "magicast"; +import { statSync } from "node:fs"; + +import { findFile } from "../../../dsn/fs-utils.js"; + +// Try to find the Express server implementation that contains `createRequestHandler` from `@remix-run/express` +export async function findCustomExpressServerImplementation() { + const possiblePaths = [ + "server", + "server/index", + "app/server", + "app/server/index", + ]; + + for (const filePath of possiblePaths) { + const filename = await findFile(filePath); + + if (!filename) { + continue; + } + + const fileStat = statSync(filename); + + if (!fileStat.isFile()) { + continue; + } + + const fileMod = await loadFile(filename); + const createRequestHandlerImport = fileMod.imports.$items.find( + (imp) => + imp.from === "@remix-run/express" && + imp.imported === "createRequestHandler", + ); + + if (createRequestHandlerImport) { + return filename; + } + } + + return null; +} diff --git a/packages/cli/src/lib/wizard/remix/codemods/handle-error.ts b/packages/cli/src/lib/wizard/remix/codemods/handle-error.ts new file mode 100644 index 000000000..8d741f2f5 --- /dev/null +++ b/packages/cli/src/lib/wizard/remix/codemods/handle-error.ts @@ -0,0 +1,104 @@ +/** + * Adds or wraps `handleError` in a Remix `entry.server` file so server + * errors reach Sentry. + */ + +import type { ProxifiedModule } from "magicast"; +import type { namedTypes as t } from "ast-types"; + +import recast from "recast"; + +import { HANDLE_ERROR_TEMPLATE } from "../templates.js"; +import { getAfterImportsInsertionIndex, hasSentryContent } from "../utils.js"; + +import { clack } from "../../utils/clack/prompts.js"; +import chalk from "chalk"; + +export function instrumentHandleError( + originalEntryServerMod: ProxifiedModule, + serverEntryFilename: string, +): boolean { + const originalEntryServerModAST = originalEntryServerMod.$ast as t.Program; + + const handleErrorFunctionExport = originalEntryServerModAST.body.find( + (node) => { + return ( + node.type === "ExportNamedDeclaration" && + node.declaration?.type === "FunctionDeclaration" && + node.declaration.id?.name === "handleError" + ); + }, + ); + + const handleErrorFunctionVariableDeclarationExport = + originalEntryServerModAST.body.find( + (node) => + node.type === "ExportNamedDeclaration" && + node.declaration?.type === "VariableDeclaration" && + // @ts-expect-error - id should always have a name in this case + node.declaration.declarations[0].id.name === "handleError", + ); + + if ( + !handleErrorFunctionExport && + !handleErrorFunctionVariableDeclarationExport + ) { + clack.log.warn( + `Could not find function ${chalk.cyan("handleError")} in ${chalk.cyan( + serverEntryFilename, + )}. Creating one for you.`, + ); + + const implementation = recast.parse(HANDLE_ERROR_TEMPLATE).program.body[0]; + + originalEntryServerModAST.body.splice( + getAfterImportsInsertionIndex(originalEntryServerModAST), + 0, + recast.types.builders.exportNamedDeclaration(implementation), + ); + } else if ( + (handleErrorFunctionExport && + ["wrapHandleErrorWithSentry", "sentryHandleError"].some((util) => + hasSentryContent( + recast.print(handleErrorFunctionExport).code, + originalEntryServerMod.$code, + util, + ), + )) || + (handleErrorFunctionVariableDeclarationExport && + ["wrapHandleErrorWithSentry", "sentryHandleError"].some((util) => + hasSentryContent( + recast.print(handleErrorFunctionVariableDeclarationExport).code, + originalEntryServerMod.$code, + util, + ), + )) + ) { + return false; + } else if (handleErrorFunctionExport) { + const implementation = recast.parse(HANDLE_ERROR_TEMPLATE).program.body[0]; + + // If the current handleError function has a body, we need to merge the new implementation with the existing one + implementation.declarations[0].init.arguments[0].body.body.unshift( + // @ts-expect-error - declaration works here because the AST is proxified by magicast + ...handleErrorFunctionExport.declaration.body.body, + ); + + // @ts-expect-error - declaration works here because the AST is proxified by magicast + handleErrorFunctionExport.declaration = implementation; + } else if (handleErrorFunctionVariableDeclarationExport) { + const implementation = recast.parse(HANDLE_ERROR_TEMPLATE).program.body[0]; + + // If the current handleError function has a body, we need to merge the new implementation with the existing one + implementation.declarations[0].init.arguments[0].body.body.unshift( + // @ts-expect-error - declaration works here because the AST is proxified by magicast + ...handleErrorFunctionVariableDeclarationExport.declaration + .declarations[0].init.body.body, + ); + + // @ts-expect-error - declaration works here because the AST is proxified by magicast + handleErrorFunctionVariableDeclarationExport.declaration = implementation; + } + + return true; +} diff --git a/packages/cli/src/lib/wizard/remix/codemods/root.ts b/packages/cli/src/lib/wizard/remix/codemods/root.ts new file mode 100644 index 000000000..a132bdb35 --- /dev/null +++ b/packages/cli/src/lib/wizard/remix/codemods/root.ts @@ -0,0 +1,244 @@ +/** + * Wraps a Remix root route with `withSentry` and captures errors in its + * `ErrorBoundary`. + */ + +import recast from "recast"; +import path from "node:path"; + +import type { namedTypes as t } from "ast-types"; + +import { + builders, + generateCode, + loadFile, + type ProxifiedModule, + writeFile, +} from "magicast"; + +import { ERROR_BOUNDARY_TEMPLATE } from "../templates.js"; +import { hasSentryContent } from "../utils.js"; +import chalk from "chalk"; + +import { clack } from "../../utils/clack/prompts.js"; + +export function wrapAppWithSentry( + rootRouteAst: ProxifiedModule, + rootFileName: string, +) { + rootRouteAst.imports.$add({ + from: "@sentry/remix", + imported: "withSentry", + local: "withSentry", + }); + + recast.visit(rootRouteAst.$ast, { + visitExportDefaultDeclaration(path) { + if (path.value.declaration.type === "FunctionDeclaration") { + // Move the function declaration just before the default export + path.insertBefore(path.value.declaration); + + // Get the name of the function to be wrapped + const functionName: string = path.value.declaration.id.name as string; + + // Create the wrapped function call + const functionCall = recast.types.builders.callExpression( + recast.types.builders.identifier("withSentry"), + [recast.types.builders.identifier(functionName)], + ); + + // Replace the default export with the wrapped function call + path.value.declaration = functionCall; + } else if (path.value.declaration.type === "Identifier") { + const rootRouteExport = rootRouteAst.exports["default"]; + + const expressionToWrap = generateCode(rootRouteExport.$ast).code; + + rootRouteAst.exports["default"] = builders.raw( + `withSentry(${expressionToWrap})`, + ); + } else { + clack.log.warn( + chalk.yellow( + `Couldn't instrument ${chalk.bold( + rootFileName, + )} automatically. Wrap your default export with: ${chalk.dim( + "withSentry()", + )}\n`, + ), + ); + } + + this.traverse(path); + }, + }); +} + +export function isWithSentryAlreadyUsed( + rootRouteAst: ProxifiedModule, +): boolean { + // Check if withSentry is called anywhere in the code + let isUsed = false; + recast.visit(rootRouteAst.$ast, { + visitCallExpression(path) { + if ( + path.value.callee.type === "Identifier" && + path.value.callee.name === "withSentry" + ) { + isUsed = true; + return false; // Stop traversal + } + this.traverse(path); + return undefined; + }, + }); + return isUsed; +} + +export async function instrumentRoot(rootFileName: string): Promise { + const rootRouteAst = await loadFile( + path.join(process.cwd(), "app", rootFileName), + ); + + const exportsAst = rootRouteAst.exports.$ast as t.Program; + + const namedExports = exportsAst.body.filter( + (node): node is t.ExportNamedDeclaration => + node.type === "ExportNamedDeclaration", + ); + + let foundErrorBoundary = false as boolean; + const withSentryAlreadyUsed = isWithSentryAlreadyUsed(rootRouteAst); + + for (const namedExport of namedExports) { + const declaration = namedExport.declaration; + + if (!declaration) { + continue; + } + + if (declaration.type === "FunctionDeclaration") { + if (declaration.id?.name === "ErrorBoundary") { + foundErrorBoundary = true; + } + } else if (declaration.type === "VariableDeclaration") { + const declarations = declaration.declarations; + + for (const declaration of declarations) { + // @ts-expect-error - id should always have a name in this case + if (declaration.id?.name === "ErrorBoundary") { + foundErrorBoundary = true; + } + } + } + } + + if (!foundErrorBoundary) { + rootRouteAst.imports.$add({ + from: "@sentry/remix", + imported: "captureRemixErrorBoundaryError", + local: "captureRemixErrorBoundaryError", + }); + + rootRouteAst.imports.$add({ + from: "@remix-run/react", + imported: "useRouteError", + local: "useRouteError", + }); + + // Call wrapAppWithSentry if withSentry is not already used + if (!withSentryAlreadyUsed) { + wrapAppWithSentry(rootRouteAst, rootFileName); + } + + recast.visit(rootRouteAst.$ast, { + visitExportDefaultDeclaration(path) { + const implementation = recast.parse(ERROR_BOUNDARY_TEMPLATE).program + .body[0]; + + path.insertBefore( + recast.types.builders.exportDeclaration(false, implementation), + ); + + this.traverse(path); + }, + }); + // If there is already a ErrorBoundary export, and it doesn't have Sentry content + } else if (!hasSentryContent(rootFileName, rootRouteAst.$code)) { + rootRouteAst.imports.$add({ + from: "@sentry/remix", + imported: "captureRemixErrorBoundaryError", + local: "captureRemixErrorBoundaryError", + }); + + // Call wrapAppWithSentry if withSentry is not already used + if (!withSentryAlreadyUsed) { + wrapAppWithSentry(rootRouteAst, rootFileName); + } + + recast.visit(rootRouteAst.$ast, { + visitExportNamedDeclaration(path) { + // Find ErrorBoundary export + if (path.value.declaration?.id?.name === "ErrorBoundary") { + const errorBoundaryExport = path.value.declaration; + + let errorIdentifier = undefined as string | undefined; + + // check if useRouteError is called + recast.visit(errorBoundaryExport, { + visitVariableDeclaration(path) { + const variableDeclaration = path.value.declarations[0]; + const initializer = variableDeclaration.init; + + if ( + initializer.type === "CallExpression" && + initializer.callee.name === "useRouteError" + ) { + errorIdentifier = variableDeclaration.id.name; + } + + this.traverse(path); + }, + }); + + // We don't have an errorIdentifier, which means useRouteError is not called / imported + // We need to add it and capture the error + if (!errorIdentifier) { + rootRouteAst.imports.$add({ + from: "@remix-run/react", + imported: "useRouteError", + local: "useRouteError", + }); + + const useRouteErrorCall = recast.parse( + `const error = useRouteError();`, + ).program.body[0]; + + // Insert at the top of ErrorBoundary body + errorBoundaryExport.body.body.splice(0, 0, useRouteErrorCall); + } + + const captureErrorCall = recast.parse( + `captureRemixErrorBoundaryError(error);`, + ).program.body[0]; + + // Insert just before the the fallback page is returned + errorBoundaryExport.body.body.splice( + errorBoundaryExport.body.body.length - 1, + 0, + captureErrorCall, + ); + } + this.traverse(path); + }, + }); + } else if (!withSentryAlreadyUsed) { + // Even if we have Sentry content but withSentry is not used, we should still wrap the app + wrapAppWithSentry(rootRouteAst, rootFileName); + } + + await writeFile( + rootRouteAst.$ast, + path.join(process.cwd(), "app", rootFileName), + ); +} diff --git a/packages/cli/src/lib/wizard/remix/remix-wizard.ts b/packages/cli/src/lib/wizard/remix/remix-wizard.ts new file mode 100644 index 000000000..b64b7e5e9 --- /dev/null +++ b/packages/cli/src/lib/wizard/remix/remix-wizard.ts @@ -0,0 +1,317 @@ +/** + * The Remix (v2) setup wizard: installs `@sentry/remix`, instruments the + * client and server entries and the root route, writes the server + * instrumentation file, and sets up source map uploads. + */ + +import { clack } from "../utils/clack/prompts.js"; +import chalk from "chalk"; +import path from "node:path"; + +import { traceStep, withTelemetry } from "../telemetry.js"; +import { findFile } from "../../dsn/fs-utils.js"; +import { + addDotEnvSentryBuildPluginFile, + addSentryCliConfig, + askShouldCreateExamplePage, + confirmContinueIfNoOrDirtyGitRepo, + ensurePackageIsInstalled, + featureSelectionPrompt, + getOrAskForProjectData, + getPackageDotJson, + installPackage, + printSdkV11MigrationGuideIfOutdated, + isUsingTypeScript, + printWelcome, + rcCliSetupConfig, + runPrettierIfInstalled, +} from "../utils/clack/index.js"; +import { + askShouldReduceDataCollection, + sdkSupportsDataCollection, +} from "../utils/data-collection.js"; +import { debug } from "../utils/debug.js"; +import { + getPackageVersion, + hasPackageInstalled, +} from "../utils/package-json.js"; +import type { WizardOptions } from "../utils/types.js"; +import { offerProjectScopedMcpConfig } from "../utils/clack/mcp-config.js"; +import { createExamplePage } from "./sdk-example.js"; +import { + createServerInstrumentationFile, + initializeSentryOnEntryClient, + insertServerInstrumentationFile, + instrumentRootRoute, + instrumentSentryOnEntryServer, + isRemixV2, + runRemixReveal, + updateBuildScript, + updateStartScript, +} from "./sdk-setup.js"; +import { isHydrogenApp } from "./utils.js"; +import { abortIfSpotlightNotSupported } from "../utils/abort-if-sportlight-not-supported.js"; +import { warnIfNodeVersionUnsupportedBySdkV11 } from "../utils/node-version.js"; + +export async function runRemixWizard(options: WizardOptions): Promise { + return await withTelemetry( + { + enabled: options.telemetryEnabled, + integration: "remix", + wizardOptions: options, + }, + () => runRemixWizardWithTelemetry(options), + ); +} + +async function runRemixWizardWithTelemetry( + options: WizardOptions, +): Promise { + const { telemetryEnabled, forceInstall } = options; + + printWelcome({ + wizardName: "Sentry Remix Wizard", + telemetryEnabled, + }); + + const packageJson = await getPackageDotJson(); + + if (!isRemixV2(packageJson)) { + clack.log.error( + `Sentry only supports Remix v2 and above. Please upgrade your Remix version to use Sentry.`, + ); + return; + } + + warnIfNodeVersionUnsupportedBySdkV11(); + + await confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: options.ignoreGitChanges, + cwd: undefined, + }); + + // We expect `@remix-run/dev` to be installed for every Remix project + await ensurePackageIsInstalled(packageJson, "@remix-run/dev", "Remix"); + + const projectData = await getOrAskForProjectData(options, "javascript-remix"); + + if (projectData.spotlight) { + return await abortIfSpotlightNotSupported("Remix"); + } + + const { selectedProject, authToken, sentryUrl, selfHosted } = projectData; + + printSdkV11MigrationGuideIfOutdated("@sentry/remix", packageJson); + + await installPackage({ + packageName: "@sentry/remix@^11", + packageNameDisplayLabel: "@sentry/remix", + alreadyInstalled: hasPackageInstalled("@sentry/remix", 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/remix", + await getPackageDotJson(), + ); + + // From v11 on, the SDK collects rich context by default, so offer to + // reduce collection of data that can identify users. + const reduceDataCollection = + sdkSupportsDataCollection(installedSdkVersion, "^11") && + (await askShouldReduceDataCollection()); + + const dsn = selectedProject.keys[0].dsn.public; + + const isTS = isUsingTypeScript(); + const viteConfig = await findFile("vite.config"); + const selectedFeatures = await featureSelectionPrompt([ + { + id: "performance", + prompt: `Do you want to enable ${chalk.bold( + "Tracing", + )} to track the performance of your application?`, + enabledHint: "recommended", + }, + { + id: "replay", + prompt: `Do you want to enable ${chalk.bold( + "Session Replay", + )} to get a video-like reproduction of errors during a user session?`, + enabledHint: "recommended, but increases bundle size", + }, + ] as const); + + if (viteConfig) { + // The source maps wizard's Vite setup isn't in the CLI yet, so point at + // the manual steps and write the auth token the plugin reads. + await traceStep( + "Update vite configuration for sourcemap uploads", + async () => { + clack.log.info( + `To upload source maps, add the Sentry Vite plugin to your ${chalk.cyan( + path.basename(viteConfig), + )} using the instructions at https://docs.sentry.io/platforms/javascript/guides/remix/sourcemaps/`, + ); + await addDotEnvSentryBuildPluginFile(authToken); + }, + ); + } else { + await traceStep("Update build script for sourcemap uploads", async () => { + try { + await updateBuildScript({ + org: selectedProject.organization.slug, + project: selectedProject.slug, + url: selfHosted ? sentryUrl : undefined, + isHydrogen: isHydrogenApp(packageJson), + }); + + await addSentryCliConfig({ authToken }, rcCliSetupConfig); + } catch (e) { + clack.log + .warn(`Could not update build script to generate and upload sourcemaps. + Please update your build script manually using instructions from https://docs.sentry.io/platforms/javascript/guides/remix/sourcemaps/`); + debug(e); + } + }); + } + + await traceStep("Instrument root route", async () => { + try { + await instrumentRootRoute(isTS); + } catch (e) { + clack.log.warn(`Could not instrument root route. + Please do it manually using instructions from https://docs.sentry.io/platforms/javascript/guides/remix/manual-setup/`); + debug(e); + } + }); + + traceStep("Reveal missing entry files", () => { + try { + runRemixReveal(isTS); + } catch (e) { + clack.log.warn(`Could not run 'npx remix reveal'. + Please create your entry files manually`); + debug(e); + } + }); + + await traceStep("Initialize Sentry on client entry", async () => { + try { + await initializeSentryOnEntryClient( + dsn, + isTS, + selectedFeatures, + reduceDataCollection, + ); + } catch (e) { + clack.log.warn(`Could not initialize Sentry on client entry. + Please do it manually using instructions from https://docs.sentry.io/platforms/javascript/guides/remix/manual-setup/`); + debug(e); + } + }); + + let instrumentationFile = "" as string; + + await traceStep("Create server instrumentation file", async () => { + try { + instrumentationFile = await createServerInstrumentationFile( + dsn, + selectedFeatures, + reduceDataCollection, + ); + } catch (e) { + clack.log.warn( + "Could not create a server instrumentation file. Please do it manually using instructions from https://docs.sentry.io/platforms/javascript/guides/remix/manual-setup/", + ); + debug(e); + } + }); + + let serverFileInstrumented = false as boolean; + + await traceStep( + "Create server instrumentation file and import it", + async () => { + try { + serverFileInstrumented = await insertServerInstrumentationFile( + dsn, + selectedFeatures, + reduceDataCollection, + ); + } catch (e) { + clack.log.warn( + "Could not create a server instrumentation file. Please do it manually using instructions from https://docs.sentry.io/platforms/javascript/guides/remix/manual-setup/", + ); + debug(e); + } + }, + ); + + if (!serverFileInstrumented && instrumentationFile) { + await traceStep( + "Update `start` script to import instrumentation file.", + async () => { + try { + await updateStartScript(instrumentationFile); + } catch (e) { + clack.log + .warn(`Could not automatically add Sentry initialization to server entry. + Please do it manually using instructions from https://docs.sentry.io/platforms/javascript/guides/remix/manual-setup/`); + debug(e); + } + }, + ); + } + + await traceStep("Instrument server `handleError`", async () => { + try { + await instrumentSentryOnEntryServer(isTS); + } catch (e) { + clack.log.warn(`Could not initialize Sentry on server entry. + Please do it manually using instructions from https://docs.sentry.io/platforms/javascript/guides/remix/manual-setup/`); + debug(e); + } + }); + + const shouldCreateExamplePage = await askShouldCreateExamplePage(); + + if (shouldCreateExamplePage) { + await traceStep("Create example page", async () => { + await createExamplePage({ + isTS, + selfHosted, + orgSlug: selectedProject.organization.slug, + projectId: selectedProject.id, + url: sentryUrl, + }); + }); + } + + 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(` +${chalk.green( + "Sentry has been successfully configured for your Remix project.", +)} + +${chalk.cyan("You can now deploy your project to see Sentry in action.")} + +${chalk.cyan( + `To learn more about how to use Sentry with Remix, visit our documentation: +https://docs.sentry.io/platforms/javascript/guides/remix/`, +)}`); +} + +/** + * Offers to add a project-scoped MCP server configuration for the Sentry MCP. + * Supports Cursor, VS Code, and Claude Code. + */ diff --git a/packages/cli/src/lib/wizard/remix/sdk-example.ts b/packages/cli/src/lib/wizard/remix/sdk-example.ts new file mode 100644 index 000000000..6ebaf06b5 --- /dev/null +++ b/packages/cli/src/lib/wizard/remix/sdk-example.ts @@ -0,0 +1,266 @@ +/** + * Writes the example page that throws a test error in a Remix app. + */ + +import { existsSync, mkdirSync, promises } from "node:fs"; +import path from "node:path"; +import { clack } from "../utils/clack/prompts.js"; + +/** + * Creates an example Remix page to test Sentry + */ +export async function createExamplePage(options: { + selfHosted: boolean; + orgSlug: string; + projectId: string; + url: string; + isTS: boolean; +}) { + const routesPath = "app/routes"; + + if (!existsSync(routesPath)) { + mkdirSync(routesPath, { recursive: true }); + } + + const exampleRoutePath = `app/routes/sentry-example-page.${ + options.isTS ? "ts" : "js" + }x`; + + if (existsSync(exampleRoutePath)) { + clack.log.warn( + `It seems like a sentry example page already exists (${path.basename( + exampleRoutePath, + )}). Skipping creation of example route.`, + ); + return; + } + + await promises.writeFile( + exampleRoutePath, + getSentryExamplePageContents(options), + ); + + clack.log.info(`Created sentry example page at ${exampleRoutePath}.`); +} + +export function getSentryExamplePageContents(options: { + selfHosted: boolean; + orgSlug: string; + projectId: string; + url: string; + isTS?: boolean; +}) { + const issuesPageLink = options.selfHosted + ? `${options.url}organizations/${options.orgSlug}/issues/?project=${options.projectId}` + : `https://${options.orgSlug}.sentry.io/issues/?project=${options.projectId}`; + + return `import * as Sentry from "@sentry/remix"; +import { useState, useEffect } from "react"; + +class SentryExampleFrontendError extends Error { + constructor(message${options.isTS ? ": string | undefined" : ""}) { + super(message); + this.name = "SentryExampleFrontendError"; + } +} + +export const meta = () => { + return [ + { title: "sentry-example-page" }, + ]; +} + +export default function SentryExamplePage() { + const [hasSentError, setHasSentError] = useState(false); + const [isConnected, setIsConnected] = useState(true); + + useEffect(() => { + async function checkConnectivity() { + const result = await Sentry.diagnoseSdkConnectivity(); + setIsConnected(result !== 'sentry-unreachable'); + } + checkConnectivity(); + }, [setIsConnected]); + + return ( +
+
+
+ + + +

+ sentry-example-page +

+ +

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

+ + + + {hasSentError ? ( +

+ Sample error was sent to Sentry. +

+ ) : !isConnected ? ( +
+

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

+
+ ) : ( +
+ )} + +
+
+ + {/* Not for production use! We're just saving you from having to delete an extra CSS file ;) */} + +
+ ); +} + +const styles = \` + main { + display: flex; + min-height: 100vh; + flex-direction: column; + justify-content: center; + align-items: center; + gap: 16px; + padding: 16px; + font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", sans-serif; + } + + h1 { + padding: 0px 4px; + border-radius: 4px; + background-color: rgba(24, 20, 35, 0.03); + font-family: monospace; + font-size: 20px; + line-height: 1.2; + } + + p { + margin: 0; + font-size: 20px; + } + + a { + color: #6341F0; + text-decoration: underline; + cursor: pointer; + + @media (prefers-color-scheme: dark) { + color: #B3A1FF; + } + } + + button { + border-radius: 8px; + color: white; + cursor: pointer; + background-color: #553DB8; + border: none; + padding: 0; + margin-top: 4px; + + & > span { + display: inline-block; + padding: 12px 16px; + border-radius: inherit; + font-size: 20px; + font-weight: bold; + line-height: 1; + background-color: #7553FF; + border: 1px solid #553DB8; + transform: translateY(-4px); + } + + &:hover > span { + transform: translateY(-8px); + } + + &:active > span { + transform: translateY(0); + } + + &:disabled { + cursor: not-allowed; + opacity: 0.6; + + & > span { + transform: translateY(0); + border: none; + } + } + } + + .description { + text-align: center; + color: #6E6C75; + max-width: 500px; + line-height: 1.5; + font-size: 20px; + + @media (prefers-color-scheme: dark) { + color: #A49FB5; + } + } + + .flex-spacer { + flex: 1; + } + + .success { + padding: 12px 16px; + border-radius: 8px; + font-size: 20px; + line-height: 1; + background-color: #00F261; + border: 1px solid #00BF4D; + color: #181423; + } + + .success_placeholder { + height: 46px; + } + + .connectivity-error { + padding: 12px 16px; + background-color: #E50045; + border-radius: 8px; + width: 500px; + color: #FFFFFF; + border: 1px solid #A80033; + text-align: center; + margin: 0; + } + + .connectivity-error a { + color: #FFFFFF; + text-decoration: underline; + } +\`; +`; +} diff --git a/packages/cli/src/lib/wizard/remix/sdk-setup.ts b/packages/cli/src/lib/wizard/remix/sdk-setup.ts new file mode 100644 index 000000000..b17bda52e --- /dev/null +++ b/packages/cli/src/lib/wizard/remix/sdk-setup.ts @@ -0,0 +1,579 @@ +/** + * Setup steps of the Remix wizard: revealing the entry files, writing and + * importing the server instrumentation file, and updating the `build` and + * `start` scripts. + */ + +import { formatError } from "../../errors.js"; +import type { namedTypes as t } from "ast-types"; + +import type { Proxified, ProxifiedModule } from "magicast"; + +import { existsSync, promises, writeFileSync } from "node:fs"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; +import { execSync } from "node:child_process"; + +import { clack } from "../utils/clack/prompts.js"; +import chalk from "chalk"; +import { gte, minVersion } from "semver"; + +import { + builders, + generateCode, + loadFile, + parseModule, + writeFile, +} from "magicast"; +import type { PackageDotJson } from "../utils/package-json.js"; +import { getPackageVersion } from "../utils/package-json.js"; +import { getDataCollectionSnippet } from "../utils/data-collection.js"; +import { + getAfterImportsInsertionIndex, + hasSentryContent, + serverHasInstrumentationImport, +} from "./utils.js"; +import { instrumentRoot } from "./codemods/root.js"; +import { instrumentHandleError } from "./codemods/handle-error.js"; +import { getPackageDotJson } from "../utils/clack/index.js"; +import { findCustomExpressServerImplementation } from "./codemods/express-server.js"; + +export type PartialRemixConfig = { + unstable_dev?: boolean; +}; + +const REMIX_CONFIG_FILE = "remix.config.js"; +const REMIX_REVEAL_COMMAND = "npx remix reveal"; + +export function runRemixReveal(isTS: boolean): void { + // Check if entry files already exist + const clientEntryFilename = `entry.client.${isTS ? "tsx" : "jsx"}`; + const serverEntryFilename = `entry.server.${isTS ? "tsx" : "jsx"}`; + + const clientEntryPath = path.join(process.cwd(), "app", clientEntryFilename); + const serverEntryPath = path.join(process.cwd(), "app", serverEntryFilename); + + if (existsSync(clientEntryPath) && existsSync(serverEntryPath)) { + clack.log.info( + `Found entry files ${chalk.cyan(clientEntryFilename)} and ${chalk.cyan( + serverEntryFilename, + )}.`, + ); + } else { + clack.log.info( + `Couldn't find entry files in your project. Trying to run ${chalk.cyan( + REMIX_REVEAL_COMMAND, + )}...`, + ); + + clack.log.info(execSync(REMIX_REVEAL_COMMAND).toString()); + } +} + +interface SdkAstOptions { + dsn: string; + tracesSampleRate?: number; + replaysSessionSampleRate?: number; + replaysOnErrorSampleRate?: number; + integrations?: Array; +} + +function getInitCallArgs( + dsn: string, + type: "client" | "server", + selectedFeatures: { + performance: boolean; + replay: boolean; + }, +) { + const initCallArgs: SdkAstOptions = { + dsn, + }; + + // Adding tracing sample rate for both client and server + if (selectedFeatures.performance) { + initCallArgs.tracesSampleRate = 1.0; + } + + // Adding integrations and replay options only for client + if ( + type === "client" && + (selectedFeatures.performance || selectedFeatures.replay) + ) { + initCallArgs.integrations = [] as Array; + + if (selectedFeatures.performance) { + initCallArgs.integrations.push( + builders.functionCall( + "browserTracingIntegration", + builders.raw("{ useEffect, useLocation, useMatches }"), + ), + ); + } + + if (selectedFeatures.replay) { + initCallArgs.integrations.push( + builders.functionCall("replayIntegration", { + maskAllText: true, + blockAllMedia: true, + }), + ); + + initCallArgs.replaysSessionSampleRate = 0.1; + initCallArgs.replaysOnErrorSampleRate = 1.0; + } + } + + return initCallArgs; +} + +/** + * Splices the PII-reducing `dataCollection` preset (with its comment block) + * into generated init code. Magicast cannot express comments inside an + * options object, so the block is inserted textually before the closing `})`. + */ +function withDataCollectionPreset( + generatedInitCode: string, + reduceDataCollection: boolean, +): string { + if (!reduceDataCollection) { + return generatedInitCode; + } + + return generatedInitCode.replace( + /\n\}\)$/, + `,\n${getDataCollectionSnippet(" ")}\n})`, + ); +} + +function insertClientInitCall( + dsn: string, + originalHooksMod: ProxifiedModule, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + reduceDataCollection: boolean, +): void { + const initCallArgs = getInitCallArgs(dsn, "client", selectedFeatures); + const initCall = builders.functionCall("init", initCallArgs); + + const generatedInitCode = withDataCollectionPreset( + generateCode(initCall).code, + reduceDataCollection, + ); + + const originalHooksModAST = originalHooksMod.$ast as t.Program; + const initCallInsertionIndex = + getAfterImportsInsertionIndex(originalHooksModAST); + + originalHooksModAST.body.splice( + initCallInsertionIndex, + 0, + // @ts-expect-error - string works here because the AST is proxified by magicast + generatedInitCode, + ); +} + +export function generateServerInstrumentationFile( + dsn: string, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + reduceDataCollection: boolean, +) { + // create an empty file named `instrument.server.mjs` + const instrumentationFile = "instrumentation.server.mjs"; + const instrumentationFileMod = parseModule(""); + + instrumentationFileMod.imports.$add({ + from: "@sentry/remix", + imported: "*", + local: "Sentry", + }); + + const initCallArgs = getInitCallArgs(dsn, "server", selectedFeatures); + const initCall = builders.functionCall("Sentry.init", initCallArgs); + + const generatedInitCode = withDataCollectionPreset( + generateCode(initCall).code, + reduceDataCollection, + ); + + const instrumentationFileModAST = instrumentationFileMod.$ast as t.Program; + + const initCallInsertionIndex = getAfterImportsInsertionIndex( + instrumentationFileModAST, + ); + + instrumentationFileModAST.body.splice( + initCallInsertionIndex, + 0, + // @ts-expect-error - string works here because the AST is proxified by magicast + generatedInitCode, + ); + + return { instrumentationFile, instrumentationFileMod }; +} + +export async function createServerInstrumentationFile( + dsn: string, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + reduceDataCollection: boolean, +) { + const { instrumentationFile, instrumentationFileMod } = + generateServerInstrumentationFile( + dsn, + selectedFeatures, + reduceDataCollection, + ); + + await writeFile(instrumentationFileMod.$ast, instrumentationFile); + + return instrumentationFile; +} + +export async function insertServerInstrumentationFile( + dsn: string, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + reduceDataCollection: boolean, +) { + const instrumentationFile = await createServerInstrumentationFile( + dsn, + selectedFeatures, + reduceDataCollection, + ); + + const expressServerPath = await findCustomExpressServerImplementation(); + + if (!expressServerPath) { + return false; + } + + const originalExpressServerMod = await loadFile(expressServerPath); + + if ( + serverHasInstrumentationImport( + expressServerPath, + originalExpressServerMod.$code, + ) + ) { + clack.log.warn( + `File ${chalk.cyan( + path.basename(expressServerPath), + )} already contains instrumentation import. +Skipping adding instrumentation functionality to ${chalk.cyan( + path.basename(expressServerPath), + )}.`, + ); + + return true; + } + + originalExpressServerMod.$code = `import './${instrumentationFile}';\n${originalExpressServerMod.$code}`; + + writeFileSync(expressServerPath, originalExpressServerMod.$code); + + return true; +} + +export function isRemixV2(packageJson: PackageDotJson): boolean { + const remixVersion = getPackageVersion("@remix-run/react", packageJson); + if (!remixVersion) { + return false; + } + + const minVer = minVersion(remixVersion); + + if (!minVer) { + return false; + } + + return gte(minVer, "2.0.0"); +} + +export async function loadRemixConfig(): Promise { + const configFilePath = path.join(process.cwd(), REMIX_CONFIG_FILE); + + try { + if (!existsSync(configFilePath)) { + return {}; + } + + const configUrl = pathToFileURL(configFilePath).href; + const remixConfigModule = (await import(configUrl)) as { + default?: PartialRemixConfig; + }; + + return remixConfigModule.default ?? {}; + } catch (e: unknown) { + clack.log.error(`Couldn't load ${REMIX_CONFIG_FILE}.`); + clack.log.info(chalk.dim(formatError(e))); + + return {}; + } +} + +export async function instrumentRootRoute(isTS?: boolean): Promise { + const rootFilename = `root.${isTS ? "tsx" : "jsx"}`; + + await instrumentRoot(rootFilename); + + clack.log.success( + `Successfully instrumented root route ${chalk.cyan(rootFilename)}.`, + ); +} + +export async function updateBuildScript(args: { + org: string; + project: string; + url?: string | undefined; + isHydrogen: boolean; +}): Promise { + const packageJson = await getPackageDotJson(); + + if (!packageJson.scripts) { + packageJson.scripts = {}; + } + + const buildCommand = args.isHydrogen + ? "shopify hydrogen build" + : "remix build"; + + const instrumentedBuildCommand = + `${buildCommand} --sourcemap && npx @sentry/remix --upload-sourcemaps --org ${args.org} --project ${args.project}` + + (args.url ? ` --url ${args.url}` : "") + + (args.isHydrogen ? " --buildPath ./dist" : ""); + + if ( + packageJson.scripts["build"]?.includes("@sentry/remix --upload-sourcemaps") + ) { + // Already set up by an earlier run; replacing again would duplicate it. + clack.log.info( + `${chalk.cyan("build")} script already uploads sourcemaps, skipping.`, + ); + return; + } + + if (!packageJson.scripts["build"]) { + packageJson.scripts["build"] = instrumentedBuildCommand; + } else if (packageJson.scripts["build"].includes(buildCommand)) { + packageJson.scripts["build"] = packageJson.scripts["build"].replace( + buildCommand, + instrumentedBuildCommand, + ); + } else { + throw new Error( + "`build` script doesn't contain a known build command. Please update it manually.", + ); + } + + await promises.writeFile( + path.join(process.cwd(), "package.json"), + JSON.stringify(packageJson, null, 2), + ); + + clack.log.success( + `Successfully updated ${chalk.cyan("build")} script in ${chalk.cyan( + "package.json", + )} to generate and upload sourcemaps.`, + ); +} + +export function updateEntryClientMod( + originalEntryClientMod: ProxifiedModule, + dsn: string, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + reduceDataCollection: boolean, +): ProxifiedModule { + const imports = ["init"]; + if (selectedFeatures.replay) { + imports.push("replayIntegration"); + } + if (selectedFeatures.performance) { + imports.push("browserTracingIntegration"); + } + originalEntryClientMod.imports.$add({ + from: "@sentry/remix", + imported: imports.join(", "), + }); + + if (selectedFeatures.performance) { + originalEntryClientMod.imports.$add({ + from: "@remix-run/react", + imported: "useLocation", + local: "useLocation", + }); + + originalEntryClientMod.imports.$add({ + from: "@remix-run/react", + imported: "useMatches", + local: "useMatches", + }); + + originalEntryClientMod.imports.$add({ + from: "react", + imported: "useEffect", + local: "useEffect", + }); + } + + insertClientInitCall( + dsn, + originalEntryClientMod, + selectedFeatures, + reduceDataCollection, + ); + + return originalEntryClientMod; +} + +export async function initializeSentryOnEntryClient( + dsn: string, + isTS: boolean, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + reduceDataCollection: boolean, +): Promise { + const clientEntryFilename = `entry.client.${isTS ? "tsx" : "jsx"}`; + + const originalEntryClient = path.join( + process.cwd(), + "app", + clientEntryFilename, + ); + + const originalEntryClientMod = await loadFile(originalEntryClient); + + if (hasSentryContent(originalEntryClient, originalEntryClientMod.$code)) { + return; + } + + const updatedEntryClientMod = updateEntryClientMod( + originalEntryClientMod, + dsn, + selectedFeatures, + reduceDataCollection, + ); + + await writeFile( + updatedEntryClientMod.$ast, + path.join(process.cwd(), "app", clientEntryFilename), + ); + + clack.log.success( + `Successfully initialized Sentry on client entry point ${chalk.cyan( + clientEntryFilename, + )}`, + ); +} + +export async function updateStartScript(instrumentationFile: string) { + const packageJson = await getPackageDotJson(); + + if (!packageJson.scripts?.["start"]) { + throw new Error( + "Couldn't find a `start` script in your package.json. Please add one manually.", + ); + } + + if (packageJson.scripts["start"].includes("NODE_OPTIONS")) { + clack.log.warn( + `Found existing NODE_OPTIONS in ${chalk.cyan( + "start", + )} script. Skipping adding Sentry initialization.`, + ); + + return; + } + + if ( + !packageJson.scripts["start"].includes("remix-serve") && + // Adding a following empty space not to match a path that includes `node` + !packageJson.scripts["start"].includes("node ") + ) { + clack.log.warn( + `Found a ${chalk.cyan("start")} script that doesn't use ${chalk.cyan( + "remix-serve", + )} or ${chalk.cyan("node")}. Skipping adding Sentry initialization.`, + ); + + return; + } + + const startCommand = packageJson.scripts["start"]; + + packageJson.scripts["start"] = + `NODE_OPTIONS='--import ./${instrumentationFile}' ${startCommand}`; + + await promises.writeFile( + path.join(process.cwd(), "package.json"), + JSON.stringify(packageJson, null, 2), + ); + + clack.log.success( + `Successfully updated ${chalk.cyan("start")} script in ${chalk.cyan( + "package.json", + )} to include Sentry initialization on start.`, + ); +} + +export async function instrumentSentryOnEntryServer( + isTS: boolean, +): Promise { + const serverEntryFilename = `entry.server.${isTS ? "tsx" : "jsx"}`; + + const originalEntryServer = path.join( + process.cwd(), + "app", + serverEntryFilename, + ); + + const originalEntryServerMod = await loadFile(originalEntryServer); + + if (hasSentryContent(originalEntryServer, originalEntryServerMod.$code)) { + return; + } + + originalEntryServerMod.imports.$add({ + from: "@sentry/remix", + imported: "*", + local: "Sentry", + }); + + const handleErrorInstrumented = instrumentHandleError( + originalEntryServerMod, + serverEntryFilename, + ); + + if (handleErrorInstrumented) { + clack.log.success( + `Instrumented ${chalk.cyan("handleError")} in ${chalk.cyan( + serverEntryFilename, + )}`, + ); + } + + await writeFile( + originalEntryServerMod.$ast, + path.join(process.cwd(), "app", serverEntryFilename), + ); + + clack.log.success( + `Successfully initialized Sentry on server entry point ${chalk.cyan( + serverEntryFilename, + )}.`, + ); +} diff --git a/packages/cli/src/lib/wizard/remix/templates.ts b/packages/cli/src/lib/wizard/remix/templates.ts new file mode 100644 index 000000000..5606bff3b --- /dev/null +++ b/packages/cli/src/lib/wizard/remix/templates.ts @@ -0,0 +1,15 @@ +/** + * Code templates the Remix codemods insert. + */ + +export const ERROR_BOUNDARY_TEMPLATE = `const ErrorBoundary = () => { + const error = useRouteError(); + captureRemixErrorBoundaryError(error); + return
Something went wrong
; +}; +`; + +export const HANDLE_ERROR_TEMPLATE = `const handleError = Sentry.wrapHandleErrorWithSentry((error, { request }) => { + // Custom handleError implementation +}); +`; diff --git a/packages/cli/src/lib/wizard/remix/utils.ts b/packages/cli/src/lib/wizard/remix/utils.ts new file mode 100644 index 000000000..b602a374b --- /dev/null +++ b/packages/cli/src/lib/wizard/remix/utils.ts @@ -0,0 +1,102 @@ +/** + * Helpers shared by the Remix wizard steps: detecting Sentry code, + * Hydrogen apps, and where to insert new statements. + */ + +import type { namedTypes as t } from "ast-types"; + +import path from "node:path"; + +import { clack } from "../utils/clack/prompts.js"; +import chalk from "chalk"; +import { + type PackageDotJson, + hasPackageInstalled, +} from "../utils/package-json.js"; + +export const POSSIBLE_SERVER_INSTRUMENTATION_PATHS = [ + "./instrumentation", + "./instrumentation.server", +]; + +export function hasSentryContent( + fileName: string, + fileContent: string, + expectedContent = "@sentry/remix", +): boolean { + const includesContent = fileContent.includes(expectedContent); + + if (includesContent) { + clack.log.warn( + `File ${chalk.cyan( + path.basename(fileName), + )} already contains ${expectedContent}. +Skipping adding Sentry functionality to ${chalk.cyan( + path.basename(fileName), + )}.`, + ); + } + + return includesContent; +} + +export function serverHasInstrumentationImport( + serverFileName: string, + serverFileContent: string, +): boolean { + const includesServerInstrumentationImport = + POSSIBLE_SERVER_INSTRUMENTATION_PATHS.some((path) => + serverFileContent.includes(path), + ); + + if (includesServerInstrumentationImport) { + clack.log.warn( + `File ${chalk.cyan( + path.basename(serverFileName), + )} already contains instrumentation import. +Skipping adding instrumentation functionality to ${chalk.cyan( + path.basename(serverFileName), + )}.`, + ); + } + + return includesServerInstrumentationImport; +} + +/** + * We want to insert the init call on top of the file, before any other imports. + */ +export function getBeforeImportsInsertionIndex( + originalHooksModAST: t.Program, +): number { + for (let x = 0; x < originalHooksModAST.body.length - 1; x++) { + const node = originalHooksModAST.body[x]; + if ( + node?.type === "ImportDeclaration" && + node.source.value === "@sentry/remix" + ) { + return x + 1; + } + } + + return 0; +} + +/** + * We want to insert the handleError function just after all imports + */ +export function getAfterImportsInsertionIndex( + originalEntryServerModAST: t.Program, +): number { + for (let x = originalEntryServerModAST.body.length - 1; x >= 0; x--) { + if (originalEntryServerModAST.body[x]?.type === "ImportDeclaration") { + return x + 1; + } + } + + return 0; +} + +export function isHydrogenApp(packageJson: PackageDotJson): boolean { + return hasPackageInstalled("@shopify/hydrogen", packageJson); +} diff --git a/packages/cli/src/lib/wizard/run.ts b/packages/cli/src/lib/wizard/run.ts index eaa33e567..678b2083a 100644 --- a/packages/cli/src/lib/wizard/run.ts +++ b/packages/cli/src/lib/wizard/run.ts @@ -56,6 +56,20 @@ const WIZARD_RUNNERS: Partial> = { const { runNextjsWizard } = await import("./nextjs/nextjs-wizard.js"); await runNextjsWizard(options); }, + remix: async (options) => { + const { runRemixWizard } = await import("./remix/remix-wizard.js"); + await runRemixWizard(options); + }, + reactRouter: async (options) => { + const { runReactRouterWizard } = + await import("./react-router/react-router-wizard.js"); + await runReactRouterWizard(options); + }, + sveltekit: async (options) => { + const { runSvelteKitWizard } = + await import("./sveltekit/sveltekit-wizard.js"); + await runSvelteKitWizard(options); + }, android: async (options) => { const { runAndroidWizard } = await import("./android/android-wizard.js"); await runAndroidWizard(options); diff --git a/packages/cli/src/lib/wizard/sveltekit/sdk-example.ts b/packages/cli/src/lib/wizard/sveltekit/sdk-example.ts new file mode 100644 index 000000000..7fcae593a --- /dev/null +++ b/packages/cli/src/lib/wizard/sveltekit/sdk-example.ts @@ -0,0 +1,63 @@ +/** + * Writes the example page and API route that throw a test error in a + * SvelteKit app. + */ + +import { existsSync, mkdirSync, promises } from "node:fs"; +import path from "node:path"; +import { clack } from "../utils/clack/prompts.js"; + +import type { PartialBackwardsForwardsCompatibleSvelteConfig } from "./sdk-setup/svelte-config.js"; +import { + getSentryExampleApiRoute, + getSentryExampleSveltePage, +} from "./templates.js"; + +/** + * Creates example page and API route to test Sentry + */ +export async function createExamplePage( + svelteConfig: PartialBackwardsForwardsCompatibleSvelteConfig, + projectProps: { + selfHosted: boolean; + url: string; + orgSlug: string; + projectId: string; + isUsingSvelte5: boolean; + }, +): Promise { + const routesDirectory = svelteConfig.kit?.files?.routes || "src/routes"; + const exampleRoutePath = path.resolve( + path.join(routesDirectory, "sentry-example-page"), + ); + + if (!existsSync(routesDirectory)) { + clack.log.warn( + `Couldn't find your routes directory. Creating it now: ${routesDirectory}`, + ); + mkdirSync(routesDirectory, { recursive: true }); + } + + if (!existsSync(exampleRoutePath)) { + mkdirSync(exampleRoutePath); + } else { + clack.log.warn( + `It seems like a sentry example page already exists (${path.basename( + exampleRoutePath, + )}). Skipping creation of example route.`, + ); + return; + } + + await promises.writeFile( + path.join(exampleRoutePath, "+page.svelte"), + getSentryExampleSveltePage({ + ...projectProps, + }), + ); + + await promises.writeFile( + path.join(exampleRoutePath, "+server.js"), + getSentryExampleApiRoute(), + ); +} diff --git a/packages/cli/src/lib/wizard/sveltekit/sdk-setup/setup.ts b/packages/cli/src/lib/wizard/sveltekit/sdk-setup/setup.ts new file mode 100644 index 000000000..07814b615 --- /dev/null +++ b/packages/cli/src/lib/wizard/sveltekit/sdk-setup/setup.ts @@ -0,0 +1,696 @@ +/** + * Creates or merges the SvelteKit hooks and `instrumentation.server` files + * that initialize the Sentry SDK. + */ + +import { promises } from "node:fs"; +import path from "node:path"; +import chalk from "chalk"; + +import { Sentry } from "../../telemetry.js"; + +import { clack } from "../../utils/clack/prompts.js"; +import type { ProxifiedModule } from "magicast"; +import { builders, generateCode, loadFile } from "magicast"; +import { + getClientHooksTemplate, + getInstrumentationServerTemplate, + getServerHooksTemplate, +} from "../templates.js"; +import { + featureSelectionPrompt, + isUsingTypeScript, + showCopyPasteInstructions, +} from "../../utils/clack/index.js"; +import { findFile } from "../../../dsn/fs-utils.js"; +import { hasSentryContent } from "../../utils/ast-utils.js"; +import { getDataCollectionSnippet } from "../../utils/data-collection.js"; + +import recast from "recast"; +import type { namedTypes as t } from "ast-types"; +import { + enableTracingAndInstrumentation, + type PartialBackwardsForwardsCompatibleSvelteConfig, +} from "./svelte-config.js"; +import type { ProjectInfo } from "./types.js"; +import { modifyViteConfig } from "./vite.js"; +import { modifyAndRecordFail } from "./utils.js"; +import { debug } from "../../utils/debug.js"; + +export async function createOrMergeSvelteKitFiles( + projectInfo: ProjectInfo, + svelteConfig: PartialBackwardsForwardsCompatibleSvelteConfig, + setupForSvelteKitTracing: boolean, +): Promise { + const selectedFeatures = await featureSelectionPrompt([ + { + id: "performance", + prompt: `Do you want to enable ${chalk.bold( + "Tracing", + )} to track the performance of your application?`, + enabledHint: "recommended", + }, + { + id: "replay", + prompt: `Do you want to enable ${chalk.bold( + "Session Replay", + )} to get a video-like reproduction of errors during a user session?`, + enabledHint: "recommended, but increases bundle size", + }, + ] as const); + + const { clientHooksPath, serverHooksPath } = getHooksConfigDirs(svelteConfig); + + // full file paths with correct file ending (or undefined if not found) + const originalClientHooksFile = await findFile(clientHooksPath); + const originalServerHooksFile = await findFile(serverHooksPath); + const originalInstrumentationServerFile = await findFile( + path.resolve(process.cwd(), "src", "instrumentation.server"), + ); + + const viteConfig = await findFile(path.resolve(process.cwd(), "vite.config")); + + const fileEnding = isUsingTypeScript() ? "ts" : "js"; + + const { dsn, reduceDataCollection } = projectInfo; + + if (setupForSvelteKitTracing) { + await enableTracingAndInstrumentation( + svelteConfig, + selectedFeatures.performance, + ); + + try { + if (!originalInstrumentationServerFile) { + await createNewInstrumentationServerFile( + dsn, + selectedFeatures, + reduceDataCollection, + ); + } else { + await mergeInstrumentationServerFile( + originalInstrumentationServerFile, + dsn, + selectedFeatures, + reduceDataCollection, + ); + } + } catch (e) { + clack.log.warn( + `Failed to automatically set up ${chalk.cyan( + `instrumentation.server.${fileEnding}`, + )}.`, + ); + debug(e); + + await showCopyPasteInstructions({ + codeSnippet: getInstrumentationServerTemplate( + dsn, + selectedFeatures, + reduceDataCollection, + ), + filename: `instrumentation.server.${fileEnding}`, + }); + + Sentry.setTag("created-instrumentation-server", "fail"); + } + } + + Sentry.setTag( + "server-hooks-file-strategy", + originalServerHooksFile ? "merge" : "create", + ); + + if (!originalServerHooksFile) { + await createNewHooksFile( + `${serverHooksPath}.${fileEnding}`, + "server", + dsn, + selectedFeatures, + !setupForSvelteKitTracing, + reduceDataCollection, + ); + } else { + await mergeHooksFile( + originalServerHooksFile, + "server", + dsn, + selectedFeatures, + !setupForSvelteKitTracing, + reduceDataCollection, + ); + } + + Sentry.setTag( + "client-hooks-file-strategy", + originalClientHooksFile ? "merge" : "create", + ); + if (!originalClientHooksFile) { + await createNewHooksFile( + `${clientHooksPath}.${fileEnding}`, + "client", + dsn, + selectedFeatures, + true, + reduceDataCollection, + ); + } else { + await mergeHooksFile( + originalClientHooksFile, + "client", + dsn, + selectedFeatures, + true, + reduceDataCollection, + ); + } + + if (viteConfig) { + await modifyViteConfig(viteConfig, projectInfo); + } +} + +/** + * Attempts to read the svelte.config.js file to find the location of the hooks files. + * If users specified a custom location, we'll use that. Otherwise, we'll use the default. + */ +function getHooksConfigDirs( + svelteConfig: PartialBackwardsForwardsCompatibleSvelteConfig, +): { + clientHooksPath: string; + serverHooksPath: string; +} { + const relativeUserClientHooksPath = svelteConfig.kit?.files?.hooks?.client; + const relativeUserServerHooksPath = svelteConfig.kit?.files?.hooks?.server; + const userClientHooksPath = + relativeUserClientHooksPath && + path.resolve(process.cwd(), relativeUserClientHooksPath); + const userServerHooksPath = + relativeUserServerHooksPath && + path.resolve(process.cwd(), relativeUserServerHooksPath); + + const defaulHooksDir = path.resolve(process.cwd(), "src"); + const defaultClientHooksPath = path.resolve(defaulHooksDir, "hooks.client"); // file ending missing on purpose + const defaultServerHooksPath = path.resolve(defaulHooksDir, "hooks.server"); // same here + + return { + clientHooksPath: userClientHooksPath || defaultClientHooksPath, + serverHooksPath: userServerHooksPath || defaultServerHooksPath, + }; +} + +/** + * Reads the template, replaces the dsn placeholder with the actual dsn and writes the file to @param hooksFileDest + */ +// oxlint-disable-next-line max-params -- positional like the sentry-wizard original and its tests +async function createNewHooksFile( + hooksFileDest: string, + hooktype: "client" | "server", + dsn: string, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + setupForSvelteKitTracing: boolean, + reduceDataCollection: boolean, +): Promise { + const filledTemplate = + hooktype === "client" + ? getClientHooksTemplate(dsn, selectedFeatures, reduceDataCollection) + : getServerHooksTemplate( + dsn, + selectedFeatures, + setupForSvelteKitTracing, + reduceDataCollection, + ); + + await promises.mkdir(path.dirname(hooksFileDest), { recursive: true }); + await promises.writeFile(hooksFileDest, filledTemplate); + + clack.log.success(`Created ${hooksFileDest}`); + Sentry.setTag(`created-${hooktype}-hooks`, "success"); +} + +async function createNewInstrumentationServerFile( + dsn: string, + selectedFeatures: { + performance: boolean; + }, + reduceDataCollection: boolean, +): Promise { + const filledTemplate = getInstrumentationServerTemplate( + dsn, + selectedFeatures, + reduceDataCollection, + ); + + const fileEnding = isUsingTypeScript() ? "ts" : "js"; + + const instrumentationServerFile = path.resolve( + process.cwd(), + "src", + `instrumentation.server.${fileEnding}`, + ); + + await promises.mkdir(path.dirname(instrumentationServerFile), { + recursive: true, + }); + + await promises.writeFile(instrumentationServerFile, filledTemplate); + + clack.log.success( + `Created ${chalk.cyan(path.basename(instrumentationServerFile))}`, + ); + Sentry.setTag("created-instrumentation-server", "success"); +} + +/** + * Merges the users' hooks file with Sentry-related code. + * + * Both hooks: + * - add import * as Sentry + * - add Sentry.init + * - add handleError hook wrapper + * + * Additionally in Server hook: + * - add handle hook handler + */ +// oxlint-disable-next-line max-params -- positional like the sentry-wizard original and its tests +async function mergeHooksFile( + hooksFile: string, + hookType: "client" | "server", + dsn: string, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + includeSentryInit: boolean, + reduceDataCollection: boolean, +): Promise { + const originalHooksMod = await loadFile(hooksFile); + + const file: "server-hooks" | "client-hooks" = `${hookType}-hooks`; + + if (hasSentryContent(originalHooksMod.$ast as t.Program)) { + // We don't want to mess with files that already have Sentry content. + // Let's just bail out at this point. + clack.log.warn( + `File ${chalk.cyan( + path.basename(hooksFile), + )} already contains Sentry code. +Skipping adding Sentry functionality to.`, + ); + Sentry.setTag(`modified-${file}`, "fail"); + Sentry.setTag(`${file}-fail-reason`, "has-sentry-content"); + return; + } + + await modifyAndRecordFail( + () => + originalHooksMod.imports.$add({ + from: "@sentry/sveltekit", + imported: "*", + local: "Sentry", + }), + "import-injection", + file, + ); + + if (hookType === "client" || includeSentryInit) { + await modifyAndRecordFail( + () => { + if (hookType === "client") { + insertClientInitCall( + dsn, + originalHooksMod, + selectedFeatures, + reduceDataCollection, + ); + } else { + insertServerInitCall( + dsn, + originalHooksMod, + selectedFeatures, + reduceDataCollection, + ); + } + }, + "init-call-injection", + file, + ); + } + + await modifyAndRecordFail( + () => wrapHandleError(originalHooksMod), + "wrap-handle-error", + file, + ); + + if (hookType === "server") { + await modifyAndRecordFail( + () => wrapHandle(originalHooksMod), + "wrap-handle", + "server-hooks", + ); + } + + await modifyAndRecordFail( + async () => { + const modifiedCode = originalHooksMod.generate().code; + await promises.writeFile(hooksFile, modifiedCode); + }, + "write-file", + file, + ); + + clack.log.success(`Added Sentry code to ${hooksFile}`); + Sentry.setTag(`modified-${hookType}-hooks`, "success"); +} + +/** + * Merges the users' instrumentation.server file with Sentry-related code. + * + * Both hooks: + * - add import * as Sentry + * - add Sentry.init + * - add handleError hook wrapper + * + * Additionally in Server hook: + * - add handle hook handler + */ +async function mergeInstrumentationServerFile( + instrumentationServerFilePath: string, + dsn: string, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + reduceDataCollection: boolean, +): Promise { + const originalInstrumentationServerMod = await loadFile( + instrumentationServerFilePath, + ); + const filename = path.basename(instrumentationServerFilePath); + + if (hasSentryContent(originalInstrumentationServerMod.$ast as t.Program)) { + // We don't want to mess with files that already have Sentry content. + // Let's just bail out at this point. + clack.log.warn( + `File ${chalk.cyan(filename)} already contains Sentry code. +Skipping adding Sentry functionality to it.`, + ); + Sentry.setTag(`modified-instrumentation-server`, "fail"); + Sentry.setTag(`instrumentation-server-fail-reason`, "has-sentry-content"); + return; + } + + await modifyAndRecordFail( + () => + originalInstrumentationServerMod.imports.$add({ + from: "@sentry/sveltekit", + imported: "*", + local: "Sentry", + }), + "import-injection", + "instrumentation-server", + ); + + await modifyAndRecordFail( + () => { + insertServerInitCall( + dsn, + originalInstrumentationServerMod, + selectedFeatures, + reduceDataCollection, + ); + }, + "init-call-injection", + "instrumentation-server", + ); + + await modifyAndRecordFail( + async () => { + const modifiedCode = originalInstrumentationServerMod.generate().code; + await promises.writeFile(instrumentationServerFilePath, modifiedCode); + }, + "write-file", + "instrumentation-server", + ); + + clack.log.success(`Added Sentry.init code to ${chalk.cyan(filename)}`); + Sentry.setTag(`modified-instrumentation-server`, "success"); +} + +const DATA_COLLECTION_HINT = [ + "", + " dataCollection: {", + " // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit:", + " // https://docs.sentry.io/platforms/javascript/guides/sveltekit/configuration/options/#dataCollection", + " // userInfo: false,", + " // httpBodies: [],", + " },", +].join("\n"); + +/** + * The active PII-reducing preset when the user opted in, the commented-out + * hint otherwise. Spliced into the generated `Sentry.init` code right before + * the closing `})`. + */ +function getDataCollectionInitCode(reduceDataCollection: boolean): string { + return reduceDataCollection + ? `\n${getDataCollectionSnippet(" ")}` + : DATA_COLLECTION_HINT; +} + +export function insertClientInitCall( + dsn: string, + originalHooksMod: ProxifiedModule, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + reduceDataCollection: boolean, +): void { + const initCallComment = ` + // If you don't want to use Session Replay, remove the \`Replay\` integration, + // \`replaysSessionSampleRate\` and \`replaysOnErrorSampleRate\` options.`; + + const initArgs: { + dsn: string; + tracesSampleRate?: number; + replaysSessionSampleRate?: number; + replaysOnErrorSampleRate?: number; + integrations?: string[]; + } = { + dsn, + }; + + if (selectedFeatures.performance) { + initArgs.tracesSampleRate = 1.0; + } + + if (selectedFeatures.replay) { + initArgs.replaysSessionSampleRate = 0.1; + initArgs.replaysOnErrorSampleRate = 1.0; + initArgs.integrations = [builders.functionCall("Sentry.replayIntegration")]; + } + + // This assignment of any values is fine because we're just creating a function call in magicast + const initCall = builders.functionCall("Sentry.init", initArgs); + + const generatedInitCode = generateCode(initCall).code; + const initCodeWithHint = generatedInitCode.replace( + /\n\}\)$/, + `,${getDataCollectionInitCode(reduceDataCollection)}\n})`, + ); + + const initCallWithComment = builders.raw( + `${initCallComment}\n${initCodeWithHint}`, + ); + + const originalHooksModAST = originalHooksMod.$ast as t.Program; + + const initCallInsertionIndex = getInitCallInsertionIndex(originalHooksModAST); + + originalHooksModAST.body.splice( + initCallInsertionIndex, + 0, + // @ts-expect-error - string works here because the AST is proxified by magicast + generateCode(initCallWithComment).code, + ); +} + +function insertServerInitCall( + dsn: string, + originalMod: ProxifiedModule, + selectedFeatures: { + performance: boolean; + }, + reduceDataCollection: boolean, +): void { + const initArgs: { + dsn: string; + tracesSampleRate?: number; + } = { + dsn, + }; + + if (selectedFeatures.performance) { + initArgs.tracesSampleRate = 1.0; + } + + // This assignment of any values is fine because we're just creating a function call in magicast + const initCall = builders.functionCall("Sentry.init", initArgs); + + const generatedInitCode = generateCode(initCall).code; + const initCodeWithHint = generatedInitCode.replace( + /\n\}\)$/, + `,${getDataCollectionInitCode(reduceDataCollection)}\n})`, + ); + + const originalModAST = originalMod.$ast as t.Program; + + const initCallInsertionIndex = getInitCallInsertionIndex(originalModAST); + + originalModAST.body.splice( + initCallInsertionIndex, + 0, + // @ts-expect-error - string works here because the AST is proxified by magicast + initCodeWithHint, + ); +} + +function wrapHandleError(mod: ProxifiedModule): void { + const modAst = mod.exports.$ast as t.Program; + const namedExports = modAst.body.filter( + (node): node is t.ExportNamedDeclaration => + node.type === "ExportNamedDeclaration", + ); + + let foundHandleError = false as boolean; + + for (const modExport of namedExports) { + const declaration = modExport.declaration; + if (!declaration) { + continue; + } + if (declaration.type === "FunctionDeclaration") { + if (declaration.id?.name !== "handleError") { + continue; + } + foundHandleError = true; + const userCode = recast.print(declaration).code; + mod.exports["handleError"] = builders.raw( + `Sentry.handleErrorWithSentry(${userCode.replace( + "handleError", + "_handleError", + )})`, + ); + // because magicast doesn't overwrite the original function export, we need to remove it manually + modAst.body = modAst.body.filter((node) => node !== modExport); + } else if (declaration.type === "VariableDeclaration") { + const declarations = declaration.declarations; + for (const declaration of declarations) { + if ( + declaration.type !== "VariableDeclarator" || + declaration.id.type !== "Identifier" || + declaration.id.name !== "handleError" + ) { + continue; + } + foundHandleError = true; + const userCode = declaration.init; + const stringifiedUserCode = userCode ? recast.print(userCode).code : ""; + // @ts-expect-error - we can just place a string here, magicast will convert it to a node + declaration.init = `Sentry.handleErrorWithSentry(${stringifiedUserCode})`; + } + } + } + + if (!foundHandleError) { + mod.exports["handleError"] = builders.functionCall( + "Sentry.handleErrorWithSentry", + ); + } +} + +function wrapHandle(mod: ProxifiedModule): void { + const modAst = mod.exports.$ast as t.Program; + const namedExports = modAst.body.filter( + (node): node is t.ExportNamedDeclaration => + node.type === "ExportNamedDeclaration", + ); + + let foundHandle = false as boolean; + + for (const modExport of namedExports) { + const declaration = modExport.declaration; + if (!declaration) { + continue; + } + if (declaration.type === "FunctionDeclaration") { + if (declaration.id?.name !== "handle") { + continue; + } + foundHandle = true; + const userCode = recast.print(declaration).code; + mod.exports["handle"] = builders.raw( + `sequence(Sentry.sentryHandle(), ${userCode.replace( + "handle", + "_handle", + )})`, + ); + // because of an issue with magicast, we need to remove the original export + modAst.body = modAst.body.filter((node) => node !== modExport); + } else if (declaration.type === "VariableDeclaration") { + const declarations = declaration.declarations; + for (const declaration of declarations) { + if ( + declaration.type !== "VariableDeclarator" || + declaration.id.type !== "Identifier" || + (declaration.id.name && declaration.id.name !== "handle") + ) { + continue; + } + const userCode = declaration.init; + const stringifiedUserCode = userCode ? recast.print(userCode).code : ""; + // @ts-expect-error - we can just place a string here, magicast will convert it to a node + declaration.init = `sequence(Sentry.sentryHandle(), ${stringifiedUserCode})`; + foundHandle = true; + } + } + } + + if (!foundHandle) { + // can't use builders.functionCall here because it doesn't yet + // support member expressions (Sentry.sentryHandle()) in args + mod.exports["handle"] = builders.raw("sequence(Sentry.sentryHandle())"); + } + + try { + mod.imports.$add({ + from: "@sveltejs/kit/hooks", + imported: "sequence", + local: "sequence", + }); + } catch (error) { + // It's possible sequence is already imported. in this case, magicast throws but that's fine. + debug(error); + } +} + +/** + * We want to insert the init call on top of the file but after all import statements + */ +function getInitCallInsertionIndex(originalModAST: t.Program): number { + // We need to deep-copy here because reverse mutates in place + const copiedBodyNodes = [...originalModAST.body]; + const lastImportDeclaration = copiedBodyNodes + .reverse() + .find((node) => node.type === "ImportDeclaration"); + + const initCallInsertionIndex = lastImportDeclaration + ? originalModAST.body.indexOf(lastImportDeclaration) + 1 + : 0; + return initCallInsertionIndex; +} diff --git a/packages/cli/src/lib/wizard/sveltekit/sdk-setup/svelte-config.ts b/packages/cli/src/lib/wizard/sveltekit/sdk-setup/svelte-config.ts new file mode 100644 index 000000000..3fe77554c --- /dev/null +++ b/packages/cli/src/lib/wizard/sveltekit/sdk-setup/svelte-config.ts @@ -0,0 +1,400 @@ +/** + * Reads `svelte.config.js` and turns on SvelteKit's native tracing and + * instrumentation in it. + */ + +import { formatError } from "../../../errors.js"; +import { reportCliError } from "../../../error-reporting.js"; +import { existsSync, promises } from "node:fs"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; +import chalk from "chalk"; +import recast from "recast"; +import type { namedTypes as t } from "ast-types"; + +import { clack } from "../../utils/clack/prompts.js"; +import { + makeCodeSnippet, + showCopyPasteInstructions, +} from "../../utils/clack/index.js"; +import { generateCode, parseModule, type ProxifiedModule } from "magicast"; +import { debug } from "../../utils/debug.js"; + +const SVELTE_CONFIG_FILE = "svelte.config.js"; + +const b = recast.types.builders; + +export type PartialBackwardsForwardsCompatibleSvelteConfig = { + kit?: { + files?: { + hooks?: { + client?: string; + server?: string; + }; + routes?: string; + }; + experimental?: { + tracing?: { + server?: boolean; + }; + instrumentation?: { + server?: boolean; + }; + }; + }; +}; + +export async function loadSvelteConfig(): Promise { + const configFilePath = path.join(process.cwd(), SVELTE_CONFIG_FILE); + + try { + if (!existsSync(configFilePath)) { + return {}; + } + + const configUrl = pathToFileURL(configFilePath).href; + const svelteConfigModule = (await import(configUrl)) as { + default?: PartialBackwardsForwardsCompatibleSvelteConfig; + }; + + return svelteConfigModule.default ?? {}; + } catch (e: unknown) { + clack.log.error(`Couldn't load ${chalk.cyan(SVELTE_CONFIG_FILE)}. +Are you running this wizard from the root of your SvelteKit project?`); + clack.log.info(chalk.dim(formatError(e))); + + return {}; + } +} + +export async function enableTracingAndInstrumentation( + originalSvelteConfig: PartialBackwardsForwardsCompatibleSvelteConfig, + enableTracing: boolean, +) { + const experimental = originalSvelteConfig.kit?.experimental; + const hasTracingEnabled = experimental?.tracing?.server === true; + const hasInstrumentationEnabled = + experimental?.instrumentation?.server === true; + + if (hasInstrumentationEnabled && (hasTracingEnabled || !enableTracing)) { + clack.log.info("Tracing and instrumentation are already enabled."); + return; + } + + // Never turn off server tracing that the project already enabled. + const tracingServer = enableTracing || hasTracingEnabled; + + try { + const configPath = path.join(process.cwd(), SVELTE_CONFIG_FILE); + const svelteConfigContent = await promises.readFile(configPath, "utf-8"); + + const { error, result } = _enableTracingAndInstrumentationInConfig( + svelteConfigContent, + tracingServer, + ); + + if (error) { + clack.log.warning( + "Failed to automatically enable SvelteKit tracing and instrumentation.", + ); + debug(error); + reportCliError(error); + await showFallbackConfigSnippet(tracingServer); + return; + } + + if (result) { + await promises.writeFile(configPath, result); + } + + clack.log.success( + `Enabled tracing and instrumentation in ${chalk.cyan( + SVELTE_CONFIG_FILE, + )}`, + ); + } catch (e) { + clack.log.error( + `Failed to enable tracing and instrumentation in ${chalk.cyan( + SVELTE_CONFIG_FILE, + )}.`, + ); + debug(e); + reportCliError( + new Error( + `Failed to enable tracing and instrumentation in ${SVELTE_CONFIG_FILE}`, + ), + ); + await showFallbackConfigSnippet(tracingServer); + return; + } +} + +export function _enableTracingAndInstrumentationInConfig( + config: string, + enableTracing: boolean, +): { + result?: string; + error?: string; +} { + let svelteConfig: ProxifiedModule; + try { + svelteConfig = parseModule(config); + } catch (e) { + // The caller shows the error and falls back to copy-paste instructions. + debug(e); + return { + error: "Failed to parse Svelte config", + }; + } + + let configObject: t.ObjectExpression | undefined = undefined; + + // Cases to handle for finding the config object: + // 1. default export is named object + // 2. default export is in-place object + // 3. default export is an identifier, so look up the variable declaration + recast.visit(svelteConfig.$ast, { + visitExportDefaultDeclaration(path) { + const exportDeclarationNode = path.node; + if ( + exportDeclarationNode.declaration.type === "AssignmentExpression" && + exportDeclarationNode.declaration.right.type === "ObjectExpression" + ) { + configObject = exportDeclarationNode.declaration.right; + return false; + } + + if (exportDeclarationNode.declaration.type === "ObjectExpression") { + configObject = exportDeclarationNode.declaration; + return false; + } + + if (exportDeclarationNode.declaration.type === "Identifier") { + const identifierName = exportDeclarationNode.declaration.name; + recast.visit(svelteConfig.$ast, { + visitVariableDeclarator(path) { + if ( + path.node.id.type === "Identifier" && + path.node.id.name === identifierName && + path.node.init?.type === "ObjectExpression" + ) { + configObject = path.node.init; + return false; + } + + this.traverse(path); + return undefined; + }, + }); + } + + this.traverse(path); + return undefined; + }, + }); + + if (!_isValidConfigObject(configObject)) { + return { + error: "Couldn't find the config object", + }; + } + + // This type cast is safe. For some reason, TS still assumes that `configObject` + // is `undefined` so we have to tell it that it's not (see check above) + const validatedConfigObject = + configObject as recast.types.namedTypes.ObjectExpression; + + const kitProp = validatedConfigObject.properties.find( + (prop) => + prop.type === "ObjectProperty" && + prop.key.type === "Identifier" && + prop.key.name === "kit", + ); + + if (kitProp?.type !== "ObjectProperty") { + return { + error: "Couldn't find the `kit` property", + }; + } + + if (kitProp.value.type !== "ObjectExpression") { + return { + error: `\`kit\` property has unexpected type: ${kitProp.value.type}`, + }; + } + + // 1. find or add `kit.experimental` property + // type-cast because TS can't infer the type in `.find` :( + const kitExperimentalProp = kitProp.value.properties.find( + (prop) => + prop.type === "ObjectProperty" && + prop.key.type === "Identifier" && + prop.key.name === "experimental", + ) as t.ObjectProperty | undefined; + + let experimentalObject: t.ObjectExpression; + + if (kitExperimentalProp) { + if (kitExperimentalProp.value.type !== "ObjectExpression") { + return { + error: `Property \`kit.experimental\` has unexpected type: ${kitExperimentalProp.value.type}`, + }; + } + + experimentalObject = kitExperimentalProp.value; + } else { + experimentalObject = b.objectExpression([]); + kitProp.value.properties.push( + b.objectProperty(b.identifier("experimental"), experimentalObject), + ); + } + + // 2. find or add `kit.experimental.tracing` property + // find or add `kit.experimental.instrumentation` property + const kitExperimentalTraingProp = experimentalObject.properties.find( + (prop) => + prop.type === "ObjectProperty" && + prop.key.type === "Identifier" && + prop.key.name === "tracing", + ) as t.ObjectProperty | undefined; + + const kitExperimentalInstrumentationProp = experimentalObject.properties.find( + (prop) => + prop.type === "ObjectProperty" && + prop.key.type === "Identifier" && + prop.key.name === "instrumentation", + ) as t.ObjectProperty | undefined; + + let experimentalTracingObject: t.ObjectExpression; + let experimentalInstrumentationObject: t.ObjectExpression; + + if (kitExperimentalTraingProp) { + if (kitExperimentalTraingProp.value.type !== "ObjectExpression") { + return { + error: `Property \`kit.experimental.tracing\` has unexpected type: ${kitExperimentalTraingProp.value.type}`, + }; + } + + experimentalTracingObject = kitExperimentalTraingProp.value; + } else { + experimentalTracingObject = b.objectExpression([]); + experimentalObject.properties.push( + b.objectProperty(b.identifier("tracing"), experimentalTracingObject), + ); + } + + if (kitExperimentalInstrumentationProp) { + if (kitExperimentalInstrumentationProp.value.type !== "ObjectExpression") { + return { + error: `Property \`kit.experimental.instrumentation\` has unexpected type: ${kitExperimentalInstrumentationProp.value.type}`, + }; + } + + experimentalInstrumentationObject = + kitExperimentalInstrumentationProp.value; + } else { + experimentalInstrumentationObject = b.objectExpression([]); + experimentalObject.properties.push( + b.objectProperty( + b.identifier("instrumentation"), + experimentalInstrumentationObject, + ), + ); + } + + // 3. find or add `kit.experimental.tracing.server` property + // find or add `kit.experimental.instrumentation.server` property + const kitExperimentalTracingSeverProp = + experimentalTracingObject.properties.find( + (prop) => + prop.type === "ObjectProperty" && + prop.key.type === "Identifier" && + prop.key.name === "server", + ) as t.ObjectProperty | undefined; + + const kitExperimentalInstrumentationSeverProp = + experimentalInstrumentationObject.properties.find( + (prop) => + prop.type === "ObjectProperty" && + prop.key.type === "Identifier" && + prop.key.name === "server", + ) as t.ObjectProperty | undefined; + + if (kitExperimentalTracingSeverProp) { + if (kitExperimentalTracingSeverProp.value.type !== "BooleanLiteral") { + return { + error: `Property \`kit.experimental.tracing.server\` has unexpected type: ${kitExperimentalTracingSeverProp.value.type}`, + }; + } + + // Never turn off server tracing that the file already enables, even when + // the loaded config didn't show it. + kitExperimentalTracingSeverProp.value = b.booleanLiteral( + enableTracing || kitExperimentalTracingSeverProp.value.value, + ); + } else { + experimentalTracingObject.properties.push( + b.objectProperty(b.identifier("server"), b.booleanLiteral(enableTracing)), + ); + } + + if (kitExperimentalInstrumentationSeverProp) { + if ( + kitExperimentalInstrumentationSeverProp.value.type !== "BooleanLiteral" + ) { + return { + error: `Property \`kit.experimental.instrumentation.server\` has unexpected type: ${kitExperimentalInstrumentationSeverProp.value.type}`, + }; + } + kitExperimentalInstrumentationSeverProp.value = b.booleanLiteral(true); + } else { + experimentalInstrumentationObject.properties.push( + b.objectProperty(b.identifier("server"), b.booleanLiteral(true)), + ); + } + + try { + return { + result: generateCode(svelteConfig).code, + }; + } catch (e) { + debug(e); + return { + error: "Failed to generate code for Svelte config", + }; + } +} + +function _isValidConfigObject( + o: t.ObjectExpression | undefined, +): o is t.ObjectExpression { + return !!o; +} + +async function showFallbackConfigSnippet( + tracingServer: boolean, +): Promise { + const codeSnippet = makeCodeSnippet(true, (unchanged, plus) => + unchanged(`const config = { +preprocess: vitePreprocess(), + +kit: { + adapter: adapter(), + ${plus(`experimental: { + instrumentation: { + server: true, + }, + tracing: { + server: ${tracingServer}, + }, + },`)} +}, +}; +`), + ); + + await showCopyPasteInstructions({ + filename: "svelte.config.js", + codeSnippet, + }); +} diff --git a/packages/cli/src/lib/wizard/sveltekit/sdk-setup/types.ts b/packages/cli/src/lib/wizard/sveltekit/sdk-setup/types.ts new file mode 100644 index 000000000..ddf6fcb2b --- /dev/null +++ b/packages/cli/src/lib/wizard/sveltekit/sdk-setup/types.ts @@ -0,0 +1,15 @@ +/** + * Types shared by the SvelteKit setup steps. + */ + +export type ProjectInfo = { + dsn: string; + org: string; + project: string; + selfHosted: boolean; + url: string; + /** Module `sentrySvelteKit` is imported from; depends on the installed SDK major. */ + vitePluginImportPath: string; + /** Whether to write the PII-reducing `dataCollection` preset into `Sentry.init` (SDK v11+). */ + reduceDataCollection: boolean; +}; diff --git a/packages/cli/src/lib/wizard/sveltekit/sdk-setup/utils.ts b/packages/cli/src/lib/wizard/sveltekit/sdk-setup/utils.ts new file mode 100644 index 000000000..ee2f4b973 --- /dev/null +++ b/packages/cli/src/lib/wizard/sveltekit/sdk-setup/utils.ts @@ -0,0 +1,29 @@ +/** + * Runs a SvelteKit setup step as a telemetry step and tags why it failed. + */ + +import { traceStep } from "../../telemetry.js"; +import { Sentry } from "../../telemetry.js"; + +/** + * Applies the @param modifyCallback and records Sentry tags if the call failed. + * In case of a failure, a tag is set with @param reason as a fail reason + * and the error is rethrown. + */ +export async function modifyAndRecordFail( + modifyCallback: () => T | Promise, + reason: string, + fileType: + | "server-hooks" + | "client-hooks" + | "vite-cfg" + | "instrumentation-server", +): Promise { + try { + await traceStep(`${fileType}-${reason}`, modifyCallback); + } catch (e) { + Sentry.setTag(`modified-${fileType}`, "fail"); + Sentry.setTag(`${fileType}-mod-fail-reason`, reason); + throw e; + } +} diff --git a/packages/cli/src/lib/wizard/sveltekit/sdk-setup/vite.ts b/packages/cli/src/lib/wizard/sveltekit/sdk-setup/vite.ts new file mode 100644 index 000000000..d3625f3ae --- /dev/null +++ b/packages/cli/src/lib/wizard/sveltekit/sdk-setup/vite.ts @@ -0,0 +1,157 @@ +/** + * Adds the Sentry SvelteKit Vite plugin to `vite.config.(js|ts)`. + */ + +import { reportCliError } from "../../../error-reporting.js"; +import { Sentry } from "../../telemetry.js"; +import { promises } from "node:fs"; +import path from "node:path"; +import chalk from "chalk"; + +import { clack } from "../../utils/clack/prompts.js"; +import { generateCode, parseModule } from "magicast"; +import { addVitePlugin } from "magicast/helpers"; + +import type { namedTypes as t } from "ast-types"; + +import { + hasSentryContent, + preserveTrailingNewline, +} from "../../utils/ast-utils.js"; +import { debug } from "../../utils/debug.js"; +import { abortIfCancelled } from "../../utils/clack/index.js"; +import type { ProjectInfo } from "./types.js"; +import { modifyAndRecordFail } from "./utils.js"; + +export async function modifyViteConfig( + viteConfigPath: string, + projectInfo: ProjectInfo, +): Promise { + const viteConfigContent = ( + await promises.readFile(viteConfigPath, "utf-8") + ).toString(); + + const { org, project, url, selfHosted, vitePluginImportPath } = projectInfo; + + const prettyViteConfigFilename = chalk.cyan(path.basename(viteConfigPath)); + + try { + const viteModule = parseModule(viteConfigContent); + + if (hasSentryContent(viteModule.$ast as t.Program)) { + clack.log.warn( + `File ${prettyViteConfigFilename} already contains Sentry code. +Skipping adding Sentry functionality to.`, + ); + Sentry.setTag(`modified-vite-cfg`, "fail"); + Sentry.setTag(`vite-cfg-fail-reason`, "has-sentry-content"); + return; + } + + await modifyAndRecordFail( + () => + addVitePlugin(viteModule, { + imported: "sentrySvelteKit", + from: vitePluginImportPath, + constructor: "sentrySvelteKit", + options: { + org, + project, + ...(selfHosted && { sentryUrl: url }), + }, + index: 0, + }), + "add-vite-plugin", + "vite-cfg", + ); + + await modifyAndRecordFail( + async () => { + const code = preserveTrailingNewline( + viteConfigContent, + generateCode(viteModule.$ast).code, + ); + await promises.writeFile(viteConfigPath, code); + }, + "write-file", + "vite-cfg", + ); + } catch (e) { + debug(e); + await showFallbackViteCopyPasteSnippet( + viteConfigPath, + getViteConfigCodeSnippet( + org, + project, + selfHosted, + url, + vitePluginImportPath, + ), + ); + reportCliError(new Error("Sveltekit Vite Config Modification Fail")); + return; + } + + clack.log.success(`Added Sentry code to ${prettyViteConfigFilename}`); + Sentry.setTag(`modified-vite-cfg`, "success"); +} + +async function showFallbackViteCopyPasteSnippet( + viteConfigPath: string, + codeSnippet: string, +) { + const viteConfigFilename = path.basename(viteConfigPath); + + clack.log.warning( + `Couldn't automatically modify your ${chalk.cyan(viteConfigFilename)} +${chalk.dim(`This sometimes happens when we encounter more complex vite configs. +It may not seem like it but sometimes our magical powers are limited ;)`)}`, + ); + + clack.log.info("But don't worry - it's super easy to do this yourself!"); + + clack.log.step( + `Add the following code to your ${chalk.cyan(viteConfigFilename)}:`, + ); + + // Printed outside clack's gutter for easier copy/pasting + clack.rawOutput(codeSnippet); + + await abortIfCancelled( + clack.select({ + message: "Did you copy the snippet above?", + options: [ + { label: "Yes!", value: true, hint: "Great, that's already it!" }, + ], + initialValue: true, + }), + ); +} + +const getViteConfigCodeSnippet = ( + org: string, + project: string, + selfHosted: boolean, + url: string, + vitePluginImportPath: string, +) => + chalk.gray(` +import { sveltekit } from '@sveltejs/kit/vite'; +import { defineConfig } from 'vite'; +${chalk.greenBright( + `import { sentrySvelteKit } from '${vitePluginImportPath}'`, +)} + +export default defineConfig({ + plugins: [ + // Make sure \`sentrySvelteKit\` is registered before \`sveltekit\` + ${chalk.greenBright(`sentrySvelteKit({ + org: '${org}', + project: '${project}',${ + selfHosted ? `\n sentryUrl: '${url}',` : "" + } + }),`)} + sveltekit(), + ] +}); +`); diff --git a/packages/cli/src/lib/wizard/sveltekit/sveltekit-wizard.ts b/packages/cli/src/lib/wizard/sveltekit/sveltekit-wizard.ts new file mode 100644 index 000000000..51f3d0387 --- /dev/null +++ b/packages/cli/src/lib/wizard/sveltekit/sveltekit-wizard.ts @@ -0,0 +1,298 @@ +/** + * The SvelteKit setup wizard: installs `@sentry/sveltekit`, sets up the + * hooks and instrumentation files and the Vite plugin, and optionally adds + * an example page. + */ + +import { formatError } from "../../errors.js"; +import { reportCliError } from "../../error-reporting.js"; +import { clack } from "../utils/clack/prompts.js"; +import chalk from "chalk"; + +import { Sentry } from "../telemetry.js"; + +import { traceStep, withTelemetry } from "../telemetry.js"; +import { + abort, + abortIfCancelled, + addDotEnvSentryBuildPluginFile, + askShouldCreateExamplePage, + confirmContinueIfNoOrDirtyGitRepo, + ensurePackageIsInstalled, + getOrAskForProjectData, + getPackageDotJson, + getPackageManager, + installPackage, + printSdkV11MigrationGuideIfOutdated, + printWelcome, + runPrettierIfInstalled, +} from "../utils/clack/index.js"; +import { + askShouldReduceDataCollection, + sdkSupportsDataCollection, +} from "../utils/data-collection.js"; +import { + getPackageVersion, + hasPackageInstalled, +} from "../utils/package-json.js"; +import { NPM } from "../utils/package-manager.js"; +import type { WizardOptions } from "../utils/types.js"; +import { offerProjectScopedMcpConfig } from "../utils/clack/mcp-config.js"; +import { createExamplePage } from "./sdk-example.js"; +import { createOrMergeSvelteKitFiles } from "./sdk-setup/setup.js"; +import { loadSvelteConfig } from "./sdk-setup/svelte-config.js"; +import { + getKitVersionBucket, + getSvelteVersionBucket, + SENTRY_SVELTEKIT_SDK_RANGE, + getSentrySvelteKitVitePluginImportPath, +} from "./utils.js"; +import { abortIfSpotlightNotSupported } from "../utils/abort-if-sportlight-not-supported.js"; +import { warnIfNodeVersionUnsupportedBySdkV11 } from "../utils/node-version.js"; + +export async function runSvelteKitWizard( + options: WizardOptions, +): Promise { + return await withTelemetry( + { + enabled: options.telemetryEnabled, + integration: "sveltekit", + wizardOptions: options, + }, + () => runSvelteKitWizardWithTelemetry(options), + ); +} + +export async function runSvelteKitWizardWithTelemetry( + options: WizardOptions, +): Promise { + const { telemetryEnabled, forceInstall } = options; + + printWelcome({ + wizardName: "Sentry SvelteKit Wizard", + telemetryEnabled, + }); + + warnIfNodeVersionUnsupportedBySdkV11(); + + await confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: options.ignoreGitChanges, + cwd: undefined, + }); + + const packageJson = await getPackageDotJson(); + + await ensurePackageIsInstalled(packageJson, "@sveltejs/kit", "Sveltekit"); + + const kitVersion = getPackageVersion("@sveltejs/kit", packageJson); + const kitVersionBucket = getKitVersionBucket(kitVersion); + Sentry.setTag("sveltekit-version", kitVersionBucket); + + if (kitVersionBucket === "0.x") { + clack.log.warn( + "It seems you're using a SvelteKit version <1.0.0 which is not supported by Sentry.\nWe recommend upgrading to the latest 1.x version before you continue.", + ); + const shouldContinue = await abortIfCancelled( + clack.select({ + message: "Do you want to continue anyway?", + options: [ + { + label: "Yes, continue", + hint: "The SDK might not work correctly", + value: true, + }, + { label: "No, I'll upgrade first", value: false }, + ], + }), + ); + if (!shouldContinue) { + await abort("Exiting Wizard", 0); + return; + } + } + + let setupForSvelteKitTracing = kitVersionBucket === ">=2.31.0"; + + if (kitVersionBucket !== ">=2.31.0") { + clack.log.warn( + `It seems you're using a SvelteKit version ${chalk.cyan( + "<2.31.0", + )} (detected ${chalk.cyan(kitVersion ?? "unknown")}). + +We recommend upgrading SvelteKit to version ${chalk.cyan( + ">=2.31.0", + )} to use SvelteKit's builtin observability: +${chalk.cyan("https://svelte.dev/docs/kit/observability")} + +Sentry works best with SvelteKit versions ${chalk.cyan(">=2.31.0")}. + +If you prefer, you can stay on your current version and use the Sentry SDK +without SvelteKit's builtin observability.`, + ); + + const decision = await abortIfCancelled( + clack.select({ + message: "Do you want to continue anyway?", + options: [ + { + label: "No, I'll upgrade SvelteKit first", + hint: "Recommended", + value: "exit-to-upgrade", + }, + { + label: "I'm already on SvelteKit >=2.31.0", + hint: "Sorry, my bad!", + value: "install-with-kit-tracing", + }, + { + label: "Yes, continue", + hint: "No Problem!", + value: "install-without-kit-tracing", + }, + ], + }), + ); + + if (decision === "install-with-kit-tracing") { + setupForSvelteKitTracing = true; + } + + if (decision === "exit-to-upgrade") { + await abort("Exiting Wizard", 0); + return; + } + } + + const svelteVersionBucket = getSvelteVersionBucket( + getPackageVersion("svelte", packageJson), + ); + Sentry.setTag("svelte-version", svelteVersionBucket); + + const projectData = await getOrAskForProjectData( + options, + "javascript-sveltekit", + ); + + if (projectData.spotlight) { + return await abortIfSpotlightNotSupported("SvelteKit"); + } + + const { selectedProject, selfHosted, sentryUrl, authToken } = projectData; + + const sdkAlreadyInstalled = hasPackageInstalled( + "@sentry/sveltekit", + packageJson, + ); + Sentry.setTag("sdk-already-installed", sdkAlreadyInstalled); + + printSdkV11MigrationGuideIfOutdated("@sentry/sveltekit", packageJson); + + await installPackage({ + packageName: `@sentry/sveltekit@${SENTRY_SVELTEKIT_SDK_RANGE}`, + packageNameDisplayLabel: "@sentry/sveltekit", + alreadyInstalled: sdkAlreadyInstalled, + 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/sveltekit", + await getPackageDotJson(), + ); + const vitePluginImportPath = + getSentrySvelteKitVitePluginImportPath(installedSdkVersion); + + // 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, + SENTRY_SVELTEKIT_SDK_RANGE, + ) && (await askShouldReduceDataCollection()); + + await addDotEnvSentryBuildPluginFile(authToken); + + const svelteConfig = await traceStep("load-svelte-config", loadSvelteConfig); + + try { + await traceStep("configure-sdk", () => + createOrMergeSvelteKitFiles( + { + dsn: selectedProject.keys[0].dsn.public, + org: selectedProject.organization.slug, + project: selectedProject.slug, + selfHosted, + url: sentryUrl, + vitePluginImportPath, + reduceDataCollection, + }, + svelteConfig, + setupForSvelteKitTracing, + ), + ); + } catch (e: unknown) { + clack.log.error("Error while setting up the SvelteKit SDK:"); + clack.log.info(chalk.dim(formatError(e))); + reportCliError(new Error("Error while setting up the SvelteKit SDK")); + await abort("Exiting Wizard"); + return; + } + + const shouldCreateExamplePage = await askShouldCreateExamplePage( + "/sentry-example-page", + ); + + if (shouldCreateExamplePage) { + try { + await traceStep( + "create-example-page", + async () => + await createExamplePage(svelteConfig, { + selfHosted, + url: sentryUrl, + orgSlug: selectedProject.organization.slug, + projectId: selectedProject.id, + isUsingSvelte5: ["5.x", ">5.x"].includes(svelteVersionBucket), + }), + ); + } catch (e: unknown) { + clack.log.error("Error while creating an example page to test Sentry:"); + clack.log.info(chalk.dim(formatError(e))); + reportCliError( + new Error("Error while creating an example Svelte page to test Sentry"), + ); + await abort("Exiting Wizard"); + return; + } + } + + 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(await buildOutroMessage(shouldCreateExamplePage)); +} + +async function buildOutroMessage( + shouldCreateExamplePage: boolean, +): Promise { + const packageManager = await getPackageManager(NPM); + + let msg = chalk.green("Successfully installed the Sentry SvelteKit SDK!"); + + if (shouldCreateExamplePage) { + msg += `\n\nYou can validate your setup by starting your dev environment (${chalk.cyan( + `\`${packageManager.runScriptCommand} dev\``, + )}) and visiting ${chalk.cyan('"/sentry-example-page"')}.`; + } + + msg += `\n\nCheck out the SDK documentation for further configuration: +https://docs.sentry.io/platforms/javascript/guides/sveltekit/`; + + return msg; +} diff --git a/packages/cli/src/lib/wizard/sveltekit/templates.ts b/packages/cli/src/lib/wizard/sveltekit/templates.ts new file mode 100644 index 000000000..936a9b6aa --- /dev/null +++ b/packages/cli/src/lib/wizard/sveltekit/templates.ts @@ -0,0 +1,369 @@ +/** + * Code templates the SvelteKit wizard writes or shows as copy-paste + * instructions. + */ + +import { getDataCollectionSnippet } from "../utils/data-collection.js"; + +const DATA_COLLECTION_HINT = ` dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/sveltekit/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + },`; + +/** + * The active PII-reducing preset when the user opted in, the commented-out + * hint otherwise. + */ +function getDataCollectionBlock(reduceDataCollection: boolean): string { + return reduceDataCollection + ? getDataCollectionSnippet(" ") + : DATA_COLLECTION_HINT; +} + +export function getClientHooksTemplate( + dsn: string, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + reduceDataCollection: boolean, +) { + return `import { handleErrorWithSentry, replayIntegration } from "@sentry/sveltekit"; +import * as Sentry from '@sentry/sveltekit'; + +Sentry.init({ + dsn: '${dsn}', +${ + selectedFeatures.performance + ? ` + tracesSampleRate: 1.0, +` + : "" +} +${ + selectedFeatures.replay + ? ` // This sets the sample rate to be 10%. You may want this to be 100% while + // in development and sample at a lower rate in production + replaysSessionSampleRate: 0.1, + + // If the entire session is not sampled, use the below sample rate to sample + // sessions when an error occurs. + replaysOnErrorSampleRate: 1.0, + + // If you don't want to use Session Replay, just remove the line below: + integrations: [replayIntegration()],` + : "" +} + +${getDataCollectionBlock(reduceDataCollection)} +}); + +// If you have a custom error handler, pass it to \`handleErrorWithSentry\` +export const handleError = handleErrorWithSentry(); +`; +} + +export function getServerHooksTemplate( + dsn: string, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + includeSentryInit: boolean, + reduceDataCollection: boolean, +) { + const sentryInit = includeSentryInit + ? `import * as Sentry from '@sentry/sveltekit'; + +Sentry.init({ + dsn: '${dsn}', +${ + selectedFeatures.performance + ? ` + tracesSampleRate: 1.0, +` + : "" +} +${getDataCollectionBlock(reduceDataCollection)} + + // uncomment the line below to enable Spotlight (https://spotlightjs.com) + // spotlight: import.meta.env.DEV, +});` + : ``; + + return `import { sequence } from "@sveltejs/kit/hooks"; +import { handleErrorWithSentry, sentryHandle } from "@sentry/sveltekit"; +${sentryInit} + +// If you have custom handlers, make sure to place them after \`sentryHandle()\` in the \`sequence\` function. +export const handle = sequence(sentryHandle()); + +// If you have a custom error handler, pass it to \`handleErrorWithSentry\` +export const handleError = handleErrorWithSentry(); +`; +} + +export function getInstrumentationServerTemplate( + dsn: string, + selectedFeatures: { + performance: boolean; + }, + reduceDataCollection: boolean, +) { + return `import * as Sentry from '@sentry/sveltekit'; + +Sentry.init({ + dsn: '${dsn}', +${ + selectedFeatures.performance + ? ` + tracesSampleRate: 1.0, +` + : "" +}${ + reduceDataCollection + ? `${getDataCollectionSnippet(" ")} +` + : "" + } // uncomment the line below to enable Spotlight (https://spotlightjs.com) + // spotlight: import.meta.env.DEV, +});`; +} + +/** + * +page.svelte with Sentry example + */ +export function getSentryExampleSveltePage(options: { + selfHosted: boolean; + url: string; + orgSlug: string; + projectId: string; + isUsingSvelte5: boolean; +}) { + const issuesPageLink = options.selfHosted + ? `${options.url}organizations/${options.orgSlug}/issues/?project=${options.projectId}` + : `https://${options.orgSlug}.sentry.io/issues/?project=${options.projectId}`; + + return ` + + + +sentry-example-page + +
+
+
+ + + +

+ sentry-example-page +

+ +

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

+ + + + {#if hasSentError} +

+ Sample error was sent to Sentry. +

+ {:else if !isConnected} +
+

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

+
+ {:else} +
+ {/if} +
+
+
+ + +`; +} + +export function getSentryExampleApiRoute() { + return `// This is just a very simple API route that throws an example error. +// Feel free to delete this file and the entire sentry route. + +export const GET = async () => { + throw new Error("Sentry Example API Route Error"); +}; +`; +} diff --git a/packages/cli/src/lib/wizard/sveltekit/utils.ts b/packages/cli/src/lib/wizard/sveltekit/utils.ts new file mode 100644 index 000000000..13045bacf --- /dev/null +++ b/packages/cli/src/lib/wizard/sveltekit/utils.ts @@ -0,0 +1,117 @@ +/** + * SvelteKit SDK version constants and the SvelteKit and Svelte version + * buckets the wizard branches on. + */ + +import { debug } from "../utils/debug.js"; +import { lt, minVersion } from "semver"; + +import { getMajorVersion } from "../utils/semver.js"; + +/** + * Version range of `@sentry/sveltekit` the wizard installs. Also decides the + * default import path of the Vite plugin when the installed version is unknown. + */ +export const SENTRY_SVELTEKIT_SDK_RANGE = "^11"; + +/** Root export. Exposes `sentrySvelteKit` up to SDK v10 only. */ +export const SENTRY_SVELTEKIT_ROOT_IMPORT_PATH = "@sentry/sveltekit"; + +/** Subpath that exposes `sentrySvelteKit` from SDK v11 on. v10 does not ship it. */ +export const SENTRY_SVELTEKIT_VITE_IMPORT_PATH = "@sentry/sveltekit/vite"; + +/** + * Returns the module `sentrySvelteKit` must be imported from for the installed + * SDK. v11 moved the Vite plugin to the `/vite` subpath and removed it from the + * root export, while v10 only has it on the root export. Unknown or unparseable + * versions fall back to whatever the wizard would install. + */ +export function getSentrySvelteKitVitePluginImportPath( + installedSdkVersion: string | undefined, +): string { + const sdkMajor = + getMajorVersion(installedSdkVersion) ?? + getMajorVersion(SENTRY_SVELTEKIT_SDK_RANGE) ?? + 0; + + return sdkMajor >= 11 + ? SENTRY_SVELTEKIT_VITE_IMPORT_PATH + : SENTRY_SVELTEKIT_ROOT_IMPORT_PATH; +} + +export type KitVersionBucket = + | "none" + | "invalid" + | "0.x" + | ">=1.0.0 <1.24.0" + | ">=1.24.0 <2.31.0" + | ">=2.31.0"; + +export function getKitVersionBucket( + version: string | undefined, +): KitVersionBucket { + if (!version) { + return "none"; + } + + try { + const minVer = minVersion(version); + if (!minVer) { + return "invalid"; + } + + if (lt(minVer, "1.0.0")) { + return "0.x"; + } + if (lt(minVer, "1.24.0")) { + return ">=1.0.0 <1.24.0"; + } + if (lt(minVer, "2.31.0")) { + // This is the version when the client-side invalidation fix was released + // https://github.com/sveltejs/kit/releases/tag/%40sveltejs%2Fkit%401.24.0 + // https://github.com/sveltejs/kit/pull/10576 + return ">=1.24.0 <2.31.0"; + } + // This is the version where sveltekit-native tracing and instrumentation was + // introduced as an experimental feature. + return ">=2.31.0"; + } catch (error) { + // `minVersion` throws for a range it can't parse; the bucket says so. + debug(error); + return "invalid"; + } +} + +export function getSvelteVersionBucket( + version: string | undefined, +): "none" | "invalid" | "<3.0.0" | "3.x" | "4.x" | "5.x" | ">5.x" { + if (!version) { + return "none"; + } + + try { + const minVer = minVersion(version); + if (!minVer) { + return "invalid"; + } + + if (lt(minVer, "3.0.0")) { + return "<3.0.0"; + } + if (lt(minVer, "4.0.0")) { + return "3.x"; + } + if (lt(minVer, "5.0.0")) { + return "4.x"; + } + if (lt(minVer, "6.0.0")) { + return "5.x"; + } + // bucket for any future versions of svelte not covered by the other buckets + return ">5.x"; + } catch (error) { + // `minVersion` throws for a range it can't parse; the bucket says so. + debug(error); + return "invalid"; + } +} diff --git a/packages/cli/test/commands/wizard.test.ts b/packages/cli/test/commands/wizard.test.ts index 4a44c6815..39bb10e4b 100644 --- a/packages/cli/test/commands/wizard.test.ts +++ b/packages/cli/test/commands/wizard.test.ts @@ -18,6 +18,23 @@ vi.mock("../../src/lib/telemetry.js", async (importOriginal) => ({ isTelemetryEnabled, })); +const { runRemixWizard, runReactRouterWizard, runSvelteKitWizard } = vi.hoisted( + () => ({ + runRemixWizard: vi.fn<(options: unknown) => Promise>(), + runReactRouterWizard: vi.fn<(options: unknown) => Promise>(), + runSvelteKitWizard: vi.fn<(options: unknown) => Promise>(), + }), +); +vi.mock("../../src/lib/wizard/remix/remix-wizard.js", () => ({ + runRemixWizard, +})); +vi.mock("../../src/lib/wizard/react-router/react-router-wizard.js", () => ({ + runReactRouterWizard, +})); +vi.mock("../../src/lib/wizard/sveltekit/sveltekit-wizard.js", () => ({ + runSvelteKitWizard, +})); + import { parseWizardArguments, wizardCommand, @@ -243,6 +260,20 @@ describe("sentry wizard", () => { }, ); + test.each([ + ["remix", runRemixWizard], + ["reactRouter", runReactRouterWizard], + ["sveltekit", runSvelteKitWizard], + ])("runs the %s wizard", async (integration, runner) => { + await runWizardCommand({}, "acme/my-project", integration); + + expect(runner).toHaveBeenCalledWith( + expect.objectContaining({ + target: { type: "explicit", org: "acme", project: "my-project" }, + }), + ); + }); + const unported = INTEGRATION_IDS.find((id) => !hasWizardRunner(id)); test.runIf(unported)( diff --git a/packages/cli/test/lib/wizard/react-router/codemods/client-entry.test.ts b/packages/cli/test/lib/wizard/react-router/codemods/client-entry.test.ts new file mode 100644 index 000000000..2038964b4 --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/codemods/client-entry.test.ts @@ -0,0 +1,368 @@ +import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; +import { + existsSync, + mkdirSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import path from "node:path"; +import { instrumentClientEntry } from "../../../../../src/lib/wizard/react-router/codemods/client.entry.js"; + +vi.mock("@clack/prompts", () => { + const mock = { + log: { + warn: vi.fn(), + info: vi.fn(), + success: vi.fn(), + }, + }; + return { + default: mock, + ...mock, + }; +}); + +describe("instrumentClientEntry", () => { + const fixturesDir = path.join(__dirname, "fixtures", "client-entry"); + let tmpDir: string; + let tmpFile: string; + + beforeEach(() => { + vi.clearAllMocks(); + + // Create unique tmp directory for each test + tmpDir = path.join( + fixturesDir, + "tmp", + `test-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, + ); + tmpFile = path.join(tmpDir, "entry.client.tsx"); + + // Ensure tmp directory exists + mkdirSync(tmpDir, { recursive: true }); + }); + + afterEach(() => { + // Clean up tmp directory + if (existsSync(tmpDir)) { + rmSync(tmpDir, { recursive: true }); + } + }); + + it("should add Sentry import and initialization with all features enabled", async () => { + const basicContent = readFileSync( + path.join(fixturesDir, "basic.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, basicContent); + + await instrumentClientEntry( + tmpFile, + "test-dsn", + true, + true, + false, + false, + true, + ); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).toContain( + 'import * as Sentry from "@sentry/react-router";', + ); + expect(modifiedContent).toContain("Sentry.init({"); + expect(modifiedContent).toContain('dsn: "test-dsn"'); + expect(modifiedContent).toContain("integrations: ["); + expect(modifiedContent).toContain("Sentry.reactRouterTracingIntegration()"); + expect(modifiedContent).toContain("Sentry.replayIntegration("); + expect(modifiedContent).toContain("onError={Sentry.sentryOnError}"); + }); + + it("should add Sentry initialization with only tracing enabled", async () => { + const basicContent = readFileSync( + path.join(fixturesDir, "basic.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, basicContent); + + await instrumentClientEntry(tmpFile, "test-dsn", true, false, false); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).toContain( + 'import * as Sentry from "@sentry/react-router";', + ); + expect(modifiedContent).toContain("Sentry.init({"); + expect(modifiedContent).toContain('dsn: "test-dsn"'); + expect(modifiedContent).toContain("integrations: ["); + expect(modifiedContent).toContain("Sentry.reactRouterTracingIntegration()"); + expect(modifiedContent).not.toContain("Sentry.replayIntegration()"); + }); + + it("should add Sentry initialization with only replay enabled", async () => { + const basicContent = readFileSync( + path.join(fixturesDir, "basic.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, basicContent); + + await instrumentClientEntry(tmpFile, "test-dsn", false, true, false); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).toContain( + 'import * as Sentry from "@sentry/react-router";', + ); + expect(modifiedContent).toContain("Sentry.init({"); + expect(modifiedContent).toContain('dsn: "test-dsn"'); + expect(modifiedContent).toContain("integrations: ["); + expect(modifiedContent).not.toContain( + "Sentry.reactRouterTracingIntegration()", + ); + expect(modifiedContent).toContain("Sentry.replayIntegration("); + }); + + it("should add minimal Sentry initialization when all features are disabled", async () => { + const basicContent = readFileSync( + path.join(fixturesDir, "basic.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, basicContent); + + await instrumentClientEntry(tmpFile, "test-dsn", false, false, false); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).toContain( + 'import * as Sentry from "@sentry/react-router";', + ); + expect(modifiedContent).toContain("Sentry.init({"); + expect(modifiedContent).toContain('dsn: "test-dsn"'); + expect(modifiedContent).toContain("integrations: []"); + expect(modifiedContent).not.toContain( + "Sentry.reactRouterTracingIntegration()", + ); + expect(modifiedContent).not.toContain("Sentry.replayIntegration()"); + }); + + it("should write the dataCollection preset when reduceDataCollection is true", async () => { + const basicContent = readFileSync( + path.join(fixturesDir, "basic.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, basicContent); + + await instrumentClientEntry(tmpFile, "test-dsn", true, true, true); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).toContain("userInfo: false,"); + expect(modifiedContent).toContain( + 'httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }', + ); + expect(modifiedContent).not.toContain("// userInfo: false,"); + expect(modifiedContent).not.toContain( + "uncomment the lines below. For more info visit:", + ); + }); + + it("should keep the commented dataCollection hint when reduceDataCollection is false", async () => { + const basicContent = readFileSync( + path.join(fixturesDir, "basic.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, basicContent); + + await instrumentClientEntry(tmpFile, "test-dsn", true, true, false); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).toContain("// userInfo: false,"); + expect(modifiedContent).toContain("// httpBodies: [],"); + expect(modifiedContent).toContain( + "uncomment the lines below. For more info visit:", + ); + }); + + it("should not add Sentry.init when Sentry content already exists but still add onError", async () => { + const withSentryContent = readFileSync( + path.join(fixturesDir, "with-sentry.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, withSentryContent); + + await instrumentClientEntry( + tmpFile, + "test-dsn", + true, + true, + false, + false, + true, + ); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + // Should not duplicate Sentry.init + const initCount = (modifiedContent.match(/Sentry\.init\(/g) || []).length; + expect(initCount).toBe(1); + + // Should still add onError prop to HydratedRouter + expect(modifiedContent).toContain("onError={Sentry.sentryOnError}"); + }); + + it("should insert Sentry initialization after imports", async () => { + const withImportsContent = readFileSync( + path.join(fixturesDir, "with-imports.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, withImportsContent); + + await instrumentClientEntry(tmpFile, "test-dsn", true, false, false); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).toContain( + 'import * as Sentry from "@sentry/react-router";', + ); + expect(modifiedContent).toContain("Sentry.init({"); + + // Check that the Sentry import is before the init call + const sentryImportIndex = modifiedContent.indexOf( + 'import * as Sentry from "@sentry/react-router";', + ); + const sentryInitIndex = modifiedContent.indexOf("Sentry.init({"); + expect(sentryImportIndex).toBeLessThan(sentryInitIndex); + }); + + it("should handle files with no imports", async () => { + const noImportsContent = readFileSync( + path.join(fixturesDir, "no-imports.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, noImportsContent); + + await instrumentClientEntry(tmpFile, "test-dsn", false, true, false); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).toContain( + 'import * as Sentry from "@sentry/react-router";', + ); + expect(modifiedContent).toContain("Sentry.init({"); + expect(modifiedContent).toContain("Sentry.replayIntegration("); + }); + + it("should preserve existing code structure", async () => { + const complexContent = readFileSync( + path.join(fixturesDir, "complex.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, complexContent); + + await instrumentClientEntry(tmpFile, "test-dsn", true, true, false); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).toContain( + 'import * as Sentry from "@sentry/react-router";', + ); + expect(modifiedContent).toContain("Sentry.init({"); + + // Original content should still be there + expect(modifiedContent).toContain("startTransition"); + expect(modifiedContent).toContain("hydrateRoot"); + expect(modifiedContent).toContain(""); + }); + + describe("Instrumentation API", () => { + it("should add instrumentation API setup when enabled", async () => { + const basicContent = readFileSync( + path.join(fixturesDir, "basic.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, basicContent); + + await instrumentClientEntry( + tmpFile, + "test-dsn", + true, + false, + false, + true, + ); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).toContain( + "const tracing = Sentry.reactRouterTracingIntegration();", + ); + expect(modifiedContent).toContain("integrations: [tracing]"); + expect(modifiedContent).toContain( + "instrumentations={[tracing.clientInstrumentation]}", + ); + }); + + it("should combine instrumentation API with replay", async () => { + const basicContent = readFileSync( + path.join(fixturesDir, "basic.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, basicContent); + + await instrumentClientEntry(tmpFile, "test-dsn", true, true, false, true); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).toContain( + "const tracing = Sentry.reactRouterTracingIntegration();", + ); + expect(modifiedContent).toContain( + "integrations: [tracing, Sentry.replayIntegration()]", + ); + expect(modifiedContent).toContain( + "instrumentations={[tracing.clientInstrumentation]}", + ); + }); + + it("should not use instrumentation API when useInstrumentationAPI is false", async () => { + const basicContent = readFileSync( + path.join(fixturesDir, "basic.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, basicContent); + + await instrumentClientEntry( + tmpFile, + "test-dsn", + true, + false, + false, + false, + ); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).not.toContain("const tracing"); + expect(modifiedContent).toContain( + "Sentry.reactRouterTracingIntegration()", + ); + expect(modifiedContent).not.toContain("instrumentations"); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/basic.tsx b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/basic.tsx new file mode 100644 index 000000000..08ab4ec35 --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/basic.tsx @@ -0,0 +1,12 @@ +import { startTransition, StrictMode } from "react"; +import { hydrateRoot } from "react-dom/client"; +import { HydratedRouter } from "react-router/dom"; + +startTransition(() => { + hydrateRoot( + document, + + + + ); +}); diff --git a/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/complex.tsx b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/complex.tsx new file mode 100644 index 000000000..87ab5bdca --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/complex.tsx @@ -0,0 +1,30 @@ +import { startTransition, StrictMode } from "react"; +import { hydrateRoot } from "react-dom/client"; +import { HydratedRouter } from "react-router/dom"; +import { SomeProvider } from "./providers"; +import { GlobalStyles } from "./styles"; + +// Some configuration +const config = { + enableTracing: true, + debugMode: false, +}; + +// Initialize the app +function initializeApp() { + console.log('Initializing app with config:', config); +} + +startTransition(() => { + initializeApp(); + + hydrateRoot( + document, + + + + + + + ); +}); diff --git a/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/no-imports.tsx b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/no-imports.tsx new file mode 100644 index 000000000..fcb950ad7 --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/no-imports.tsx @@ -0,0 +1,6 @@ +// Simple client entry without imports + +const element = document.getElementById('root'); +if (element) { + console.log('Starting app'); +} diff --git a/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/with-imports.tsx b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/with-imports.tsx new file mode 100644 index 000000000..d69b73c94 --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/with-imports.tsx @@ -0,0 +1,13 @@ +import { startTransition, StrictMode } from "react"; +import { hydrateRoot } from "react-dom/client"; +import { HydratedRouter } from "react-router/dom"; +import { SomeOtherImport } from "./some-module"; + +startTransition(() => { + hydrateRoot( + document, + + + + ); +}); diff --git a/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/with-sentry.tsx b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/with-sentry.tsx new file mode 100644 index 000000000..980a959e7 --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/with-sentry.tsx @@ -0,0 +1,18 @@ +import * as Sentry from '@sentry/react-router'; +import { startTransition, StrictMode } from "react"; +import { hydrateRoot } from "react-dom/client"; +import { HydratedRouter } from "react-router/dom"; + +Sentry.init({ + dsn: "existing-dsn", + tracesSampleRate: 1.0, +}); + +startTransition(() => { + hydrateRoot( + document, + + + + ); +}); diff --git a/packages/cli/test/lib/wizard/react-router/codemods/fixtures/server-entry/already-instrumented.tsx b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/server-entry/already-instrumented.tsx new file mode 100644 index 000000000..10ab95329 --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/server-entry/already-instrumented.tsx @@ -0,0 +1,28 @@ +import * as Sentry from '@sentry/react-router'; +import type { AppLoadContext, EntryContext } from 'react-router'; + +async function handleRequest( + request: Request, + responseStatusCode: number, + responseHeaders: Headers, + routerContext: EntryContext, + loadContext: AppLoadContext +) { + return new Response('Already instrumented', { + status: responseStatusCode, + headers: responseHeaders, + }); +} + +export async function handleError( + error: unknown, + { request }: { request: Request } +): Promise { + if (!request.signal.aborted) { + Sentry.captureException(error); + } + console.error(error); + return new Response('Internal Server Error', { status: 500 }); +} + +export default Sentry.wrapSentryHandleRequest(handleRequest); diff --git a/packages/cli/test/lib/wizard/react-router/codemods/fixtures/server-entry/basic.tsx b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/server-entry/basic.tsx new file mode 100644 index 000000000..7bc4603f8 --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/server-entry/basic.tsx @@ -0,0 +1,23 @@ +import type { AppLoadContext, EntryContext } from 'react-router'; +import { ServerRouter } from 'react-router'; +import { renderToString } from 'react-dom/server'; + +// Basic server entry file with no handleRequest or handleError functions +export default function handleRequest( + request: Request, + responseStatusCode: number, + responseHeaders: Headers, + routerContext: EntryContext, + loadContext: AppLoadContext +) { + const html = renderToString( + + ); + + responseHeaders.set('Content-Type', 'text/html'); + + return new Response(`${html}`, { + status: responseStatusCode, + headers: responseHeaders, + }); +} diff --git a/packages/cli/test/lib/wizard/react-router/codemods/fixtures/server-entry/entry-server-basic.ts b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/server-entry/entry-server-basic.ts new file mode 100644 index 000000000..f68bd1509 --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/server-entry/entry-server-basic.ts @@ -0,0 +1,5 @@ +import { createRequestHandler } from "@react-router/node"; + +export default createRequestHandler({ + build: require("./build"), +}); diff --git a/packages/cli/test/lib/wizard/react-router/codemods/fixtures/server-entry/variable-export.tsx b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/server-entry/variable-export.tsx new file mode 100644 index 000000000..24caa74de --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/server-entry/variable-export.tsx @@ -0,0 +1,31 @@ +import type { AppLoadContext, EntryContext } from 'react-router'; +import { ServerRouter } from 'react-router'; +import { renderToString } from 'react-dom/server'; + +// handleError declared as variable and exported directly +export const handleError = async ( + error: unknown, + { request }: { request: Request } +): Promise => { + console.error('Unhandled error:', error); + return new Response('Internal Server Error', { status: 500 }); +}; + +export default function handleRequest( + request: Request, + responseStatusCode: number, + responseHeaders: Headers, + routerContext: EntryContext, + loadContext: AppLoadContext +) { + const html = renderToString( + + ); + + responseHeaders.set('Content-Type', 'text/html'); + + return new Response(`${html}`, { + status: responseStatusCode, + headers: responseHeaders, + }); +} diff --git a/packages/cli/test/lib/wizard/react-router/codemods/react-router-config.test.ts b/packages/cli/test/lib/wizard/react-router/codemods/react-router-config.test.ts new file mode 100644 index 000000000..e17b9adc6 --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/codemods/react-router-config.test.ts @@ -0,0 +1,324 @@ +import { existsSync, promises } from "node:fs"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { log } from "@clack/prompts"; +import { + getReactRouterConfigFilename, + instrumentReactRouterConfig, +} from "../../../../../src/lib/wizard/react-router/codemods/react-router-config.js"; +import { configureReactRouterConfig } from "../../../../../src/lib/wizard/react-router/sdk-setup.js"; + +vi.mock("@clack/prompts", () => ({ + log: { + info: vi.fn(), + warn: vi.fn(), + success: vi.fn(), + }, +})); +vi.mock("node:fs", async () => { + const actual = await vi.importActual("node:fs"); + return { + ...actual, + existsSync: vi.fn(), + promises: { + ...actual.promises, + readFile: vi.fn(), + writeFile: vi.fn(), + }, + }; +}); + +describe("React Router Config File Instrumentation", () => { + const mockCwd = "/mock/project"; + + beforeEach(() => { + vi.clearAllMocks(); + vi.spyOn(process, "cwd").mockReturnValue(mockCwd); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + describe("instrumentReactRouterConfig", () => { + it("imports sentryOnBuildEnd from the given path when creating the config", async () => { + const writtenFiles: Record = {}; + vi.mocked(existsSync).mockReturnValue(false); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + await instrumentReactRouterConfig(true, "@sentry/react-router/vite"); + + const written = Object.values(writtenFiles)[0]; + expect(written).toContain( + 'import { sentryOnBuildEnd } from "@sentry/react-router/vite";', + ); + expect(written).not.toContain('from "@sentry/react-router";'); + }); + + it("imports sentryOnBuildEnd from the given path when modifying an existing config", async () => { + const writtenFiles: Record = {}; + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue( + `import type { Config } from "@react-router/dev/config"; + +export default { + ssr: true, +} satisfies Config; +`, + ); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + await instrumentReactRouterConfig(true, "@sentry/react-router/vite"); + + const written = Object.values(writtenFiles)[0]; + expect(written).toContain('from "@sentry/react-router/vite"'); + expect(written).toContain("sentryOnBuildEnd"); + expect(written).not.toContain('from "@sentry/react-router";'); + }); + + it("should create new config file if it does not exist", async () => { + const writtenFiles: Record = {}; + + vi.mocked(existsSync).mockReturnValue(false); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + const result = await instrumentReactRouterConfig(true); + + expect(result.ssrWasChanged).toBe(false); + + const configPath = path.join(mockCwd, "react-router.config.ts"); + expect(writtenFiles[configPath]).toContain("ssr: true"); + expect(writtenFiles[configPath]).toContain("sentryOnBuildEnd"); + expect(writtenFiles[configPath]).toContain("buildEnd:"); + }); + + it("should create .js config when TypeScript is not used", async () => { + const writtenFiles: Record = {}; + + vi.mocked(existsSync).mockReturnValue(false); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + await instrumentReactRouterConfig(false); + + const configPath = path.join(mockCwd, "react-router.config.js"); + expect(writtenFiles[configPath]).toBeDefined(); + // Verify JS config doesn't have TypeScript-only syntax + expect(writtenFiles[configPath]).not.toContain("import type"); + expect(writtenFiles[configPath]).not.toContain("satisfies Config"); + expect(writtenFiles[configPath]).toContain("sentryOnBuildEnd"); + expect(writtenFiles[configPath]).toContain("buildEnd:"); + }); + + it("should detect and skip if Sentry content already exists", async () => { + const existingConfig = `import { sentryOnBuildEnd } from '@sentry/react-router'; + +export default { + ssr: true, + buildEnd: async ({ viteConfig, reactRouterConfig, buildManifest }) => { + await sentryOnBuildEnd({ viteConfig, reactRouterConfig, buildManifest }); + } +};`; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue(existingConfig); + + const result = await instrumentReactRouterConfig(true); + + expect(result.ssrWasChanged).toBe(false); + }); + + it.each([ + [true, [], "react-router.config.ts"], + [false, [], "react-router.config.js"], + [true, ["react-router.config.js"], "react-router.config.js"], + [false, ["react-router.config.ts"], "react-router.config.ts"], + [ + true, + ["react-router.config.ts", "react-router.config.js"], + "react-router.config.ts", + ], + ])( + "getReactRouterConfigFilename(isTS: %s) with %j picks %s", + (isTS, existing, expected) => { + vi.mocked(existsSync).mockImplementation((filePath) => + existing.some((name) => filePath === path.join(mockCwd, name)), + ); + + expect(getReactRouterConfigFilename(isTS)).toBe(expected); + }, + ); + + it("names the existing .js config when configuring a TypeScript project", async () => { + vi.mocked(existsSync).mockImplementation( + (filePath) => filePath === path.join(mockCwd, "react-router.config.js"), + ); + vi.mocked(promises.readFile).mockResolvedValue( + "export default {\n ssr: true,\n};\n", + ); + vi.mocked(promises.writeFile).mockResolvedValue(); + + await configureReactRouterConfig(true, "@sentry/react-router"); + + expect(log.success).toHaveBeenCalledWith( + expect.stringContaining("react-router.config.js"), + ); + expect(log.success).not.toHaveBeenCalledWith( + expect.stringContaining("react-router.config.ts"), + ); + }); + + it("updates an existing react-router.config.js in a TypeScript project", async () => { + const writtenFiles: Record = {}; + vi.mocked(existsSync).mockImplementation( + (filePath) => filePath === path.join(mockCwd, "react-router.config.js"), + ); + vi.mocked(promises.readFile).mockResolvedValue( + "export default {\n ssr: true,\n};\n", + ); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + await instrumentReactRouterConfig(true); + + expect(Object.keys(writtenFiles)).toEqual([ + path.join(mockCwd, "react-router.config.js"), + ]); + expect( + writtenFiles[path.join(mockCwd, "react-router.config.js")], + ).toContain("sentryOnBuildEnd"); + }); + + it("should add buildEnd hook to existing config", async () => { + const existingConfig = `export default { + ssr: true, + async: false +};`; + + const writtenFiles: Record = {}; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue(existingConfig); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + const result = await instrumentReactRouterConfig(true); + + expect(result.ssrWasChanged).toBe(false); + + const writtenConfig = Object.values(writtenFiles)[0]; + expect(writtenConfig).toContain("sentryOnBuildEnd"); + expect(writtenConfig).toContain("buildEnd:"); + }); + + it("should set ssr: true if missing", async () => { + const existingConfig = `export default { + async: false +};`; + + const writtenFiles: Record = {}; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue(existingConfig); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + const result = await instrumentReactRouterConfig(true); + + expect(result.ssrWasChanged).toBe(true); + + const writtenConfig = Object.values(writtenFiles)[0]; + expect(writtenConfig).toContain("ssr: true"); + }); + + it('flips a quoted "ssr": false instead of adding a second key', async () => { + const existingConfig = `export default { + "ssr": false +};`; + + const writtenFiles: Record = {}; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue(existingConfig); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + const result = await instrumentReactRouterConfig(true); + + expect(result.ssrWasChanged).toBe(true); + const writtenConfig = Object.values(writtenFiles)[0]; + expect(writtenConfig).not.toContain("false"); + expect(writtenConfig?.match(/ssr/g)).toHaveLength(1); + }); + + it("should report ssrWasChanged when changing ssr from false to true", async () => { + const existingConfig = `export default { + ssr: false +};`; + + const writtenFiles: Record = {}; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue(existingConfig); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + const result = await instrumentReactRouterConfig(true); + + expect(result.ssrWasChanged).toBe(true); + + const writtenConfig = Object.values(writtenFiles)[0]; + expect(writtenConfig).toContain("ssr: true"); + }); + + it("throws when buildEnd already exists as a method", async () => { + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue( + "export default {\n ssr: true,\n async buildEnd() {\n await upload();\n },\n};\n", + ); + vi.mocked(promises.writeFile).mockResolvedValue(); + + await expect(instrumentReactRouterConfig(true)).rejects.toThrow( + "A buildEnd hook already exists", + ); + expect(promises.writeFile).not.toHaveBeenCalled(); + }); + + it("should throw error if buildEnd already exists", async () => { + const existingConfig = `export default { + ssr: true, + buildEnd: async () => { + console.log('existing hook'); + } +};`; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue(existingConfig); + + await expect(instrumentReactRouterConfig(true)).rejects.toThrow( + "A buildEnd hook already exists", + ); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/react-router/codemods/server-entry.test.ts b/packages/cli/test/lib/wizard/react-router/codemods/server-entry.test.ts new file mode 100644 index 000000000..72b6afb78 --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/codemods/server-entry.test.ts @@ -0,0 +1,683 @@ +import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; +import { + existsSync, + mkdirSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import path from "node:path"; +import recast from "recast"; +import { + instrumentServerEntry, + instrumentHandleRequest, + instrumentHandleError, +} from "../../../../../src/lib/wizard/react-router/codemods/server-entry.js"; + +import { loadFile, generateCode } from "magicast"; + +vi.mock("@clack/prompts", () => { + const mock = { + log: { + warn: vi.fn(), + info: vi.fn(), + success: vi.fn(), + }, + }; + return { + default: mock, + ...mock, + }; +}); + +vi.mock("../../../../../src/lib/wizard/utils/debug.js", () => ({ + debug: vi.fn(), +})); + +describe("instrumentServerEntry", () => { + const fixturesDir = path.join(__dirname, "fixtures", "server-entry"); + let tmpDir: string; + let tmpFile: string; + + beforeEach(() => { + vi.clearAllMocks(); + + // Create unique tmp directory for each test + tmpDir = path.join( + __dirname, + "fixtures", + "tmp", + `test-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, + ); + tmpFile = path.join(tmpDir, "entry.server.tsx"); + + // Ensure tmp directory exists + mkdirSync(tmpDir, { recursive: true }); + }); + + afterEach(() => { + // Clean up tmp directory + if (existsSync(tmpDir)) { + rmSync(tmpDir, { recursive: true }); + } + }); + + it("should add Sentry import and wrap handleRequest function", async () => { + const basicContent = readFileSync( + path.join(fixturesDir, "basic.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, basicContent); + + await instrumentServerEntry(tmpFile); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + // Should add Sentry import + expect(modifiedContent).toContain( + 'import * as Sentry from "@sentry/react-router";', + ); + + // Should wrap the existing handleRequest function + expect(modifiedContent).toContain( + "export default Sentry.wrapSentryHandleRequest(handleRequest);", + ); + + // Should add the Sentry import at the top of the file (after existing imports) + const lines = modifiedContent.split("\n"); + const sentryImportLine = lines.findIndex((line) => + line.includes('import * as Sentry from "@sentry/react-router";'), + ); + expect(sentryImportLine).toBeGreaterThanOrEqual(0); + + // Should make handleRequest async + expect(modifiedContent).toMatch(/async function handleRequest/); + + // Should create default handleError since none exists + expect(modifiedContent).toContain( + "export const handleError = Sentry.createSentryHandleError({", + ); + expect(modifiedContent).toContain("logErrors: false"); + }); + + it("should handle already instrumented server entry without duplication", async () => { + const alreadyInstrumentedContent = readFileSync( + path.join(fixturesDir, "already-instrumented.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, alreadyInstrumentedContent); + + await instrumentServerEntry(tmpFile); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + // Should not add duplicate imports or wrapping since already instrumented + expect(modifiedContent).toContain( + "import * as Sentry from '@sentry/react-router';", + ); + expect(modifiedContent).toContain( + "export default Sentry.wrapSentryHandleRequest(handleRequest);", + ); + + // Should NOT add a new createSentryHandleError export since handleError already has captureException + expect(modifiedContent).not.toContain( + "export const handleError = Sentry.createSentryHandleError({", + ); + + // Should preserve the existing handleError function with captureException + expect(modifiedContent).toContain("Sentry.captureException(error);"); + expect(modifiedContent).toContain("export async function handleError"); + }); + + it("should handle variable export pattern with existing export", async () => { + const variableExportContent = readFileSync( + path.join(fixturesDir, "variable-export.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, variableExportContent); + + await instrumentServerEntry(tmpFile); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + // Should add Sentry import and wrap handleRequest + expect(modifiedContent).toContain( + 'import * as Sentry from "@sentry/react-router";', + ); + expect(modifiedContent).toContain( + "export default Sentry.wrapSentryHandleRequest(handleRequest);", + ); + + // Should instrument the existing handleError variable with captureException + expect(modifiedContent).toContain("Sentry.captureException(error);"); + + // Should preserve the variable export pattern + expect(modifiedContent).toContain("export const handleError"); + }); + + it("should not add duplicate async keyword when handleRequest is already async", async () => { + const asyncContent = ` +import { ServerRouter } from 'react-router'; +import { renderToString } from 'react-dom/server'; + +export default async function handleRequest(request: Request) { + const html = renderToString(); + return new Response(html); +} +`; + writeFileSync(tmpFile, asyncContent); + + await instrumentServerEntry(tmpFile); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + // Should have async function handleRequest (not async async) + expect(modifiedContent).toMatch(/async function handleRequest/); + expect(modifiedContent).not.toMatch(/async\s+async/); + expect(modifiedContent).toContain( + "export default Sentry.wrapSentryHandleRequest(handleRequest);", + ); + }); +}); + +describe("instrumentHandleRequest", () => { + let tmpDir: string; + + beforeEach(() => { + tmpDir = path.join( + __dirname, + "fixtures", + "tmp", + `handle-request-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, + ); + mkdirSync(tmpDir, { recursive: true }); + }); + + afterEach(() => { + if (existsSync(tmpDir)) { + rmSync(tmpDir, { recursive: true }); + } + }); + + it("should add required imports when creating new handleRequest", async () => { + const content = `// Empty server entry file`; + const tempFile = path.join(tmpDir, "entry.server.tsx"); + writeFileSync(tempFile, content); + + const mod = await loadFile(tempFile); + instrumentHandleRequest(mod); + + // Check if required imports were added + const imports = mod.imports.$items; + const hasServerRouter = imports.some( + (item: any) => + item.imported === "ServerRouter" && item.from === "react-router", + ); + const hasRenderToPipeableStream = imports.some( + (item: any) => + item.imported === "renderToPipeableStream" && + item.from === "react-dom/server", + ); + + expect(hasServerRouter).toBe(true); + expect(hasRenderToPipeableStream).toBe(true); + }); + + it("should not duplicate imports if they already exist", async () => { + const content = ` +import { ServerRouter } from 'react-router'; +import { renderToPipeableStream } from 'react-dom/server'; +import { createReadableStreamFromReadable } from '@react-router/node'; +`; + const tempFile = path.join(tmpDir, "entry.server.tsx"); + writeFileSync(tempFile, content); + + const mod = await loadFile(tempFile); + const originalImportsCount = mod.imports.$items.length; + + instrumentHandleRequest(mod); + + // Should not add duplicate imports + expect(mod.imports.$items.length).toBe(originalImportsCount); + }); +}); + +describe("instrumentHandleError", () => { + let tmpDir: string; + + beforeEach(() => { + tmpDir = path.join( + __dirname, + "fixtures", + "tmp", + `handle-error-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, + ); + mkdirSync(tmpDir, { recursive: true }); + }); + + afterEach(() => { + if (existsSync(tmpDir)) { + rmSync(tmpDir, { recursive: true }); + } + }); + + it("should not modify existing handleError with captureException", async () => { + const content = ` +export function handleError(error: unknown) { + Sentry.captureException(error); + console.error(error); +} +`; + const tempFile = path.join(tmpDir, "entry.server.tsx"); + writeFileSync(tempFile, content); + + const mod = await loadFile(tempFile); + const originalBodyLength = (mod.$ast as any).body.length; + + instrumentHandleError(mod); + + // Should not modify since captureException already exists + expect((mod.$ast as any).body.length).toBe(originalBodyLength); + }); + + it("should not modify existing handleError with createSentryHandleError", async () => { + const content = ` +export const handleError = Sentry.createSentryHandleError({ + logErrors: false +}); +`; + const tempFile = path.join(tmpDir, "entry.server.tsx"); + writeFileSync(tempFile, content); + + const mod = await loadFile(tempFile); + const originalBodyLength = (mod.$ast as any).body.length; + + instrumentHandleError(mod); + + // Should not modify since createSentryHandleError already exists + expect((mod.$ast as any).body.length).toBe(originalBodyLength); + }); + + it("should add captureException to existing handleError function declaration without breaking AST", async () => { + const content = ` +export function handleError(error: unknown) { + console.error('Custom error handling:', error); + // some other logic here +} +`; + const tempFile = path.join(tmpDir, "entry.server.tsx"); + writeFileSync(tempFile, content); + + const mod = await loadFile(tempFile); + + // This should not throw an error due to broken AST manipulation + expect(() => instrumentHandleError(mod)).not.toThrow(); + + // Verify the function was modified correctly + const modifiedCode = generateCode(mod.$ast).code; + expect(modifiedCode).toContain("Sentry.captureException(error)"); + expect(modifiedCode).toContain( + "console.error('Custom error handling:', error)", + ); + }); + + it("should add captureException to existing handleError variable declaration without breaking AST", async () => { + const content = ` +export const handleError = (error: unknown, { request }: { request: Request }) => { + console.log('Handling error:', error.message); + return new Response('Error occurred', { status: 500 }); +}; +`; + const tempFile = path.join(tmpDir, "entry.server.tsx"); + writeFileSync(tempFile, content); + + const mod = await loadFile(tempFile); + + // This should not throw an error due to broken AST manipulation + expect(() => instrumentHandleError(mod)).not.toThrow(); + + // Verify the function was modified correctly + const modifiedCode = generateCode(mod.$ast).code; + expect(modifiedCode).toContain("Sentry.captureException(error)"); + expect(modifiedCode).toContain( + "console.log('Handling error:', error.message)", + ); + }); + + it("should handle existing handleError with only error parameter and add request parameter", async () => { + const content = ` +export const handleError = (error: unknown) => { + console.error('Simple error handler:', error); +}; +`; + const tempFile = path.join(tmpDir, "entry.server.tsx"); + writeFileSync(tempFile, content); + + const mod = await loadFile(tempFile); + + // This should not throw an error due to broken AST manipulation + expect(() => instrumentHandleError(mod)).not.toThrow(); + + // Verify the function signature was updated correctly + const modifiedCode = generateCode(mod.$ast).code; + expect(modifiedCode).toContain("Sentry.captureException(error)"); + expect(modifiedCode).toContain("if (!request.signal.aborted)"); + // Should add request parameter + expect(modifiedCode).toMatch( + /handleError.*=.*\(\s*error.*,\s*\{\s*request\s*\}/, + ); + }); +}); + +describe("instrumentHandleError AST manipulation edge cases", () => { + let tmpDir: string; + + beforeEach(() => { + tmpDir = path.join( + __dirname, + "fixtures", + "tmp", + `ast-edge-cases-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, + ); + mkdirSync(tmpDir, { recursive: true }); + }); + + afterEach(() => { + if (existsSync(tmpDir)) { + rmSync(tmpDir, { recursive: true }); + } + }); + + it("should handle function declaration with existing try-catch block", async () => { + const content = ` +export function handleError(error: unknown, { request }: { request: Request }) { + try { + console.error('Error occurred:', error); + logToExternalService(error); + } catch (loggingError) { + console.warn('Failed to log error:', loggingError); + } +} +`; + const tempFile = path.join(tmpDir, "entry.server.tsx"); + writeFileSync(tempFile, content); + + const mod = await loadFile(tempFile); + + // This test will expose the broken AST logic + expect(() => instrumentHandleError(mod)).not.toThrow(); + + const modifiedCode = generateCode(mod.$ast).code; + expect(modifiedCode).toContain("Sentry.captureException(error)"); + expect(modifiedCode).toContain("if (!request.signal.aborted)"); + // Should preserve existing try-catch + expect(modifiedCode).toContain("try {"); + expect(modifiedCode).toContain("} catch (loggingError) {"); + }); + + it("should handle arrow function with block body", async () => { + const content = ` +export const handleError = (error: unknown, context: any) => { + const { request } = context; + console.error('Error in route:', error); + return new Response('Internal Server Error', { status: 500 }); +}; +`; + const tempFile = path.join(tmpDir, "entry.server.tsx"); + writeFileSync(tempFile, content); + + const mod = await loadFile(tempFile); + + // This test will expose the broken AST logic + expect(() => instrumentHandleError(mod)).not.toThrow(); + + const modifiedCode = generateCode(mod.$ast).code; + expect(modifiedCode).toContain("Sentry.captureException(error)"); + expect(modifiedCode).toContain("if (!request.signal.aborted)"); + }); + + it("should demonstrate that the AST bug is now fixed - no longer throws TypeError", async () => { + const content = ` +export function handleError(error: unknown) { + console.error('Error occurred:', error); +} +`; + const tempFile = path.join(tmpDir, "entry.server.tsx"); + writeFileSync(tempFile, content); + + const mod = await loadFile(tempFile); + + // This test specifically targets the broken AST logic at lines 279-284 in server-entry.ts + // The bug is in this code: + // implementation.declarations[0].init.arguments[0].body.body.unshift(...) + // Where 'implementation' is an IfStatement, not a VariableDeclaration + + let thrownError: Error | null = null; + try { + instrumentHandleError(mod); + } catch (error) { + thrownError = error as Error; + } + + // The bug is fixed - no error should be thrown + expect(thrownError).toBeNull(); + + // And the code should be successfully modified + const modifiedCode = generateCode(mod.$ast).code; + expect(modifiedCode).toContain("Sentry.captureException(error)"); + + // The error occurs because recast.parse() creates an IfStatement: + // { type: 'IfStatement', test: ..., consequent: ... } + // But the code tries to access .declarations[0] as if it were a VariableDeclaration + }); + + it("should demonstrate the specific line that breaks - recast.parse creates IfStatement not VariableDeclaration", () => { + // This test shows exactly what the problematic line 278 in server-entry.ts creates + const problematicCode = `if (!request.signal.aborted) { + Sentry.captureException(error); +}`; + + // This is what line 278 does: recast.parse(problematicCode).program.body[0] + const implementation = recast.parse(problematicCode).program.body[0]; + + // The implementation is an IfStatement, not a VariableDeclaration + expect(implementation.type).toBe("IfStatement"); + expect(implementation.declarations).toBeUndefined(); + + // But lines 279-284 try to access implementation.declarations[0].init.arguments[0].body.body + // This will throw "Cannot read properties of undefined (reading '0')" + expect(() => { + const declarations = implementation.declarations; + return declarations[0]; // This line will throw the error + }).toThrow("Cannot read properties of undefined"); + }); +}); + +// Test for Bug #1: Array access vulnerability +describe("Array access vulnerability bugs", () => { + let tmpDir: string; + let tmpFile: string; + + beforeEach(() => { + vi.clearAllMocks(); + + // Create unique tmp directory for each test + tmpDir = path.join( + __dirname, + "fixtures", + "tmp", + `test-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, + ); + tmpFile = path.join(tmpDir, "entry.server.tsx"); + + // Ensure tmp directory exists + mkdirSync(tmpDir, { recursive: true }); + }); + + afterEach(() => { + // Clean up tmp directory + if (existsSync(tmpDir)) { + rmSync(tmpDir, { recursive: true, force: true }); + } + }); + + it("should safely handle VariableDeclaration with empty declarations array", () => { + // This test verifies that the bug fix works correctly + // Previously this would crash, but now it handles empty arrays safely + + // The implementation now includes proper safety checks, so we test that + // it can handle edge cases without crashing + + // Test the actual safe implementation behavior + const testResult = () => { + // Simulate the safe check logic from the actual implementation + const declarations: any[] = []; // Empty array + if (declarations.length === 0) { + return false; // Safe early return + } + // This code would never be reached due to the safe check + return declarations[0].id.name === "handleError"; + }; + + // Should return false safely without throwing + expect(testResult()).toBe(false); + }); + + it("should safely handle VariableDeclaration with empty declarations array after fix", async () => { + // This test will pass after we fix the bug + + writeFileSync(tmpFile, "export const handleError = () => {};"); + const mod = await loadFile(tmpFile); + + // Create a problematic AST structure + const problematicNode = { + type: "ExportNamedDeclaration", + declaration: { + type: "VariableDeclaration", + kind: "const", + declarations: [], // Empty declarations array + }, + }; + + // Add the problematic node to the AST + // @ts-expect-error - We need to access body for this test even though it's typed as any + (mod.$ast.body as any[]).push(problematicNode); + + // After the fix, this should NOT throw an error + let thrownError = null; + try { + instrumentHandleError(mod); + } catch (error) { + thrownError = error; + } + + // After the fix, no error should be thrown + expect(thrownError).toBeNull(); + }); +}); + +describe("Instrumentation API", () => { + const fixturesDir = path.join(__dirname, "fixtures", "server-entry"); + let tmpDir: string; + let tmpFile: string; + + beforeEach(() => { + vi.clearAllMocks(); + + tmpDir = path.join( + __dirname, + "fixtures", + "tmp", + `test-instrumentation-api-${Date.now()}-${Math.random() + .toString(36) + .substring(2, 11)}`, + ); + tmpFile = path.join(tmpDir, "entry.server.tsx"); + + mkdirSync(tmpDir, { recursive: true }); + }); + + afterEach(() => { + if (existsSync(tmpDir)) { + rmSync(tmpDir, { recursive: true }); + } + }); + + it("should add instrumentations export when useInstrumentationAPI is true", async () => { + const basicContent = readFileSync( + path.join(fixturesDir, "basic.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, basicContent); + + await instrumentServerEntry(tmpFile, true); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).toContain( + 'import * as Sentry from "@sentry/react-router";', + ); + expect(modifiedContent).toContain( + "export const instrumentations = [Sentry.createSentryServerInstrumentation()];", + ); + }); + + it("should not add instrumentations export when useInstrumentationAPI is false", async () => { + const basicContent = readFileSync( + path.join(fixturesDir, "basic.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, basicContent); + + await instrumentServerEntry(tmpFile, false); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).not.toContain("instrumentations"); + expect(modifiedContent).not.toContain("createSentryServerInstrumentation"); + }); + + it("should not duplicate instrumentations export if already present", async () => { + const contentWithInstrumentations = ` +import { ServerRouter } from 'react-router'; +import * as Sentry from '@sentry/react-router'; + +export default function handleRequest() {} +export const handleError = () => {}; +export const instrumentations = [Sentry.createSentryServerInstrumentation()]; +`; + + writeFileSync(tmpFile, contentWithInstrumentations); + + await instrumentServerEntry(tmpFile, true); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + const count = (modifiedContent.match(/\binstrumentations\b/g) || []).length; + expect(count).toBe(1); + }); + + it("should not duplicate if legacy unstable_instrumentations export is already present", async () => { + const contentWithLegacy = ` +import { ServerRouter } from 'react-router'; +import * as Sentry from '@sentry/react-router'; + +export default function handleRequest() {} +export const handleError = () => {}; +export const unstable_instrumentations = [Sentry.createSentryServerInstrumentation()]; +`; + + writeFileSync(tmpFile, contentWithLegacy); + + await instrumentServerEntry(tmpFile, true); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).not.toContain("export const instrumentations ="); + }); +}); diff --git a/packages/cli/test/lib/wizard/react-router/codemods/vite.test.ts b/packages/cli/test/lib/wizard/react-router/codemods/vite.test.ts new file mode 100644 index 000000000..12232b891 --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/codemods/vite.test.ts @@ -0,0 +1,343 @@ +import { existsSync, promises } from "node:fs"; +import type { namedTypes as t } from "ast-types"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + addReactRouterPluginToViteConfig, + getViteConfigFilename, + instrumentViteConfig, +} from "../../../../../src/lib/wizard/react-router/codemods/vite.js"; + +vi.mock("@clack/prompts", () => ({ + log: { + info: vi.fn(), + warn: vi.fn(), + success: vi.fn(), + }, +})); +vi.mock("node:fs", async () => { + const actual = await vi.importActual("node:fs"); + return { + ...actual, + existsSync: vi.fn(), + promises: { + ...actual.promises, + readFile: vi.fn(), + writeFile: vi.fn(), + }, + }; +}); + +describe("Vite Config Instrumentation", () => { + const mockCwd = "/mock/project"; + + beforeEach(() => { + vi.clearAllMocks(); + vi.spyOn(process, "cwd").mockReturnValue(mockCwd); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + describe("instrumentViteConfig", () => { + it("imports sentryReactRouter from the given path and keeps the package name in optimizeDeps.exclude", async () => { + const writtenFiles: Record = {}; + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue( + `import { defineConfig } from 'vite'; + +export default defineConfig({ + plugins: [] +});`, + ); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + await instrumentViteConfig( + "my-org", + "my-project", + "@sentry/react-router/vite", + ); + + const written = Object.values(writtenFiles)[0]; + expect(written).toContain( + 'import { sentryReactRouter } from "@sentry/react-router/vite";', + ); + expect(written).not.toContain('from "@sentry/react-router";'); + expect(written).toMatch( + /exclude:\s*\[\s*["']@sentry\/react-router["']\s*\]/, + ); + }); + + it("should throw error if vite config file does not exist", async () => { + vi.mocked(existsSync).mockReturnValue(false); + + await expect( + instrumentViteConfig("my-org", "my-project"), + ).rejects.toThrow("Could not find vite.config.ts or vite.config.js"); + }); + + it("should detect and skip if Sentry content already exists", async () => { + const existingConfig = `import { defineConfig } from 'vite'; +import { sentryReactRouter } from '@sentry/react-router'; + +export default defineConfig({ + plugins: [sentryReactRouter({ org: "my-org", project: "my-project" }, config)] +});`; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue(existingConfig); + + const result = await instrumentViteConfig("my-org", "my-project"); + + expect(result.wasConverted).toBe(false); + }); + + it("should add sentryReactRouter plugin and convert to function form", async () => { + const simpleConfig = `import { defineConfig } from 'vite'; + +export default defineConfig({ + plugins: [] +});`; + + const writtenFiles: Record = {}; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue(simpleConfig); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + const result = await instrumentViteConfig("my-org", "my-project"); + + expect(result.wasConverted).toBe(true); + + const writtenConfig = Object.values(writtenFiles)[0]; + expect(writtenConfig).toContain("sentryReactRouter"); + expect(writtenConfig).toContain('org: "my-org"'); + expect(writtenConfig).toContain('project: "my-project"'); + expect(writtenConfig).toContain("config =>"); + expect(writtenConfig).toContain("optimizeDeps"); + expect(writtenConfig).toMatch(/exclude.*@sentry\/react-router/s); + }); + + it("should work with existing function form", async () => { + const functionConfig = `import { defineConfig } from 'vite'; + +export default defineConfig(config => ({ + plugins: [] +}));`; + + const writtenFiles: Record = {}; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue(functionConfig); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + const result = await instrumentViteConfig("my-org", "my-project"); + + expect(result.wasConverted).toBe(false); + + const writtenConfig = Object.values(writtenFiles)[0]; + expect(writtenConfig).toContain("sentryReactRouter"); + expect(writtenConfig).toContain('org: "my-org"'); + expect(writtenConfig).toContain('project: "my-project"'); + expect(writtenConfig).toContain("optimizeDeps"); + expect(writtenConfig).toMatch(/exclude.*@sentry\/react-router/s); + }); + + it("should add @sentry/react-router to existing optimizeDeps.exclude", async () => { + const configWithExistingExclude = `import { defineConfig } from 'vite'; + +export default defineConfig(config => ({ + plugins: [], + optimizeDeps: { + exclude: ["some-other-package"], + }, +}));`; + + const writtenFiles: Record = {}; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue(configWithExistingExclude); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + const result = await instrumentViteConfig("my-org", "my-project"); + + expect(result.wasConverted).toBe(false); + + const writtenConfig = Object.values(writtenFiles)[0]; + expect(writtenConfig).toContain("sentryReactRouter"); + expect(writtenConfig).toContain("some-other-package"); + expect(writtenConfig).toMatch(/exclude.*@sentry\/react-router/s); + }); + + it("should not duplicate exclude entry on repeated calls", async () => { + const configContent = `import { defineConfig } from 'vite'; + +export default defineConfig({ + plugins: [], +});`; + + const { parseModule, generateCode } = await import("magicast"); + const mod = parseModule(configContent); + const program = mod.$ast as t.Program; + + addReactRouterPluginToViteConfig(program, "my-org", "my-project"); + addReactRouterPluginToViteConfig(program, "my-org", "my-project"); + + const output = generateCode(mod).code; + const excludeMatches = + output.match(/exclude.*@sentry\/react-router/gs) ?? []; + expect(excludeMatches).toHaveLength(1); + }); + + it("should skip non-object optimizeDeps", async () => { + const configWithFunctionOptimizeDeps = `import { defineConfig } from 'vite'; +import { getOptimizeDeps } from './config-utils'; + +export default defineConfig(config => ({ + plugins: [], + optimizeDeps: getOptimizeDeps(), +}));`; + + const writtenFiles: Record = {}; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue( + configWithFunctionOptimizeDeps, + ); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + const result = await instrumentViteConfig("my-org", "my-project"); + + expect(result.wasConverted).toBe(false); + + const writtenConfig = Object.values(writtenFiles)[0]; + expect(writtenConfig).toContain("sentryReactRouter"); + expect(writtenConfig).toContain("getOptimizeDeps()"); + }); + + it("should skip non-array optimizeDeps.exclude", async () => { + const configWithFunctionExclude = `import { defineConfig } from 'vite'; +import { getExcludes } from './config-utils'; + +export default defineConfig(config => ({ + plugins: [], + optimizeDeps: { + exclude: getExcludes(), + }, +}));`; + + const writtenFiles: Record = {}; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue(configWithFunctionExclude); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + const result = await instrumentViteConfig("my-org", "my-project"); + + expect(result.wasConverted).toBe(false); + + const writtenConfig = Object.values(writtenFiles)[0]; + expect(writtenConfig).toContain("sentryReactRouter"); + expect(writtenConfig).toContain("getExcludes()"); + expect(writtenConfig).not.toMatch(/exclude.*@sentry\/react-router/s); + }); + + it("should prefer vite.config.ts over vite.config.js", async () => { + const configContent = `import { defineConfig } from 'vite'; +export default defineConfig({ plugins: [] });`; + + const writtenFiles: Record = {}; + + // First call checks for vite.config.ts (returns true), second call validates it exists + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue(configContent); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + await instrumentViteConfig("my-org", "my-project"); + + // Should write to vite.config.ts, not vite.config.js + const writtenPath = Object.keys(writtenFiles)[0]; + expect(writtenPath).toContain("vite.config.ts"); + expect(writtenPath).not.toContain("vite.config.js"); + }); + + it("should work with function expression form", async () => { + const functionConfig = `import { defineConfig } from 'vite'; + +export default defineConfig(function(config) { + return { + plugins: [] + }; +});`; + + const writtenFiles: Record = {}; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue(functionConfig); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + const result = await instrumentViteConfig("my-org", "my-project"); + + expect(result.wasConverted).toBe(false); + + const writtenConfig = Object.values(writtenFiles)[0]; + expect(writtenConfig).toContain("sentryReactRouter"); + expect(writtenConfig).toContain('org: "my-org"'); + expect(writtenConfig).toContain('project: "my-project"'); + expect(writtenConfig).toContain("optimizeDeps"); + expect(writtenConfig).toMatch(/exclude.*@sentry\/react-router/s); + }); + }); +}); + +describe("getViteConfigFilename", () => { + beforeEach(() => { + vi.spyOn(process, "cwd").mockReturnValue("/mock/project"); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("names an existing vite.config.js in a TypeScript project", () => { + vi.mocked(existsSync).mockImplementation( + (p) => p === "/mock/project/vite.config.js", + ); + expect(getViteConfigFilename(true)).toBe("vite.config.js"); + }); + + it("prefers an existing vite.config.ts, as the codemod does", () => { + vi.mocked(existsSync).mockReturnValue(true); + expect(getViteConfigFilename(false)).toBe("vite.config.ts"); + }); + + it("falls back to the project language when neither exists", () => { + vi.mocked(existsSync).mockReturnValue(false); + expect(getViteConfigFilename(true)).toBe("vite.config.ts"); + expect(getViteConfigFilename(false)).toBe("vite.config.js"); + }); +}); diff --git a/packages/cli/test/lib/wizard/react-router/react-router-wizard.test.ts b/packages/cli/test/lib/wizard/react-router/react-router-wizard.test.ts new file mode 100644 index 000000000..8063c6ede --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/react-router-wizard.test.ts @@ -0,0 +1,83 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const { installPackageMock } = vi.hoisted(() => ({ + installPackageMock: vi.fn(), +})); + +vi.mock("../../../../src/lib/wizard/telemetry.js", () => ({ + Sentry: { setTag: vi.fn() }, + withTelemetry: (_options: unknown, callback: () => unknown) => callback(), + traceStep: (_name: string, callback: () => unknown) => callback(), +})); + +vi.mock("../../../../src/lib/wizard/utils/clack/index.js", () => ({ + printWelcome: vi.fn(), + getPackageDotJson: vi.fn(() => + Promise.resolve({ devDependencies: { "@react-router/dev": "^7.0.0" } }), + ), + isUsingTypeScript: vi.fn(() => true), + confirmContinueIfNoOrDirtyGitRepo: vi.fn(() => Promise.resolve()), + getOrAskForProjectData: vi.fn(() => + Promise.resolve({ + spotlight: false, + selfHosted: false, + sentryUrl: "https://sentry.io/", + authToken: "token", + selectedProject: { + id: "1", + slug: "project", + organization: { id: "1", slug: "org", name: "Org" }, + keys: [{ dsn: { public: "https://key@sentry.io/1" } }], + }, + }), + ), + printSdkV11MigrationGuideIfOutdated: vi.fn(), + installPackage: installPackageMock, +})); + +vi.mock("../../../../src/lib/wizard/utils/node-version.js", () => ({ + warnIfNodeVersionUnsupportedBySdkV11: vi.fn(), +})); + +import { runReactRouterWizard } from "../../../../src/lib/wizard/react-router/react-router-wizard.js"; +import { printWelcome } from "../../../../src/lib/wizard/utils/clack/index.js"; + +describe("runReactRouterWizard", () => { + beforeEach(() => { + vi.clearAllMocks(); + // Stop the wizard right after the SDK install; only its options matter. + installPackageMock.mockRejectedValue(new Error("stop after install")); + }); + + it.each([true, false])( + "passes forceInstall=%s to the SDK install", + async (forceInstall) => { + await expect( + runReactRouterWizard({ + telemetryEnabled: false, + forceInstall, + }), + ).rejects.toThrow("stop after install"); + + expect(installPackageMock).toHaveBeenCalledWith( + expect.objectContaining({ + packageNameDisplayLabel: "@sentry/react-router", + forceInstall, + }), + ); + }, + ); + + it.each([true, false])( + "shows the telemetry disclosure when telemetryEnabled=%s", + async (telemetryEnabled) => { + await expect( + runReactRouterWizard({ telemetryEnabled, forceInstall: false }), + ).rejects.toThrow("stop after install"); + + expect(printWelcome).toHaveBeenCalledWith( + expect.objectContaining({ telemetryEnabled }), + ); + }, + ); +}); diff --git a/packages/cli/test/lib/wizard/react-router/routes-config.test.ts b/packages/cli/test/lib/wizard/react-router/routes-config.test.ts new file mode 100644 index 000000000..57781f6b5 --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/routes-config.test.ts @@ -0,0 +1,227 @@ +import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; +import { + existsSync, + mkdirSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import path from "node:path"; +import { addRoutesToConfig } from "../../../../src/lib/wizard/react-router/codemods/routes-config.js"; + +vi.mock("@clack/prompts", () => { + const mock = { + log: { + warn: vi.fn(), + info: vi.fn(), + success: vi.fn(), + }, + }; + return { + default: mock, + ...mock, + }; +}); + +describe("addRoutesToConfig codemod", () => { + let tmpDir: string; + let appDir: string; + let routesConfigPath: string; + + beforeEach(() => { + vi.clearAllMocks(); + + // Create unique tmp directory for each test + tmpDir = path.join( + __dirname, + "tmp", + `test-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, + ); + appDir = path.join(tmpDir, "app"); + routesConfigPath = path.join(appDir, "routes.ts"); + + mkdirSync(appDir, { recursive: true }); + }); + + afterEach(() => { + // Clean up + if (existsSync(tmpDir)) { + rmSync(tmpDir, { recursive: true, force: true }); + } + }); + + it("should add routes to existing configuration", async () => { + // Create a routes.ts file + const routesContent = `import type { RouteConfig } from "@react-router/dev/routes"; +import { index, route } from "@react-router/dev/routes"; + +export default [ + index("routes/home.tsx"), + route("/about", "routes/about.tsx"), +] satisfies RouteConfig;`; + + writeFileSync(routesConfigPath, routesContent); + + await addRoutesToConfig(routesConfigPath, true); + + // Check that both routes were added + const updatedContent = readFileSync(routesConfigPath, "utf-8"); + expect(updatedContent).toContain( + 'route("/sentry-example-page", "routes/sentry-example-page.tsx")', + ); + expect(updatedContent).toContain( + 'route("/api/sentry-example-api", "routes/api.sentry-example-api.ts")', + ); + }); + + it("should add routes when the default export uses `as RouteConfig`", async () => { + writeFileSync( + routesConfigPath, + `import type { RouteConfig } from "@react-router/dev/routes"; +import { index, route } from "@react-router/dev/routes"; + +export default [index("routes/home.tsx")] as RouteConfig;`, + ); + + await addRoutesToConfig(routesConfigPath, true); + + const updatedContent = readFileSync(routesConfigPath, "utf-8"); + expect(updatedContent).toContain( + 'route("/sentry-example-page", "routes/sentry-example-page.tsx")', + ); + expect(updatedContent).toContain( + 'route("/api/sentry-example-api", "routes/api.sentry-example-api.ts")', + ); + }); + + it("should throw when the default export is not an array literal", async () => { + const routesContent = `import { flatRoutes } from "@react-router/fs-routes"; + +export default flatRoutes();`; + writeFileSync(routesConfigPath, routesContent); + + await expect(addRoutesToConfig(routesConfigPath, true)).rejects.toThrow( + "not an array literal", + ); + expect(readFileSync(routesConfigPath, "utf-8")).toBe(routesContent); + }); + + it("should handle JavaScript projects correctly", async () => { + // Create a routes.ts file + const routesContent = `import type { RouteConfig } from "@react-router/dev/routes"; +import { index, route } from "@react-router/dev/routes"; + +export default [ + index("routes/home.jsx"), +] satisfies RouteConfig;`; + + writeFileSync(routesConfigPath, routesContent); + + await addRoutesToConfig(routesConfigPath, false); // JavaScript project + + // Check that both routes were added with .jsx/.js extensions + const updatedContent = readFileSync(routesConfigPath, "utf-8"); + expect(updatedContent).toContain( + 'route("/sentry-example-page", "routes/sentry-example-page.jsx")', + ); + expect(updatedContent).toContain( + 'route("/api/sentry-example-api", "routes/api.sentry-example-api.js")', + ); + }); + + it("should not duplicate routes if they already exist", async () => { + // Create a routes.ts file with both routes already present + const routesContent = `import type { RouteConfig } from "@react-router/dev/routes"; +import { index, route } from "@react-router/dev/routes"; + +export default [ + index("routes/home.tsx"), + route("/sentry-example-page", "routes/sentry-example-page.tsx"), + route("/api/sentry-example-api", "routes/api.sentry-example-api.ts"), +] satisfies RouteConfig;`; + + writeFileSync(routesConfigPath, routesContent); + + await addRoutesToConfig(routesConfigPath, true); + + // Check that the routes were not duplicated + const updatedContent = readFileSync(routesConfigPath, "utf-8"); + const pageRouteMatches = updatedContent.match( + /route\("\/sentry-example-page"/g, + ); + const apiRouteMatches = updatedContent.match( + /route\("\/api\/sentry-example-api"/g, + ); + expect(pageRouteMatches).toHaveLength(1); + expect(apiRouteMatches).toHaveLength(1); + }); + + it("should add route import when it does not exist", async () => { + // Create a routes.ts file without route import + const routesContent = `import type { RouteConfig } from "@react-router/dev/routes"; +import { index } from "@react-router/dev/routes"; + +export default [ + index("routes/home.tsx"), +] satisfies RouteConfig;`; + + writeFileSync(routesConfigPath, routesContent); + + await addRoutesToConfig(routesConfigPath, true); + + // Check that the route import was added + const updatedContent = readFileSync(routesConfigPath, "utf-8"); + expect(updatedContent).toContain("route"); + expect(updatedContent).toContain( + 'route("/sentry-example-page", "routes/sentry-example-page.tsx")', + ); + }); + + it("should create default export when it does not exist", async () => { + // Create a routes.ts file without default export + const routesContent = `import type { RouteConfig } from "@react-router/dev/routes"; +import { index, route } from "@react-router/dev/routes";`; + + writeFileSync(routesConfigPath, routesContent); + + await addRoutesToConfig(routesConfigPath, true); + + // Check that the default export was created + const updatedContent = readFileSync(routesConfigPath, "utf-8"); + expect(updatedContent).toContain("export default ["); + expect(updatedContent).toContain( + 'route("/sentry-example-page", "routes/sentry-example-page.tsx")', + ); + expect(updatedContent).toContain( + 'route("/api/sentry-example-api", "routes/api.sentry-example-api.ts")', + ); + }); + + it("should handle empty file gracefully", async () => { + // Create an empty routes.ts file + writeFileSync(routesConfigPath, ""); + + await addRoutesToConfig(routesConfigPath, true); + + // Check that everything was added from scratch + const updatedContent = readFileSync(routesConfigPath, "utf-8"); + expect(updatedContent).toContain( + 'import { route } from "@react-router/dev/routes";', + ); + expect(updatedContent).toContain("export default ["); + expect(updatedContent).toContain( + 'route("/sentry-example-page", "routes/sentry-example-page.tsx")', + ); + expect(updatedContent).toContain( + 'route("/api/sentry-example-api", "routes/api.sentry-example-api.ts")', + ); + }); + + it("should skip if file does not exist", async () => { + // Don't create the file + await addRoutesToConfig(routesConfigPath, true); + + // Should not create the file if it doesn't exist + expect(existsSync(routesConfigPath)).toBe(false); + }); +}); diff --git a/packages/cli/test/lib/wizard/react-router/sdk-example.test.ts b/packages/cli/test/lib/wizard/react-router/sdk-example.test.ts new file mode 100644 index 000000000..36e6c9f39 --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/sdk-example.test.ts @@ -0,0 +1,80 @@ +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("@clack/prompts", () => ({ + log: { info: vi.fn(), warn: vi.fn(), success: vi.fn() }, +})); + +import { log } from "@clack/prompts"; +import { createExamplePage } from "../../../../src/lib/wizard/react-router/sdk-example.js"; + +describe("createExamplePage", () => { + let tmpDir: string; + + beforeEach(() => { + tmpDir = mkdtempSync(path.join(tmpdir(), "react-router-example-test-")); + mkdirSync(path.join(tmpDir, "app"), { recursive: true }); + vi.spyOn(process, "cwd").mockReturnValue(tmpDir); + }); + + afterEach(() => { + vi.restoreAllMocks(); + rmSync(tmpDir, { recursive: true, force: true }); + }); + + it("registers the example routes in a JavaScript app/routes.js", async () => { + const routesConfigPath = path.join(tmpDir, "app", "routes.js"); + writeFileSync( + routesConfigPath, + `import { index } from "@react-router/dev/routes"; + +export default [index("routes/home.jsx")]; +`, + ); + + await createExamplePage({ + selfHosted: false, + orgSlug: "org", + projectId: "1", + url: "https://sentry.io/", + isTS: false, + projectDir: tmpDir, + }); + + const updated = readFileSync(routesConfigPath, "utf-8"); + expect(updated).toContain( + 'route("/sentry-example-page", "routes/sentry-example-page.jsx")', + ); + expect(updated).toContain( + 'route("/api/sentry-example-api", "routes/api.sentry-example-api.js")', + ); + }); + + it("gives JavaScript paths in the manual routes fallback", async () => { + writeFileSync( + path.join(tmpDir, "app", "routes.js"), + "export default routes;\n", + ); + + await createExamplePage({ + selfHosted: false, + orgSlug: "org", + projectId: "1", + url: "https://sentry.io/", + isTS: false, + projectDir: tmpDir, + }); + + expect(log.info).toHaveBeenCalledWith( + 'Please manually add these routes to your routes.js file: route("/sentry-example-page", "routes/sentry-example-page.jsx") and route("/api/sentry-example-api", "routes/api.sentry-example-api.js")', + ); + }); +}); diff --git a/packages/cli/test/lib/wizard/react-router/sdk-setup.test.ts b/packages/cli/test/lib/wizard/react-router/sdk-setup.test.ts new file mode 100644 index 000000000..80b4be7ab --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/sdk-setup.test.ts @@ -0,0 +1,794 @@ +import { describe, expect, it, vi, beforeEach } from "vitest"; + +const { clackMocks } = vi.hoisted(() => { + const info = vi.fn(); + const warn = vi.fn(); + const error = vi.fn(); + const success = vi.fn(); + const outro = vi.fn(); + const confirm = vi.fn(() => Promise.resolve(false)); // default to false for tests + + return { + clackMocks: { + info, + warn, + error, + success, + outro, + confirm, + }, + }; +}); + +vi.mock("@clack/prompts", () => { + return { + __esModule: true, + log: { + info: clackMocks.info, + warn: clackMocks.warn, + error: clackMocks.error, + success: clackMocks.success, + }, + outro: clackMocks.outro, + confirm: clackMocks.confirm, + }; +}); + +const { existsSyncMock, readFileSyncMock, writeFileSyncMock } = vi.hoisted( + () => { + return { + existsSyncMock: vi.fn(), + readFileSyncMock: vi.fn(), + writeFileSyncMock: vi.fn(), + }; + }, +); + +const { getPackageDotJsonMock, getPackageVersionMock } = vi.hoisted(() => ({ + getPackageDotJsonMock: vi.fn(), + getPackageVersionMock: vi.fn(), +})); + +vi.mock("../../../../src/lib/wizard/utils/package-json.js", () => ({ + getPackageDotJson: getPackageDotJsonMock, + getPackageVersion: getPackageVersionMock, +})); + +vi.mock("node:fs", async () => { + return { + ...(await vi.importActual("node:fs")), + existsSync: existsSyncMock, + readFileSync: readFileSyncMock, + writeFileSync: writeFileSyncMock, + promises: { + writeFile: vi.fn(), + }, + }; +}); + +// module-level mock for child_process.execSync +vi.mock("node:child_process", () => ({ + __esModule: true, + execSync: vi.fn(), +})); + +// mock showCopyPasteInstructions and makeCodeSnippet used by templates +vi.mock("../../../../src/lib/wizard/utils/clack/index.js", () => { + return { + __esModule: true, + showCopyPasteInstructions: vi.fn(() => Promise.resolve()), + makeCodeSnippet: vi.fn( + ( + _colors: boolean, + callback: ( + unchanged: (str: string) => string, + plus: (str: string) => string, + minus: (str: string) => string, + ) => string, + ) => { + // Mock implementation that just calls the callback with simple string functions + const unchanged = (str: string) => str; + const plus = (str: string) => `+ ${str}`; + const minus = (str: string) => `- ${str}`; + return callback(unchanged, plus, minus); + }, + ), + getPackageDotJson: getPackageDotJsonMock, + // Same contract as the real helper: a cancelled prompt stops the wizard. + abortIfCancelled: vi.fn(async (input: unknown) => { + const value = await input; + if (typeof value === "symbol") { + const { WizardExitError } = + await import("../../../../src/lib/errors.js"); + throw new WizardExitError(0); + } + return value; + }), + }; +}); + +import { + isReactRouterV7, + getReactRouterVersion, + supportsInstrumentationAPI, + supportsOnError, + runReactRouterReveal, + createServerInstrumentationFile, + tryRevealAndGetManualInstructions, + updatePackageJsonScripts, + getEntryFilename, +} from "../../../../src/lib/wizard/react-router/sdk-setup.js"; +import { execSync } from "node:child_process"; +import type { Mock } from "vitest"; +import { WizardExitError } from "../../../../src/lib/errors.js"; +import { getSentryInstrumentationServerContent } from "../../../../src/lib/wizard/react-router/templates.js"; + +describe("React Router SDK Setup", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.resetAllMocks(); + + getPackageVersionMock.mockImplementation( + ( + packageName: string, + packageJson: { + dependencies?: Record; + devDependencies?: Record; + }, + ) => { + if (packageJson.dependencies?.[packageName]) { + return packageJson.dependencies[packageName]; + } + if (packageJson.devDependencies?.[packageName]) { + return packageJson.devDependencies[packageName]; + } + return null; + }, + ); + }); + + describe("isReactRouterV7", () => { + it("should return true for React Router v7+ in dependencies or devDependencies", () => { + expect( + isReactRouterV7({ dependencies: { "@react-router/dev": "7.0.0" } }), + ).toBe(true); + expect( + isReactRouterV7({ dependencies: { "@react-router/dev": "^7.1.0" } }), + ).toBe(true); + expect( + isReactRouterV7({ + devDependencies: { "@react-router/dev": "7.1.0" }, + }), + ).toBe(true); + }); + + it("should return false for React Router v6 or missing dependency", () => { + expect( + isReactRouterV7({ dependencies: { "@react-router/dev": "6.28.0" } }), + ).toBe(false); + expect(isReactRouterV7({ dependencies: { react: "^18.0.0" } })).toBe( + false, + ); + expect(isReactRouterV7({})).toBe(false); + }); + }); + + describe("getReactRouterVersion", () => { + it("should coerce range version from package.json", () => { + expect( + getReactRouterVersion({ + dependencies: { "@react-router/dev": "^7.8.2" }, + }), + ).toBe("7.8.2"); + }); + + it("should return undefined when package is not in package.json", () => { + expect( + getReactRouterVersion({ dependencies: { react: "^18.0.0" } }), + ).toBeUndefined(); + expect(getReactRouterVersion({})).toBeUndefined(); + }); + }); + + describe("supportsInstrumentationAPI", () => { + it("should return true for React Router v7.15.0 or higher", () => { + expect( + supportsInstrumentationAPI({ + dependencies: { "@react-router/dev": "7.15.0" }, + }), + ).toBe(true); + expect( + supportsInstrumentationAPI({ + dependencies: { "@react-router/dev": "^7.15.0" }, + }), + ).toBe(true); + expect( + supportsInstrumentationAPI({ + dependencies: { "@react-router/dev": "7.16.0" }, + }), + ).toBe(true); + expect( + supportsInstrumentationAPI({ + dependencies: { "@react-router/dev": "8.0.0" }, + }), + ).toBe(true); + expect( + supportsInstrumentationAPI({ + devDependencies: { "@react-router/dev": "7.15.0" }, + }), + ).toBe(true); + }); + + it("should return false for React Router versions below v7.15.0", () => { + expect( + supportsInstrumentationAPI({ + dependencies: { "@react-router/dev": "7.14.0" }, + }), + ).toBe(false); + expect( + supportsInstrumentationAPI({ + dependencies: { "@react-router/dev": "7.0.0" }, + }), + ).toBe(false); + expect( + supportsInstrumentationAPI({ + dependencies: { "@react-router/dev": "7.9.5" }, + }), + ).toBe(false); + }); + + it("should return false when @react-router/dev is not installed", () => { + expect( + supportsInstrumentationAPI({ + dependencies: { react: "^18.0.0" }, + }), + ).toBe(false); + expect(supportsInstrumentationAPI({})).toBe(false); + }); + + it("should handle semver range specifiers correctly", () => { + expect( + supportsInstrumentationAPI({ + dependencies: { "@react-router/dev": "~7.15.0" }, + }), + ).toBe(true); + expect( + supportsInstrumentationAPI({ + dependencies: { "@react-router/dev": ">=7.15.0" }, + }), + ).toBe(true); + }); + }); + + describe("supportsOnError", () => { + it("should return true for React Router v7.11.0 or higher", () => { + expect( + supportsOnError({ + dependencies: { "@react-router/dev": "7.11.0" }, + }), + ).toBe(true); + expect( + supportsOnError({ + dependencies: { "@react-router/dev": "^7.11.0" }, + }), + ).toBe(true); + expect( + supportsOnError({ + dependencies: { "@react-router/dev": "7.12.0" }, + }), + ).toBe(true); + expect( + supportsOnError({ + dependencies: { "@react-router/dev": "8.0.0" }, + }), + ).toBe(true); + expect( + supportsOnError({ + devDependencies: { "@react-router/dev": "7.11.0" }, + }), + ).toBe(true); + }); + + it("should return false for React Router versions below v7.11.0", () => { + expect( + supportsOnError({ + dependencies: { "@react-router/dev": "7.10.0" }, + }), + ).toBe(false); + expect( + supportsOnError({ + dependencies: { "@react-router/dev": "7.0.0" }, + }), + ).toBe(false); + expect( + supportsOnError({ + dependencies: { "@react-router/dev": "7.8.2" }, + }), + ).toBe(false); + }); + + it("should return false when @react-router/dev is not installed", () => { + expect( + supportsOnError({ + dependencies: { react: "^18.0.0" }, + }), + ).toBe(false); + expect(supportsOnError({})).toBe(false); + }); + }); + + describe("generateServerInstrumentation", () => { + it("should generate server instrumentation file with all features enabled", () => { + const dsn = "https://sentry.io/123"; + const enableTracing = true; + const enableProfiling = false; + + const result = getSentryInstrumentationServerContent( + dsn, + enableTracing, + enableProfiling, + false, + ); + + expect(result).toContain('dsn: "https://sentry.io/123"'); + expect(result).toContain("tracesSampleRate: 1"); + }); + + it("should generate server instrumentation file when performance is disabled", () => { + const dsn = "https://sentry.io/123"; + const enableTracing = false; + const enableProfiling = false; + + const result = getSentryInstrumentationServerContent( + dsn, + enableTracing, + enableProfiling, + false, + ); + + expect(result).toContain('dsn: "https://sentry.io/123"'); + expect(result).toContain("tracesSampleRate: 0"); + }); + }); +}); + +describe("runReactRouterReveal", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.resetAllMocks(); + }); + + it("runs the reveal CLI when entry files are missing", () => { + existsSyncMock.mockReturnValue(false); + + (execSync as unknown as Mock).mockImplementation(() => "ok"); + + runReactRouterReveal(); + + expect(execSync).toHaveBeenCalledWith("npx react-router reveal", { + encoding: "utf8", + stdio: "pipe", + }); + }); + + it("does not run the reveal CLI when entry files already exist", () => { + existsSyncMock.mockReturnValue(true); + + (execSync as unknown as Mock).mockReset(); + + runReactRouterReveal(); + + expect(execSync).not.toHaveBeenCalled(); + }); +}); + +describe("server instrumentation helpers", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.resetAllMocks(); + }); + + it("createServerInstrumentationFile writes instrumentation file and returns path", () => { + writeFileSyncMock.mockImplementation(() => undefined); + + const path = createServerInstrumentationFile( + "https://sentry.io/123", + { + performance: true, + replay: false, + profiling: false, + }, + false, + ); + + expect(path).toContain("instrument.server.mjs"); + expect(writeFileSyncMock).toHaveBeenCalled(); + const writtenCall = writeFileSyncMock.mock.calls[0] as unknown as [ + string, + string, + ]; + expect(writtenCall[0]).toEqual( + expect.stringContaining("instrument.server.mjs"), + ); + expect(writtenCall[1]).toEqual( + expect.stringContaining('dsn: "https://sentry.io/123"'), + ); + expect(writtenCall[1]).toEqual( + expect.stringContaining("tracesSampleRate: 1"), + ); + }); +}); + +describe("tryRevealAndGetManualInstructions", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.resetAllMocks(); + }); + + it("should return true when user confirms and reveal command succeeds", async () => { + const missingFilename = "entry.client.tsx"; + const filePath = "/app/entry.client.tsx"; + + // Mock user confirming the reveal operation + clackMocks.confirm.mockResolvedValueOnce(true); + + // Mock execSync succeeding + (execSync as unknown as Mock).mockReturnValueOnce( + "Successfully generated entry files", + ); + + // Mock file existing after reveal + existsSyncMock.mockReturnValueOnce(true); + + const result = await tryRevealAndGetManualInstructions( + missingFilename, + filePath, + ); + + expect(result).toBe(true); + expect(clackMocks.confirm).toHaveBeenCalledWith({ + message: expect.stringContaining( + "Would you like to try running", + ) as string, + initialValue: true, + }); + expect(clackMocks.info).toHaveBeenCalledWith( + expect.stringContaining("Running"), + ); + expect(execSync).toHaveBeenCalledWith("npx react-router reveal", { + encoding: "utf8", + stdio: "pipe", + }); + expect(clackMocks.success).toHaveBeenCalledWith( + expect.stringContaining("Found entry.client.tsx after running reveal"), + ); + }); + + it("stops the wizard without running reveal when the prompt is cancelled", async () => { + clackMocks.confirm.mockResolvedValueOnce( + Symbol("clack:cancel") as unknown as boolean, + ); + + await expect( + tryRevealAndGetManualInstructions( + "entry.client.tsx", + "/app/entry.client.tsx", + ), + ).rejects.toThrow(WizardExitError); + expect(execSync).not.toHaveBeenCalled(); + }); + + it("should return false when user declines reveal operation", async () => { + const missingFilename = "entry.server.tsx"; + const filePath = "/app/entry.server.tsx"; + + // Mock user declining the reveal operation + clackMocks.confirm.mockResolvedValueOnce(false); + + const result = await tryRevealAndGetManualInstructions( + missingFilename, + filePath, + ); + + expect(result).toBe(false); + expect(clackMocks.confirm).toHaveBeenCalled(); + expect(execSync).not.toHaveBeenCalled(); + expect(clackMocks.info).not.toHaveBeenCalled(); + }); + + it("should return false when reveal command succeeds but file still does not exist", async () => { + const missingFilename = "entry.client.jsx"; + const filePath = "/app/entry.client.jsx"; + + // Mock user confirming the reveal operation + clackMocks.confirm.mockResolvedValueOnce(true); + + // Mock execSync succeeding + (execSync as unknown as Mock).mockReturnValueOnce("Command output"); + + // Mock file NOT existing after reveal + existsSyncMock.mockReturnValueOnce(false); + + const result = await tryRevealAndGetManualInstructions( + missingFilename, + filePath, + ); + + expect(result).toBe(false); + expect(execSync).toHaveBeenCalled(); + expect(clackMocks.warn).toHaveBeenCalledWith( + expect.stringContaining( + "entry.client.jsx still not found after running reveal", + ), + ); + }); + + it("should return false when reveal command throws an error", async () => { + const missingFilename = "entry.server.jsx"; + const filePath = "/app/entry.server.jsx"; + + // Mock user confirming the reveal operation + clackMocks.confirm.mockResolvedValueOnce(true); + + // Mock execSync throwing an error + const mockError = new Error("Command failed"); + (execSync as unknown as Mock).mockImplementationOnce(() => { + throw mockError; + }); + + const result = await tryRevealAndGetManualInstructions( + missingFilename, + filePath, + ); + + expect(result).toBe(false); + expect(execSync).toHaveBeenCalled(); + expect(clackMocks.warn).toHaveBeenCalledWith( + expect.stringContaining("Failed to run npx react-router reveal"), + ); + }); + + it("should log command output when reveal succeeds", async () => { + const missingFilename = "entry.client.tsx"; + const filePath = "/app/entry.client.tsx"; + const commandOutput = "Generated entry files successfully"; + + // Mock user confirming the reveal operation + clackMocks.confirm.mockResolvedValueOnce(true); + + // Mock execSync succeeding with output + (execSync as unknown as Mock).mockReturnValueOnce(commandOutput); + + // Mock file existing after reveal + existsSyncMock.mockReturnValueOnce(true); + + await tryRevealAndGetManualInstructions(missingFilename, filePath); + + expect(clackMocks.info).toHaveBeenCalledWith(commandOutput); + }); + + it("should handle reveal command with proper parameters", async () => { + const missingFilename = "entry.client.tsx"; + const filePath = "/app/entry.client.tsx"; + + // Mock user confirming + clackMocks.confirm.mockResolvedValueOnce(true); + + // Mock execSync succeeding + (execSync as unknown as Mock).mockReturnValueOnce("ok"); + + // Mock file existing + existsSyncMock.mockReturnValueOnce(true); + + await tryRevealAndGetManualInstructions(missingFilename, filePath); + + expect(execSync).toHaveBeenCalledWith("npx react-router reveal", { + encoding: "utf8", + stdio: "pipe", + }); + }); +}); + +describe("updatePackageJsonScripts", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.resetAllMocks(); + }); + + it("should set NODE_ENV=production for both dev and start scripts (workaround for React Router v7 + React 19 issue)", async () => { + const mockPackageJson: { scripts: Record } = { + scripts: { + dev: "react-router dev", + start: "react-router serve", + build: "react-router build", + }, + }; + + // Mock getPackageDotJson to return our test package.json + getPackageDotJsonMock.mockResolvedValue(mockPackageJson); + + // Mock fs.promises.writeFile + const fsPromises = await import("node:fs"); + const writeFileMock = vi + .spyOn(fsPromises.promises, "writeFile") + .mockResolvedValue(); + + await updatePackageJsonScripts(); + + // Verify writeFile was called + expect(writeFileMock).toHaveBeenCalled(); + + // Check the written package.json content + const writtenContent = JSON.parse( + writeFileMock.mock.calls[0]?.[1] as string, + ) as { scripts: Record }; + + // Both dev and start scripts should use the correct filenames and commands according to documentation + expect(writtenContent.scripts["dev"]).toBe( + "NODE_OPTIONS='--import ./instrument.server.mjs' react-router dev", + ); + + // Start script should have NODE_ENV=production before --import + expect(writtenContent.scripts["start"]).toBe( + "NODE_ENV=production NODE_OPTIONS='--import ./instrument.server.mjs' react-router-serve ./build/server/index.js", + ); + + // The build script should remain unchanged + expect(writtenContent.scripts["build"]).toBe("react-router build"); + }); + + it("should handle package.json with only start script", async () => { + const mockPackageJson: { scripts: Record } = { + scripts: { + start: "react-router serve", + }, + }; + + // Mock getPackageDotJson to return our test package.json + getPackageDotJsonMock.mockResolvedValue(mockPackageJson); + + // Mock fs.promises.writeFile + const fsPromises = await import("node:fs"); + const writeFileMock = vi + .spyOn(fsPromises.promises, "writeFile") + .mockResolvedValue(); + + await updatePackageJsonScripts(); + + // Verify only start script is modified when dev doesn't exist + const writtenContent = JSON.parse( + writeFileMock.mock.calls[0]?.[1] as string, + ) as { scripts: Record }; + expect(writtenContent.scripts["start"]).toBe( + "NODE_ENV=production NODE_OPTIONS='--import ./instrument.server.mjs' react-router-serve ./build/server/index.js", + ); + expect(writtenContent.scripts["dev"]).toBeUndefined(); + }); + + it("should throw error when no start script exists", async () => { + const mockPackageJson = { + scripts: { + build: "react-router build", + }, + }; + + // Mock getPackageDotJson to return package.json without start script + getPackageDotJsonMock.mockResolvedValue(mockPackageJson); + + await expect(updatePackageJsonScripts()).rejects.toThrow( + 'Could not find a `start` script in your package.json. Please add: "start": "react-router-serve ./build/server/index.js" and re-run the wizard.', + ); + }); + + it("should handle unquoted NODE_OPTIONS in dev script", async () => { + const mockPackageJson: { scripts: Record } = { + scripts: { + dev: "NODE_OPTIONS=--loader ts-node/register react-router dev", + start: "react-router serve", + }, + }; + + getPackageDotJsonMock.mockResolvedValue(mockPackageJson); + + const fsPromises = await import("node:fs"); + const writeFileMock = vi + .spyOn(fsPromises.promises, "writeFile") + .mockResolvedValue(); + + await updatePackageJsonScripts(); + + const writtenContent = JSON.parse( + writeFileMock.mock.calls[0]?.[1] as string, + ) as { scripts: Record }; + + // Should merge unquoted NODE_OPTIONS and wrap result in single quotes + expect(writtenContent.scripts["dev"]).toBe( + "NODE_OPTIONS='--loader ts-node/register --import ./instrument.server.mjs' react-router dev", + ); + }); + + it("should handle unquoted NODE_OPTIONS in start script", async () => { + const mockPackageJson: { scripts: Record } = { + scripts: { + start: + "NODE_OPTIONS=--require ./dotenv-config.js react-router-serve ./build/server/index.js", + }, + }; + + getPackageDotJsonMock.mockResolvedValue(mockPackageJson); + + const fsPromises = await import("node:fs"); + const writeFileMock = vi + .spyOn(fsPromises.promises, "writeFile") + .mockResolvedValue(); + + await updatePackageJsonScripts(); + + const writtenContent = JSON.parse( + writeFileMock.mock.calls[0]?.[1] as string, + ) as { scripts: Record }; + + // Should merge unquoted NODE_OPTIONS and prepend NODE_ENV + expect(writtenContent.scripts["start"]).toBe( + "NODE_ENV=production NODE_OPTIONS='--require ./dotenv-config.js --import ./instrument.server.mjs' react-router-serve ./build/server/index.js", + ); + }); + + it("should handle quoted NODE_OPTIONS and standardize to single quotes", async () => { + const mockPackageJson: { scripts: Record } = { + scripts: { + dev: 'NODE_OPTIONS="--max-old-space-size=4096" react-router dev', + start: "NODE_OPTIONS='--enable-source-maps' react-router serve", + }, + }; + + getPackageDotJsonMock.mockResolvedValue(mockPackageJson); + + const fsPromises = await import("node:fs"); + const writeFileMock = vi + .spyOn(fsPromises.promises, "writeFile") + .mockResolvedValue(); + + await updatePackageJsonScripts(); + + const writtenContent = JSON.parse( + writeFileMock.mock.calls[0]?.[1] as string, + ) as { scripts: Record }; + + // Should standardize to single quotes + expect(writtenContent.scripts["dev"]).toBe( + "NODE_OPTIONS='--max-old-space-size=4096 --import ./instrument.server.mjs' react-router dev", + ); + // Should prepend NODE_ENV=production to start script + expect(writtenContent.scripts["start"]).toBe( + "NODE_ENV=production NODE_OPTIONS='--enable-source-maps --import ./instrument.server.mjs' react-router serve", + ); + }); +}); + +describe("getEntryFilename", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("finds a .jsx entry in a TypeScript project", () => { + existsSyncMock.mockImplementation((p: string) => + p.endsWith("entry.client.jsx"), + ); + expect(getEntryFilename("entry.client", true)).toBe("entry.client.jsx"); + }); + + it("finds a .tsx entry in a JavaScript project", () => { + existsSyncMock.mockImplementation((p: string) => + p.endsWith("entry.server.tsx"), + ); + expect(getEntryFilename("entry.server", false)).toBe("entry.server.tsx"); + }); + + it("uses the project language when both or neither exist", () => { + existsSyncMock.mockReturnValue(true); + expect(getEntryFilename("entry.client", true)).toBe("entry.client.tsx"); + existsSyncMock.mockReturnValue(false); + expect(getEntryFilename("entry.client", false)).toBe("entry.client.jsx"); + }); +}); diff --git a/packages/cli/test/lib/wizard/react-router/sdk-version.test.ts b/packages/cli/test/lib/wizard/react-router/sdk-version.test.ts new file mode 100644 index 000000000..6d0b6fab7 --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/sdk-version.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from "vitest"; +import { + getSentryReactRouterVitePluginImportPath, + SENTRY_REACT_ROUTER_SDK_RANGE, + getProfilingNodeRange, +} from "../../../../src/lib/wizard/react-router/sdk-version.js"; + +describe("getSentryReactRouterVitePluginImportPath", () => { + it.each(["11.0.0", "^11.0.0", "11.0.0-beta.2", "~11.2.0", "12.0.0"])( + "returns the /vite subpath for SDK %s", + (version) => { + expect(getSentryReactRouterVitePluginImportPath(version)).toBe( + "@sentry/react-router/vite", + ); + }, + ); + + it.each(["10.74.0", "^10.0.0", "~10.73.0", "9.47.1"])( + "returns the root export for SDK %s", + (version) => { + expect(getSentryReactRouterVitePluginImportPath(version)).toBe( + "@sentry/react-router", + ); + }, + ); + + it.each([undefined, "", "latest", "workspace:*"])( + "falls back to the pinned install range when the version is unknown (%s)", + (version) => { + expect(getSentryReactRouterVitePluginImportPath(version)).toBe( + getSentryReactRouterVitePluginImportPath(SENTRY_REACT_ROUTER_SDK_RANGE), + ); + }, + ); +}); + +describe("getProfilingNodeRange", () => { + it.each([ + ["^10.20.0", "^10"], + ["10.5.1", "^10"], + ["^11.0.0", "^11"], + [undefined, "^11"], + ["workspace:*", "^11"], + ])("matches the installed SDK %s with %s", (installed, expected) => { + expect(getProfilingNodeRange(installed)).toBe(expected); + }); +}); diff --git a/packages/cli/test/lib/wizard/react-router/templates.test.ts b/packages/cli/test/lib/wizard/react-router/templates.test.ts new file mode 100644 index 000000000..36a525ef9 --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/templates.test.ts @@ -0,0 +1,489 @@ +import { describe, expect, it, vi, beforeEach } from "vitest"; + +// Mock makeCodeSnippet utility +vi.mock("../../../../src/lib/wizard/utils/clack/index.js", () => { + return { + __esModule: true, + makeCodeSnippet: vi.fn( + ( + _colors: boolean, + callback: ( + unchanged: (str: string) => string, + plus: (str: string) => string, + minus: (str: string) => string, + ) => string, + ) => { + // Mock implementation that just calls the callback with simple string functions + const unchanged = (str: string) => str; + const plus = (str: string) => `+ ${str}`; + const minus = (str: string) => `- ${str}`; + return callback(unchanged, plus, minus); + }, + ), + }; +}); + +import { + EXAMPLE_PAGE_TEMPLATE_TSX, + EXAMPLE_PAGE_TEMPLATE_JSX, + getManualClientEntryContent, + getManualServerEntryContent, + getManualServerInstrumentContent, + getManualReactRouterConfigContent, + getManualViteConfigContent, + getManualPackageJsonScriptsContent, +} from "../../../../src/lib/wizard/react-router/templates.js"; + +describe("React Router Templates", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + describe("Template Constants", () => { + it("should have correct EXAMPLE_PAGE_TEMPLATE_TSX content", () => { + expect(EXAMPLE_PAGE_TEMPLATE_TSX).toContain("import type { Route }"); + expect(EXAMPLE_PAGE_TEMPLATE_TSX).toContain( + "export async function loader()", + ); + expect(EXAMPLE_PAGE_TEMPLATE_TSX).toContain( + 'throw new Error("some error thrown in a loader")', + ); + expect(EXAMPLE_PAGE_TEMPLATE_TSX).toContain( + "export default function SentryExamplePage()", + ); + expect(EXAMPLE_PAGE_TEMPLATE_TSX).toContain( + "Loading this page will throw an error", + ); + }); + + it("should have correct EXAMPLE_PAGE_TEMPLATE_JSX content", () => { + expect(EXAMPLE_PAGE_TEMPLATE_JSX).not.toContain("import type { Route }"); + expect(EXAMPLE_PAGE_TEMPLATE_JSX).toContain( + "export async function loader()", + ); + expect(EXAMPLE_PAGE_TEMPLATE_JSX).toContain( + 'throw new Error("some error thrown in a loader")', + ); + expect(EXAMPLE_PAGE_TEMPLATE_JSX).toContain( + "export default function SentryExamplePage()", + ); + expect(EXAMPLE_PAGE_TEMPLATE_JSX).toContain( + "Loading this page will throw an error", + ); + }); + }); + + describe("getManualClientEntryContent", () => { + it("should generate manual client entry with all features enabled and onError", () => { + const dsn = "https://test.sentry.io/123"; + + const result = getManualClientEntryContent( + dsn, + true, + true, + false, + false, + true, + ); + + expect(result).toContain( + "+ import * as Sentry from '@sentry/react-router'", + ); + expect(result).toContain(`dsn: "${dsn}"`); + expect(result).toContain("// httpBodies: [],"); + expect(result).toContain("Sentry.reactRouterTracingIntegration()"); + expect(result).toContain("Sentry.replayIntegration()"); + expect(result).toContain("tracesSampleRate: 1.0"); + expect(result).toContain("replaysSessionSampleRate: 0.1"); + expect(result).toContain("replaysOnErrorSampleRate: 1.0"); + expect(result).toContain("tracePropagationTargets"); + expect(result).toContain("onError={Sentry.sentryOnError}"); + }); + + it("should not include onError when useOnError is false", () => { + const dsn = "https://test.sentry.io/123"; + + const result = getManualClientEntryContent(dsn, true, true, false); + + expect(result).not.toContain("onError={Sentry.sentryOnError}"); + }); + + it("should generate manual client entry with tracing disabled", () => { + const dsn = "https://test.sentry.io/123"; + const enableTracing = false; + const enableReplay = true; + + const result = getManualClientEntryContent( + dsn, + enableTracing, + enableReplay, + false, + ); + + expect(result).toContain(`dsn: "${dsn}"`); + expect(result).toContain("tracesSampleRate: 0"); + expect(result).not.toContain("Sentry.reactRouterTracingIntegration()"); + expect(result).toContain("Sentry.replayIntegration()"); + expect(result).not.toContain("tracePropagationTargets"); + }); + + it("should generate manual client entry with replay disabled", () => { + const dsn = "https://test.sentry.io/123"; + const enableTracing = true; + const enableReplay = false; + + const result = getManualClientEntryContent( + dsn, + enableTracing, + enableReplay, + false, + ); + + expect(result).toContain(`dsn: "${dsn}"`); + expect(result).toContain("tracesSampleRate: 1.0"); + expect(result).toContain("Sentry.reactRouterTracingIntegration()"); + expect(result).not.toContain("Sentry.replayIntegration()"); + expect(result).not.toContain("replaysSessionSampleRate"); + expect(result).not.toContain("replaysOnErrorSampleRate"); + }); + + it("should generate manual client entry with no integrations", () => { + const dsn = "https://test.sentry.io/123"; + const enableTracing = false; + const enableReplay = false; + + const result = getManualClientEntryContent( + dsn, + enableTracing, + enableReplay, + false, + ); + + expect(result).toContain(`dsn: "${dsn}"`); + expect(result).toContain("tracesSampleRate: 0"); + expect(result).not.toContain("Sentry.reactRouterTracingIntegration()"); + expect(result).not.toContain("Sentry.replayIntegration()"); + expect(result).toContain("integrations: ["); + }); + + it("should write the dataCollection preset when reduceDataCollection is true", () => { + const dsn = "https://test.sentry.io/123"; + + const result = getManualClientEntryContent(dsn, true, true, true); + + expect(result).toContain("userInfo: false,"); + expect(result).toContain( + 'httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }', + ); + expect(result).not.toContain("// userInfo: false,"); + expect(result).not.toContain( + "uncomment the lines below. For more info visit:", + ); + }); + + it("should write the dataCollection preset with the instrumentation API", () => { + const dsn = "https://test.sentry.io/123"; + + const result = getManualClientEntryContent(dsn, true, true, true, true); + + expect(result).toContain("userInfo: false,"); + expect(result).toContain( + 'httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }', + ); + expect(result).not.toContain("// userInfo: false,"); + }); + + describe("Instrumentation API", () => { + it("should generate client entry with instrumentation API enabled", () => { + const dsn = "https://test.sentry.io/123"; + + const result = getManualClientEntryContent( + dsn, + true, + false, + false, + true, + true, + ); + + expect(result).toContain( + "const tracing = Sentry.reactRouterTracingIntegration();", + ); + expect(result).toContain("integrations: ["); + expect(result).toContain("tracing"); + expect(result).toContain( + "instrumentations={[tracing.clientInstrumentation]}", + ); + expect(result).toContain("onError={Sentry.sentryOnError}"); + }); + + it("should generate client entry with instrumentation API and replay enabled", () => { + const dsn = "https://test.sentry.io/123"; + + const result = getManualClientEntryContent( + dsn, + true, + true, + false, + true, + true, + ); + + expect(result).toContain( + "const tracing = Sentry.reactRouterTracingIntegration();", + ); + expect(result).toContain("tracing"); + expect(result).toContain("Sentry.replayIntegration()"); + expect(result).toContain( + "instrumentations={[tracing.clientInstrumentation]}", + ); + expect(result).toContain("onError={Sentry.sentryOnError}"); + }); + + it("should not use instrumentation API when explicitly disabled", () => { + const dsn = "https://test.sentry.io/123"; + + const result = getManualClientEntryContent( + dsn, + true, + false, + false, + false, + true, + ); + + expect(result).not.toContain("const tracing"); + expect(result).toContain("Sentry.reactRouterTracingIntegration()"); + expect(result).not.toContain("instrumentations"); + expect(result).toContain("onError={Sentry.sentryOnError}"); + }); + }); + }); + + describe("getManualServerEntryContent", () => { + it("should generate manual server entry content", () => { + const result = getManualServerEntryContent(); + + expect(result).toContain( + "+ import * as Sentry from '@sentry/react-router'", + ); + expect(result).toContain("createReadableStreamFromReadable"); + expect(result).toContain("renderToPipeableStream"); + expect(result).toContain("ServerRouter"); + expect(result).toContain( + "+ const handleRequest = Sentry.createSentryHandleRequest({", + ); + expect(result).toContain( + "+ export const handleError = Sentry.createSentryHandleError({", + ); + expect(result).toContain("logErrors: false"); + expect(result).toContain("export default handleRequest"); + expect(result).toContain("rest of your server entry"); + }); + + describe("Instrumentation API", () => { + it("should generate server entry with instrumentations when useInstrumentationAPI is true", () => { + const result = getManualServerEntryContent(true); + + expect(result).toContain( + "+ import * as Sentry from '@sentry/react-router'", + ); + expect(result).toContain( + "export const instrumentations = [Sentry.createSentryServerInstrumentation()];", + ); + expect(result).toContain( + "Enable automatic server-side instrumentation for loaders, actions, middleware", + ); + }); + + it("should not include instrumentations when useInstrumentationAPI is false", () => { + const result = getManualServerEntryContent(false); + + expect(result).not.toContain("instrumentations"); + expect(result).not.toContain("createSentryServerInstrumentation"); + }); + }); + }); + + describe("getManualServerInstrumentContent", () => { + it("should generate server instrumentation with all features enabled", () => { + const dsn = "https://test.sentry.io/123"; + const enableTracing = true; + const enableProfiling = true; + + const result = getManualServerInstrumentContent( + dsn, + enableTracing, + enableProfiling, + false, + ); + + expect(result).toContain( + "+ import * as Sentry from '@sentry/react-router'", + ); + expect(result).toContain( + "import { nodeProfilingIntegration } from '@sentry/profiling-node'", + ); + expect(result).toContain(`dsn: "${dsn}"`); + expect(result).toContain("// httpBodies: [],"); + expect(result).toContain("integrations: [nodeProfilingIntegration()]"); + expect(result).toContain("tracesSampleRate: 1.0"); + expect(result).toContain("profileSessionSampleRate: 1.0"); + expect(result).toContain('profileLifecycle: "trace"'); + expect(result).not.toContain("profilesSampleRate"); + expect(result).toContain("Capture 100% of the traces"); + }); + + it("should generate server instrumentation with tracing disabled", () => { + const dsn = "https://test.sentry.io/123"; + const enableTracing = false; + const enableProfiling = false; + + const result = getManualServerInstrumentContent( + dsn, + enableTracing, + enableProfiling, + false, + ); + + expect(result).toContain(`dsn: "${dsn}"`); + expect(result).toContain("tracesSampleRate: 0"); + expect(result).not.toContain("nodeProfilingIntegration"); + expect(result).not.toContain("profileSessionSampleRate"); + expect(result).not.toContain("profileLifecycle"); + expect(result).not.toContain( + "integrations: [nodeProfilingIntegration()]", + ); + }); + + it("should generate server instrumentation with profiling disabled but tracing enabled", () => { + const dsn = "https://test.sentry.io/123"; + const enableTracing = true; + const enableProfiling = false; + + const result = getManualServerInstrumentContent( + dsn, + enableTracing, + enableProfiling, + false, + ); + + expect(result).toContain(`dsn: "${dsn}"`); + expect(result).toContain("tracesSampleRate: 1.0"); + expect(result).not.toContain("nodeProfilingIntegration"); + expect(result).not.toContain("profileSessionSampleRate"); + expect(result).not.toContain("profileLifecycle"); + expect(result).not.toContain("integrations:"); + }); + + it("should write the dataCollection preset when reduceDataCollection is true", () => { + const dsn = "https://test.sentry.io/123"; + + const result = getManualServerInstrumentContent(dsn, true, false, true); + + expect(result).toContain("userInfo: false,"); + expect(result).toContain( + 'httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }', + ); + expect(result).not.toContain("// userInfo: false,"); + expect(result).not.toContain( + "uncomment the lines below. For more info visit:", + ); + }); + + it("should handle special characters in DSN", () => { + const dsn = "https://test@example.com/sentry/123?param=value"; + const enableTracing = true; + const enableProfiling = false; + + const result = getManualServerInstrumentContent( + dsn, + enableTracing, + enableProfiling, + false, + ); + + expect(result).toContain(`dsn: "${dsn}"`); + }); + }); + + describe("getManualReactRouterConfigContent", () => { + it("should generate TypeScript config snippet with type imports and satisfies", () => { + const result = getManualReactRouterConfigContent(true); + + expect(result).toContain("import type { Config }"); + expect(result).toContain("} satisfies Config;"); + expect(result).toContain("sentryOnBuildEnd"); + expect(result).toContain("ssr: true"); + }); + + it("should generate JavaScript config snippet without TS-only syntax", () => { + const result = getManualReactRouterConfigContent(false); + + // JS version should NOT have TypeScript-only syntax + expect(result).not.toContain("import type"); + expect(result).not.toContain("satisfies Config"); + + // JS version should have the standard import and export + expect(result).toContain("import { sentryOnBuildEnd }"); + expect(result).toContain("sentryOnBuildEnd"); + expect(result).toContain("ssr: true"); + expect(result).toContain("export default {"); + }); + + it("should default to TypeScript when no parameter is passed", () => { + const result = getManualReactRouterConfigContent(); + + expect(result).toContain("import type { Config }"); + expect(result).toContain("} satisfies Config;"); + }); + + it("imports sentryOnBuildEnd from the given path", () => { + const ts = getManualReactRouterConfigContent( + true, + "@sentry/react-router/vite", + ); + const js = getManualReactRouterConfigContent( + false, + "@sentry/react-router/vite", + ); + + expect(ts).toContain( + "import { sentryOnBuildEnd } from '@sentry/react-router/vite';", + ); + expect(js).toContain( + "import { sentryOnBuildEnd } from '@sentry/react-router/vite';", + ); + }); + }); + + describe("getManualViteConfigContent", () => { + it("imports sentryReactRouter from the given path and keeps the package in optimizeDeps.exclude", () => { + const result = getManualViteConfigContent( + "my-org", + "my-project", + "@sentry/react-router/vite", + ); + + expect(result).toContain( + "import { sentryReactRouter } from '@sentry/react-router/vite';", + ); + expect(result).toContain("exclude: ['@sentry/react-router']"); + }); + }); + + describe("getManualPackageJsonScriptsContent", () => { + it("replaces the serve start script and the dev script", () => { + const result = getManualPackageJsonScriptsContent(); + + expect(result).toContain( + '- "start": "react-router-serve ./build/server/index.js"', + ); + expect(result).not.toContain('"start": "react-router dev"'); + expect(result).toContain('- "dev": "react-router dev"'); + expect(result).toContain( + '+ "dev": "NODE_OPTIONS=\'--import ./instrument.server.mjs\' react-router dev"', + ); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/remix/build-script.test.ts b/packages/cli/test/lib/wizard/remix/build-script.test.ts new file mode 100644 index 000000000..efd2e0e91 --- /dev/null +++ b/packages/cli/test/lib/wizard/remix/build-script.test.ts @@ -0,0 +1,163 @@ +import { promises } from "node:fs"; + +import { updateBuildScript } from "../../../../src/lib/wizard/remix/sdk-setup.js"; +import { getPackageDotJson } from "../../../../src/lib/wizard/utils/clack/index.js"; + +import { vi, it, describe, expect, afterEach } from "vitest"; + +const writeFileSpy = vi + .spyOn(promises, "writeFile") + .mockImplementation(() => Promise.resolve()); + +vi.mock("@clack/prompts", () => { + const mock = { + log: { + info: vi.fn(), + success: vi.fn(), + warn: vi.fn(), + }, + confirm: vi.fn().mockResolvedValue(true), + isCancel: vi.fn().mockReturnValue(false), + }; + return { ...mock, default: mock }; +}); + +vi.mock("../../../../src/lib/wizard/utils/clack/index.js", async () => ({ + ...(await vi.importActual("../../../../src/lib/wizard/utils/clack/index.js")), + // A fresh object per call: updateBuildScript mutates the one it gets. + getPackageDotJson: vi.fn(() => + Promise.resolve({ + scripts: { + build: "remix build", + }, + version: "1.0.0", + }), + ), +})); + +describe("updateBuildScript", () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + it("uses npx @sentry/remix --upload-sourcemaps for the upload command", async () => { + await updateBuildScript({ + org: "my-org", + project: "my-project", + isHydrogen: false, + }); + + expect(writeFileSpy).toHaveBeenCalledWith( + expect.stringContaining("package.json"), + expect.stringContaining( + "npx @sentry/remix --upload-sourcemaps --org my-org --project my-project", + ), + ); + }); + + it("replaces the remix build command with sourcemap flag and upload", async () => { + await updateBuildScript({ + org: "my-org", + project: "my-project", + isHydrogen: false, + }); + + expect(writeFileSpy).toHaveBeenCalledWith( + expect.stringContaining("package.json"), + expect.stringContaining( + "remix build --sourcemap && npx @sentry/remix --upload-sourcemaps", + ), + ); + }); + + it("includes --url flag when a custom url is provided", async () => { + await updateBuildScript({ + org: "my-org", + project: "my-project", + url: "https://self-hosted.example.com", + isHydrogen: false, + }); + + expect(writeFileSpy).toHaveBeenCalledWith( + expect.stringContaining("package.json"), + expect.stringContaining("--url https://self-hosted.example.com"), + ); + }); + + it("uses shopify hydrogen build for hydrogen apps", async () => { + vi.mocked(getPackageDotJson).mockResolvedValue({ + scripts: { + build: "shopify hydrogen build", + }, + version: "1.0.0", + }); + + await updateBuildScript({ + org: "my-org", + project: "my-project", + isHydrogen: true, + }); + + expect(writeFileSpy).toHaveBeenCalledWith( + expect.stringContaining("package.json"), + expect.stringContaining( + "shopify hydrogen build --sourcemap && npx @sentry/remix --upload-sourcemaps --org my-org --project my-project --buildPath ./dist", + ), + ); + }); + + it("sets build script when none exists", async () => { + vi.mocked(getPackageDotJson).mockResolvedValue({ + scripts: {}, + version: "1.0.0", + }); + + await updateBuildScript({ + org: "my-org", + project: "my-project", + isHydrogen: false, + }); + + expect(writeFileSpy).toHaveBeenCalledWith( + expect.stringContaining("package.json"), + expect.stringContaining( + "remix build --sourcemap && npx @sentry/remix --upload-sourcemaps", + ), + ); + }); + + it("throws when build script has an unknown command", async () => { + vi.mocked(getPackageDotJson).mockResolvedValue({ + scripts: { + build: "some-custom-build-tool", + }, + version: "1.0.0", + }); + + await expect( + updateBuildScript({ + org: "my-org", + project: "my-project", + isHydrogen: false, + }), + ).rejects.toThrow("build` script doesn't contain a known build command"); + }); + + it("leaves an already instrumented build script alone on a re-run", async () => { + vi.mocked(getPackageDotJson).mockResolvedValueOnce({ + scripts: { + build: + "remix build --sourcemap && npx @sentry/remix --upload-sourcemaps --org my-org --project my-project", + }, + version: "1.0.0", + }); + + await updateBuildScript({ + org: "my-org", + project: "my-project", + isHydrogen: false, + }); + + expect(writeFileSpy).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/cli/test/lib/wizard/remix/client-entry.test.ts b/packages/cli/test/lib/wizard/remix/client-entry.test.ts new file mode 100644 index 000000000..21d637306 --- /dev/null +++ b/packages/cli/test/lib/wizard/remix/client-entry.test.ts @@ -0,0 +1,184 @@ +import { parseModule } from "magicast"; +import { updateEntryClientMod } from "../../../../src/lib/wizard/remix/sdk-setup.js"; +import { describe, expect, it } from "vitest"; + +describe("initializeSentryOnEntryClient", () => { + it("should initialize Sentry on client entry with all features enabled", () => { + // Empty entry.client.tsx file for testing + const originalEntryClientMod = parseModule(""); + + const dsn = "https://sentry.io/123"; + const selectedFeatures = { + performance: true, + replay: true, + }; + + const result = updateEntryClientMod( + originalEntryClientMod, + dsn, + selectedFeatures, + false, + ); + + expect(result.generate().code).toMatchInlineSnapshot(` + "import { useEffect,} from "react"; + + import { + useLocation, + useMatches, + } from "@remix-run/react"; + + import { init, replayIntegration, browserTracingIntegration,} from "@sentry/remix"; + + init({ + dsn: "https://sentry.io/123", + tracesSampleRate: 1, + + integrations: [browserTracingIntegration({ + useEffect, + useLocation, + useMatches + }), replayIntegration({ + maskAllText: true, + blockAllMedia: true + })], + + replaysSessionSampleRate: 0.1, + replaysOnErrorSampleRate: 1 + })" + `); + }); + + it("should initialize Sentry on client entry when performance disabled", () => { + // Empty entry.client.tsx file for testing + const originalEntryClientMod = parseModule(""); + + const dsn = "https://sentry.io/123"; + const selectedFeatures = { + performance: false, + replay: true, + }; + + const result = updateEntryClientMod( + originalEntryClientMod, + dsn, + selectedFeatures, + false, + ); + + expect(result.generate().code).toMatchInlineSnapshot(` + "import { init, replayIntegration,} from "@sentry/remix"; + + init({ + dsn: "https://sentry.io/123", + + integrations: [replayIntegration({ + maskAllText: true, + blockAllMedia: true + })], + + replaysSessionSampleRate: 0.1, + replaysOnErrorSampleRate: 1 + })" + `); + }); + + it("should initialize Sentry on client entry when replay disabled", () => { + // Empty entry.client.tsx file for testing + const originalEntryClientMod = parseModule(""); + + const dsn = "https://sentry.io/123"; + const selectedFeatures = { + performance: true, + replay: false, + }; + + const result = updateEntryClientMod( + originalEntryClientMod, + dsn, + selectedFeatures, + false, + ); + + expect(result.generate().code).toMatchInlineSnapshot(` + "import { useEffect,} from "react"; + + import { + useLocation, + useMatches, + } from "@remix-run/react"; + + import { init, browserTracingIntegration,} from "@sentry/remix"; + + init({ + dsn: "https://sentry.io/123", + tracesSampleRate: 1, + + integrations: [browserTracingIntegration({ + useEffect, + useLocation, + useMatches + })] + })" + `); + }); + + it("should add the dataCollection preset when reduced data collection is requested", () => { + // Empty entry.client.tsx file for testing + const originalEntryClientMod = parseModule(""); + + const dsn = "https://sentry.io/123"; + const selectedFeatures = { + performance: true, + replay: true, + }; + + const result = updateEntryClientMod( + originalEntryClientMod, + dsn, + selectedFeatures, + true, + ); + + expect(result.generate().code).toMatchInlineSnapshot(` + "import { useEffect,} from "react"; + + import { + useLocation, + useMatches, + } from "@remix-run/react"; + + import { init, replayIntegration, browserTracingIntegration,} from "@sentry/remix"; + + init({ + dsn: "https://sentry.io/123", + tracesSampleRate: 1, + + integrations: [browserTracingIntegration({ + useEffect, + useLocation, + useMatches + }), replayIntegration({ + maskAllText: true, + blockAllMedia: true + })], + + replaysSessionSampleRate: 0.1, + replaysOnErrorSampleRate: 1, + // Turns off collection of data that could identify users. Adjust per category: + // https://docs.sentry.io/platforms/javascript/configuration/options/#dataCollection + dataCollection: { + userInfo: false, + graphQL: { document: false, variables: false }, + genAI: { inputs: false, outputs: false }, + databaseQueryData: false, + queues: false, + httpBodies: [], + httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + cookies: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + urlQueryParams: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + }, + })" + `); + }); +}); diff --git a/packages/cli/test/lib/wizard/remix/fixtures/root-already-wrapped.tsx b/packages/cli/test/lib/wizard/remix/fixtures/root-already-wrapped.tsx new file mode 100644 index 000000000..7257d8ae7 --- /dev/null +++ b/packages/cli/test/lib/wizard/remix/fixtures/root-already-wrapped.tsx @@ -0,0 +1,8 @@ +import { Outlet } from '@remix-run/react'; +import { withSentry } from '@sentry/remix'; + +function App() { + return ; +} + +export default withSentry(App); diff --git a/packages/cli/test/lib/wizard/remix/fixtures/root-no-error-boundary.tsx b/packages/cli/test/lib/wizard/remix/fixtures/root-no-error-boundary.tsx new file mode 100644 index 000000000..1f66dd469 --- /dev/null +++ b/packages/cli/test/lib/wizard/remix/fixtures/root-no-error-boundary.tsx @@ -0,0 +1,5 @@ +import { Outlet } from '@remix-run/react'; + +export default function App() { + return ; +} diff --git a/packages/cli/test/lib/wizard/remix/fixtures/root-variable-error-boundary.tsx b/packages/cli/test/lib/wizard/remix/fixtures/root-variable-error-boundary.tsx new file mode 100644 index 000000000..b2e3d0940 --- /dev/null +++ b/packages/cli/test/lib/wizard/remix/fixtures/root-variable-error-boundary.tsx @@ -0,0 +1,11 @@ +import { Outlet } from '@remix-run/react'; + +const ErrorBoundary = () => { + return
Error occurred
; +}; + +export { ErrorBoundary }; + +export default function App() { + return ; +} diff --git a/packages/cli/test/lib/wizard/remix/fixtures/root-with-error-boundary.tsx b/packages/cli/test/lib/wizard/remix/fixtures/root-with-error-boundary.tsx new file mode 100644 index 000000000..18b3edbf4 --- /dev/null +++ b/packages/cli/test/lib/wizard/remix/fixtures/root-with-error-boundary.tsx @@ -0,0 +1,9 @@ +import { Outlet } from '@remix-run/react'; + +export function ErrorBoundary() { + return
Error occurred
; +} + +export default function App() { + return ; +} diff --git a/packages/cli/test/lib/wizard/remix/fixtures/root-with-sentry-error-boundary.tsx b/packages/cli/test/lib/wizard/remix/fixtures/root-with-sentry-error-boundary.tsx new file mode 100644 index 000000000..9957fb6b5 --- /dev/null +++ b/packages/cli/test/lib/wizard/remix/fixtures/root-with-sentry-error-boundary.tsx @@ -0,0 +1,11 @@ +import { Outlet } from '@remix-run/react'; +import { captureRemixErrorBoundaryError } from '@sentry/remix'; + +export function ErrorBoundary() { + captureRemixErrorBoundaryError(); + return
Error occurred
; +} + +export default function App() { + return ; +} diff --git a/packages/cli/test/lib/wizard/remix/remix-wizard.test.ts b/packages/cli/test/lib/wizard/remix/remix-wizard.test.ts new file mode 100644 index 000000000..7c9f9619a --- /dev/null +++ b/packages/cli/test/lib/wizard/remix/remix-wizard.test.ts @@ -0,0 +1,77 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const { askShouldReduceDataCollectionMock, getPackageDotJsonMock } = vi.hoisted( + () => ({ + askShouldReduceDataCollectionMock: vi.fn(), + getPackageDotJsonMock: vi.fn(), + }), +); + +vi.mock("../../../../src/lib/wizard/telemetry.js", () => ({ + Sentry: { setTag: vi.fn() }, + withTelemetry: (_options: unknown, callback: () => unknown) => callback(), + traceStep: (_name: string, callback: () => unknown) => callback(), +})); + +vi.mock("../../../../src/lib/wizard/utils/clack/index.js", () => ({ + printWelcome: vi.fn(), + getPackageDotJson: getPackageDotJsonMock, + confirmContinueIfNoOrDirtyGitRepo: vi.fn(() => Promise.resolve()), + ensurePackageIsInstalled: vi.fn(() => Promise.resolve()), + getOrAskForProjectData: vi.fn(() => + Promise.resolve({ + spotlight: false, + selfHosted: false, + sentryUrl: "https://sentry.io/", + authToken: "token", + selectedProject: { + id: "1", + slug: "project", + organization: { id: "1", slug: "org", name: "Org" }, + keys: [{ dsn: { public: "https://key@sentry.io/1" } }], + }, + }), + ), + printSdkV11MigrationGuideIfOutdated: vi.fn(), + installPackage: vi.fn(() => Promise.resolve()), +})); + +vi.mock("../../../../src/lib/wizard/utils/data-collection.js", async () => ({ + ...(await vi.importActual< + typeof import("../../../../src/lib/wizard/utils/data-collection.js") + >("../../../../src/lib/wizard/utils/data-collection.js")), + askShouldReduceDataCollection: askShouldReduceDataCollectionMock, +})); + +vi.mock("../../../../src/lib/wizard/utils/node-version.js", () => ({ + warnIfNodeVersionUnsupportedBySdkV11: vi.fn(), +})); + +import { runRemixWizard } from "../../../../src/lib/wizard/remix/remix-wizard.js"; + +describe("runRemixWizard", () => { + beforeEach(() => { + vi.clearAllMocks(); + // Stop the wizard at the data collection prompt; only reaching it matters. + askShouldReduceDataCollectionMock.mockRejectedValue( + new Error("stop at data collection"), + ); + }); + + it.each([undefined, "workspace:*"])( + "offers to reduce data collection when the installed SDK version is %s", + async (installedVersion) => { + getPackageDotJsonMock.mockResolvedValue({ + dependencies: { + "@remix-run/react": "^2.0.0", + ...(installedVersion && { "@sentry/remix": installedVersion }), + }, + }); + + await expect(runRemixWizard({ telemetryEnabled: false })).rejects.toThrow( + "stop at data collection", + ); + expect(askShouldReduceDataCollectionMock).toHaveBeenCalledTimes(1); + }, + ); +}); diff --git a/packages/cli/test/lib/wizard/remix/root.test.ts b/packages/cli/test/lib/wizard/remix/root.test.ts new file mode 100644 index 000000000..4f37e7bb4 --- /dev/null +++ b/packages/cli/test/lib/wizard/remix/root.test.ts @@ -0,0 +1,311 @@ +import { parseModule } from "magicast"; +import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; +import { + copyFileSync, + existsSync, + mkdirSync, + readFileSync, + readdirSync, + rmdirSync, + statSync, + unlinkSync, +} from "node:fs"; +import path from "node:path"; +import { + wrapAppWithSentry, + isWithSentryAlreadyUsed, + instrumentRoot, +} from "../../../../src/lib/wizard/remix/codemods/root.js"; + +vi.mock("@clack/prompts", () => { + const mock = { + log: { + warn: vi.fn(), + info: vi.fn(), + success: vi.fn(), + }, + }; + return { + default: mock, + ...mock, + }; +}); + +vi.mock("../../../../src/lib/wizard/utils/clack/mcp-config.js", () => ({ + offerProjectScopedMcpConfig: vi.fn().mockResolvedValue(undefined), +})); + +describe("wrapAppWithSentry", () => { + it("should wrap the app with Sentry", () => { + // Empty root.tsx file for testing + const originalRootAst = parseModule(` + import { Outlet } from '@remix-run/react'; + + export default function App() { + return ; + } + `); + + wrapAppWithSentry(originalRootAst, "root.tsx"); + + const result = originalRootAst.generate().code; + + expect(result).toMatchInlineSnapshot(` + "import {withSentry} from '@sentry/remix'; + import { Outlet } from '@remix-run/react'; + + function App() { + return ; + } + + export default withSentry(App);" + `); + }); +}); + +describe("isWithSentryAlreadyUsed", () => { + it("should return false when withSentry is not used", () => { + const rootAst = parseModule(` + import { Outlet } from '@remix-run/react'; + + export default function App() { + return ; + } + `); + + expect(isWithSentryAlreadyUsed(rootAst)).toBe(false); + }); + + it("should return true when withSentry is used in default export", () => { + const rootAst = parseModule(` + import { withSentry } from '@sentry/remix'; + import { Outlet } from '@remix-run/react'; + + function App() { + return ; + } + + export default withSentry(App); + `); + + expect(isWithSentryAlreadyUsed(rootAst)).toBe(true); + }); + + it("should return true when withSentry is used in a variable assignment", () => { + const rootAst = parseModule(` + import { withSentry } from '@sentry/remix'; + import { Outlet } from '@remix-run/react'; + + function App() { + return ; + } + + const WrappedApp = withSentry(App); + export default WrappedApp; + `); + + expect(isWithSentryAlreadyUsed(rootAst)).toBe(true); + }); + + it("should return true when withSentry is used inside a function", () => { + const rootAst = parseModule(` + import { withSentry } from '@sentry/remix'; + import { Outlet } from '@remix-run/react'; + + function App() { + return ; + } + + function createApp() { + return withSentry(App); + } + + export default createApp(); + `); + + expect(isWithSentryAlreadyUsed(rootAst)).toBe(true); + }); + + it("should return false when withSentry is imported but not used", () => { + const rootAst = parseModule(` + import { withSentry } from '@sentry/remix'; + import { Outlet } from '@remix-run/react'; + + export default function App() { + return ; + } + `); + + expect(isWithSentryAlreadyUsed(rootAst)).toBe(false); + }); + + it("should return false when a different function with similar name is used", () => { + const rootAst = parseModule(` + import { Outlet } from '@remix-run/react'; + + function withSentryLike() { + return null; + } + + export default function App() { + withSentryLike(); + return ; + } + `); + + expect(isWithSentryAlreadyUsed(rootAst)).toBe(false); + }); +}); + +describe("instrumentRoot", () => { + const fixturesDir = path.join(__dirname, "fixtures"); + const tmpDir = path.join(fixturesDir, "tmp"); + + beforeEach(() => { + vi.clearAllMocks(); + // Mock process.cwd() to return the fixtures directory + vi.spyOn(process, "cwd").mockReturnValue(fixturesDir); + }); + + afterEach(() => { + // Clean up any temporary files + if (existsSync(tmpDir)) { + try { + // Remove files first, then directory + const appDir = path.join(tmpDir, "app"); + if (existsSync(appDir)) { + const files = readdirSync(appDir); + for (const file of files) { + unlinkSync(path.join(appDir, file)); + } + rmdirSync(appDir); + } + + const files = readdirSync(tmpDir); + for (const file of files) { + const filePath = path.join(tmpDir, file); + const stat = statSync(filePath); + if (stat.isDirectory()) { + rmdirSync(filePath); + } else { + unlinkSync(filePath); + } + } + } catch (error) { + // Ignore cleanup errors in tests + } + } + }); + + it("should add ErrorBoundary and wrap app with Sentry when no ErrorBoundary exists and withSentry is not used", async () => { + // Copy fixture to tmp directory for testing + const srcFile = path.join(fixturesDir, "root-no-error-boundary.tsx"); + const appDir = path.join(tmpDir, "app"); + + // Create app directory and copy file + mkdirSync(appDir, { recursive: true }); + copyFileSync(srcFile, path.join(appDir, "root.tsx")); + + // Mock process.cwd() to return tmpDir + vi.spyOn(process, "cwd").mockReturnValue(tmpDir); + + await instrumentRoot("root.tsx"); + + // Check that the file was modified correctly + const modifiedContent = readFileSync(path.join(appDir, "root.tsx"), "utf8"); + + expect(modifiedContent).toContain( + 'import { captureRemixErrorBoundaryError, withSentry } from "@sentry/remix";', + ); + expect(modifiedContent).toContain( + "import { Outlet, useRouteError } from '@remix-run/react';", + ); + expect(modifiedContent).toContain("withSentry(App)"); + expect(modifiedContent).toContain("const ErrorBoundary = () => {"); + }); + + it("should wrap app with Sentry when ErrorBoundary exists but no Sentry content", async () => { + const srcFile = path.join(fixturesDir, "root-with-error-boundary.tsx"); + const appDir = path.join(tmpDir, "app"); + + mkdirSync(appDir, { recursive: true }); + copyFileSync(srcFile, path.join(appDir, "root.tsx")); + + vi.spyOn(process, "cwd").mockReturnValue(tmpDir); + + await instrumentRoot("root.tsx"); + + const modifiedContent = readFileSync(path.join(appDir, "root.tsx"), "utf8"); + + expect(modifiedContent).toContain( + 'import { captureRemixErrorBoundaryError, withSentry } from "@sentry/remix";', + ); + expect(modifiedContent).toContain("withSentry(App)"); + }); + + it("should wrap app with Sentry when ErrorBoundary exists with Sentry content but withSentry is not used", async () => { + const srcFile = path.join( + fixturesDir, + "root-with-sentry-error-boundary.tsx", + ); + const appDir = path.join(tmpDir, "app"); + + mkdirSync(appDir, { recursive: true }); + copyFileSync(srcFile, path.join(appDir, "root.tsx")); + + vi.spyOn(process, "cwd").mockReturnValue(tmpDir); + + await instrumentRoot("root.tsx"); + + const modifiedContent = readFileSync(path.join(appDir, "root.tsx"), "utf8"); + + expect(modifiedContent).toContain( + "import { captureRemixErrorBoundaryError, withSentry } from '@sentry/remix';", + ); + expect(modifiedContent).toContain("withSentry(App)"); + }); + + it("should not wrap app when withSentry is already used", async () => { + const srcFile = path.join(fixturesDir, "root-already-wrapped.tsx"); + const appDir = path.join(tmpDir, "app"); + + mkdirSync(appDir, { recursive: true }); + copyFileSync(srcFile, path.join(appDir, "root.tsx")); + + vi.spyOn(process, "cwd").mockReturnValue(tmpDir); + + await instrumentRoot("root.tsx"); + + const modifiedContent = readFileSync(path.join(appDir, "root.tsx"), "utf8"); + + // Should not add withSentry import or wrap again + expect(modifiedContent).toContain("withSentry(App)"); + + // Count occurrences of withSentry to ensure it's not duplicated + const withSentryOccurrences = (modifiedContent.match(/withSentry/g) || []) + .length; + expect(withSentryOccurrences).toBe(2); // One import, one usage + + // The content should remain largely the same since withSentry is already used + expect(modifiedContent).toContain("export default withSentry(App)"); + }); + + it("should handle ErrorBoundary as variable declaration", async () => { + const srcFile = path.join(fixturesDir, "root-variable-error-boundary.tsx"); + const appDir = path.join(tmpDir, "app"); + + mkdirSync(appDir, { recursive: true }); + copyFileSync(srcFile, path.join(appDir, "root.tsx")); + + vi.spyOn(process, "cwd").mockReturnValue(tmpDir); + + await instrumentRoot("root.tsx"); + + const modifiedContent = readFileSync(path.join(appDir, "root.tsx"), "utf8"); + + expect(modifiedContent).toContain( + 'import { captureRemixErrorBoundaryError, withSentry } from "@sentry/remix";', + ); + expect(modifiedContent).toContain("withSentry(App)"); + }); +}); diff --git a/packages/cli/test/lib/wizard/remix/server-instrumentation.test.ts b/packages/cli/test/lib/wizard/remix/server-instrumentation.test.ts new file mode 100644 index 000000000..2a5d2effa --- /dev/null +++ b/packages/cli/test/lib/wizard/remix/server-instrumentation.test.ts @@ -0,0 +1,79 @@ +import { describe, expect, it } from "vitest"; +import { generateServerInstrumentationFile } from "../../../../src/lib/wizard/remix/sdk-setup.js"; + +describe("generateServerInstrumentationFile", () => { + it("should generate server instrumentation file", () => { + const result = generateServerInstrumentationFile( + "https://sentry.io/123", + { + performance: true, + replay: true, + }, + false, + ); + + expect(result.instrumentationFileMod.generate().code) + .toMatchInlineSnapshot(` + "import * as Sentry from "@sentry/remix"; + + Sentry.init({ + dsn: "https://sentry.io/123", + tracesSampleRate: 1 + })" + `); + }); + + it("should generate server instrumentation file when performance is disabled", () => { + const result = generateServerInstrumentationFile( + "https://sentry.io/123", + { + performance: false, + replay: true, + }, + false, + ); + + expect(result.instrumentationFileMod.generate().code) + .toMatchInlineSnapshot(` + "import * as Sentry from "@sentry/remix"; + + Sentry.init({ + dsn: "https://sentry.io/123" + })" + `); + }); + + it("should add the dataCollection preset when reduced data collection is requested", () => { + const result = generateServerInstrumentationFile( + "https://sentry.io/123", + { + performance: true, + replay: true, + }, + true, + ); + + expect(result.instrumentationFileMod.generate().code) + .toMatchInlineSnapshot(` + "import * as Sentry from "@sentry/remix"; + + Sentry.init({ + dsn: "https://sentry.io/123", + 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"] }, + }, + })" + `); + }); +}); diff --git a/packages/cli/test/lib/wizard/sveltekit/sdk-setup/enable-tracing.test.ts b/packages/cli/test/lib/wizard/sveltekit/sdk-setup/enable-tracing.test.ts new file mode 100644 index 000000000..72b7533f5 --- /dev/null +++ b/packages/cli/test/lib/wizard/sveltekit/sdk-setup/enable-tracing.test.ts @@ -0,0 +1,142 @@ +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"; + +const { showCopyPasteInstructionsMock } = vi.hoisted(() => ({ + showCopyPasteInstructionsMock: vi.fn( + (_options: { filename: string; codeSnippet: string }) => Promise.resolve(), + ), +})); + +vi.mock("@clack/prompts", () => ({ + log: { + info: vi.fn(), + warning: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + success: vi.fn(), + }, +})); + +vi.mock("../../../../../src/lib/error-reporting.js", () => ({ + reportCliError: vi.fn(), +})); + +vi.mock("../../../../../src/lib/wizard/utils/clack/index.js", () => ({ + showCopyPasteInstructions: showCopyPasteInstructionsMock, + makeCodeSnippet: ( + _colors: boolean, + callback: ( + unchanged: (str: string) => string, + plus: (str: string) => string, + ) => string, + ) => + callback( + (str) => str, + (str) => str, + ), +})); + +import { enableTracingAndInstrumentation } from "../../../../../src/lib/wizard/sveltekit/sdk-setup/svelte-config.js"; + +const configWith = (experimental: string) => `const config = { + kit: { + experimental: ${experimental}, + }, +}; + +export default config; +`; + +describe("enableTracingAndInstrumentation", () => { + let tmpDir: string; + let configPath: string; + + beforeEach(() => { + vi.clearAllMocks(); + tmpDir = mkdtempSync(path.join(tmpdir(), "sveltekit-config-test-")); + configPath = path.join(tmpDir, "svelte.config.js"); + vi.spyOn(process, "cwd").mockReturnValue(tmpDir); + }); + + afterEach(() => { + vi.restoreAllMocks(); + rmSync(tmpDir, { recursive: true, force: true }); + }); + + it("turns on server options that are present but disabled", async () => { + writeFileSync( + configPath, + configWith( + "{ tracing: { server: false }, instrumentation: { server: true } }", + ), + ); + + await enableTracingAndInstrumentation( + { + kit: { + experimental: { + tracing: { server: false }, + instrumentation: { server: true }, + }, + }, + }, + true, + ); + + const result = readFileSync(configPath, "utf-8"); + expect(result).toMatch(/tracing: \{\s*server: true/); + expect(result).toMatch(/instrumentation: \{\s*server: true/); + expect(showCopyPasteInstructionsMock).not.toHaveBeenCalled(); + }); + + it("fills empty experimental objects", async () => { + writeFileSync( + configPath, + configWith("{ tracing: {}, instrumentation: {} }"), + ); + + await enableTracingAndInstrumentation( + { kit: { experimental: { tracing: {}, instrumentation: {} } } }, + true, + ); + + const result = readFileSync(configPath, "utf-8"); + expect(result).toMatch(/tracing: \{\s*server: true/); + expect(result).toMatch(/instrumentation: \{\s*server: true/); + }); + + it("leaves a fully enabled config untouched", async () => { + const content = configWith( + "{ tracing: { server: true }, instrumentation: { server: true } }", + ); + writeFileSync(configPath, content); + + await enableTracingAndInstrumentation( + { + kit: { + experimental: { + tracing: { server: true }, + instrumentation: { server: true }, + }, + }, + }, + true, + ); + + expect(readFileSync(configPath, "utf-8")).toBe(content); + }); + + it("keeps server tracing off in the fallback snippet when tracing was declined", async () => { + writeFileSync(configPath, "export default {{{ not js"); + + await enableTracingAndInstrumentation({}, false); + + expect(showCopyPasteInstructionsMock).toHaveBeenCalledTimes(1); + const codeSnippet = + showCopyPasteInstructionsMock.mock.calls[0]?.[0]?.codeSnippet ?? ""; + expect(codeSnippet).toMatch(/tracing: \{\s*server: false/); + expect(codeSnippet).toMatch(/instrumentation: \{\s*server: true/); + }); +}); diff --git a/packages/cli/test/lib/wizard/sveltekit/sdk-setup/svelte-config.test.ts b/packages/cli/test/lib/wizard/sveltekit/sdk-setup/svelte-config.test.ts new file mode 100644 index 000000000..c59ea90f0 --- /dev/null +++ b/packages/cli/test/lib/wizard/sveltekit/sdk-setup/svelte-config.test.ts @@ -0,0 +1,682 @@ +import { describe, it, expect } from "vitest"; +import { _enableTracingAndInstrumentationInConfig } from "../../../../../src/lib/wizard/sveltekit/sdk-setup/svelte-config.js"; + +describe("_enableTracingAndInstrumentationInConfig", () => { + it("leaves already correct config unchanged", () => { + const originalConfig = `export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + tracing: { + server: true, + }, + instrumentation: { + server: true, + }, + }, + }, +};`; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.result).toBe(originalConfig); + }); + + describe("successfully handles", () => { + it("default config as variable declaration", () => { + const originalConfig = `/** @type {import('@sveltejs/kit').Config} */ +const config = { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + }, +}; + +export default config; +`; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.result).toMatchInlineSnapshot(` + "/** @type {import('@sveltejs/kit').Config} */ + const config = { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + + experimental: { + tracing: { + server: true, + }, + + instrumentation: { + server: true, + }, + }, + }, + }; + + export default config;" + `); + }); + + it("default config named declaration object", () => { + const originalConfig = ` +export default config = { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + }, +}; +`; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.result).toMatchInlineSnapshot(` + "export default config = { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + + experimental: { + tracing: { + server: true, + }, + + instrumentation: { + server: true, + }, + }, + }, + };" + `); + }); + + it("default config as in-place object", () => { + const originalConfig = ` +export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + }, +}; +`; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.result).toMatchInlineSnapshot(` + "export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + + experimental: { + tracing: { + server: true, + }, + + instrumentation: { + server: true, + }, + }, + }, + };" + `); + }); + + it("config with tracing disabled", () => { + const originalConfig = ` +export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + }, +}; +`; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + false, + ); + + expect(modifiedConfig.result).toMatchInlineSnapshot(` + "export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + + experimental: { + tracing: { + server: false, + }, + + instrumentation: { + server: true, + }, + }, + }, + };" + `); + }); + + it("config with pre-existing `kit.experimental` property", () => { + const originalConfig = ` +export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + remoteFunctions: true, + } + }, +}; +`; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.result).toMatchInlineSnapshot(` + "export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + remoteFunctions: true, + + tracing: { + server: true, + }, + + instrumentation: { + server: true, + }, + } + }, + };" + `); + }); + + it("config with pre-existing and empty `kit.experimental.tracing` property", () => { + const originalConfig = ` +export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + remoteFunctions: true, + tracing: { + }, + } + }, +}; +`; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.result).toMatchInlineSnapshot(` + "export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + remoteFunctions: true, + + tracing: { + server: true, + }, + + instrumentation: { + server: true, + }, + } + }, + };" + `); + }); + + it("config with pre-existing and empty `kit.experimental.instrumentation` property", () => { + const originalConfig = ` +export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + remoteFunctions: true, + tracing: { + }, + instrumentation: { + }, + } + }, +}; +`; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.result).toMatchInlineSnapshot(` + "export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + remoteFunctions: true, + tracing: { + server: true, + }, + instrumentation: { + server: true, + }, + } + }, + };" + `); + }); + + it("config with pre-existing and filled `kit.experimental.(instrumentation|tracing).server` properties", () => { + const originalConfig = ` +export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + remoteFunctions: true, + tracing: { + server: false, + }, + instrumentation: { + server: false, + }, + } + }, +}; +`; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.result).toMatchInlineSnapshot(` + "export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + remoteFunctions: true, + tracing: { + server: true, + }, + instrumentation: { + server: true, + }, + } + }, + };" + `); + }); + + it("config with pre-existing and filled `kit.experimental.(instrumentation|tracing).server` properties with instrumentation disabled", () => { + const originalConfig = ` +export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + remoteFunctions: true, + tracing: { + server: true, + }, + instrumentation: { + server: false, + }, + } + }, +}; +`; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.result).toMatchInlineSnapshot(` + "export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + remoteFunctions: true, + tracing: { + server: true, + }, + instrumentation: { + server: true, + }, + } + }, + };" + `); + }); + + it("config with pre-existing and filled `kit.experimental.(instrumentation|tracing).server` properties with tracing disabled", () => { + const originalConfig = ` +export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + remoteFunctions: true, + tracing: { + server: false, + }, + instrumentation: { + server: true, + }, + } + }, +}; +`; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.result).toMatchInlineSnapshot(` + "export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + remoteFunctions: true, + tracing: { + server: true, + }, + instrumentation: { + server: true, + }, + } + }, + };" + `); + }); + }); + + describe("gracefully errors if", () => { + it("config object not found", () => { + const originalConfig = `console.log('hello')`; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.error).toBe("Couldn't find the config object"); + }); + + it("config is not an object", () => { + const originalConfig = ` + export default getSvelteConfig(); + `; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.error).toBe("Couldn't find the config object"); + }); + + it("`kit` property is missing", () => { + const originalConfig = ` + export default { + preprocess: vitePreprocess(), + }; + `; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.error).toBe("Couldn't find the `kit` property"); + }); + + it("`kit` property has unexpected type", () => { + const originalConfig = ` + export default { + preprocess: vitePreprocess(), + + kit: getKitConfig(), + }; + `; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.error).toBe( + "`kit` property has unexpected type: CallExpression", + ); + }); + + it("`kit.experimental` property has unexpected type", () => { + const originalConfig = ` + export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: 'hello', + }, + }; + `; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.error).toBe( + "Property `kit.experimental` has unexpected type: StringLiteral", + ); + }); + + it("`kit.experimental.tracing` property has unexpected type", () => { + const originalConfig = ` + export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + tracing: true, + }, + }, + }; + `; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.error).toBe( + "Property `kit.experimental.tracing` has unexpected type: BooleanLiteral", + ); + }); + + it("`kit.experimental.instrumentation` property has unexpected type", () => { + const originalConfig = ` + export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + tracing: { + server: true, + }, + instrumentation: 'server', + }, + }, + }; + `; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.error).toBe( + "Property `kit.experimental.instrumentation` has unexpected type: StringLiteral", + ); + }); + + it("`kit.experimental.tracing.server` property has unexpected type", () => { + const originalConfig = ` + export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + tracing: { + server: !!process.env['ENABLE_TRACING'], + }, + instrumentation: { + server: true, + }, + }, + }, + }; + `; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.error).toBe( + "Property `kit.experimental.tracing.server` has unexpected type: UnaryExpression", + ); + }); + + it("`kit.experimental.instrumentation.server` property has unexpected type", () => { + const originalConfig = ` + export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + tracing: { + server: true, + }, + instrumentation: { + server: 'hello', + }, + }, + }, + }; + `; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.error).toBe( + "Property `kit.experimental.instrumentation.server` has unexpected type: StringLiteral", + ); + }); + + it("config parsing fails", () => { + const originalConfig = ` + export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + tracing: { + server: true, + } + instrumentation: { + server: 'hello', + }, + }, + }, + }; + `; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.error).toBe("Failed to parse Svelte config"); + }); + }); + + it("keeps tracing.server true in the file when tracing is declined", () => { + const { result, error } = _enableTracingAndInstrumentationInConfig( + `export default { + kit: { + experimental: { + tracing: { server: true }, + }, + }, +}; +`, + false, + ); + + expect(error).toBeUndefined(); + expect(result).toMatch(/tracing:\s*\{\s*server:\s*true/); + expect(result).not.toMatch(/tracing:\s*\{\s*server:\s*false/); + }); +}); diff --git a/packages/cli/test/lib/wizard/sveltekit/sdk-setup/vite.test.ts b/packages/cli/test/lib/wizard/sveltekit/sdk-setup/vite.test.ts new file mode 100644 index 000000000..72098b6f7 --- /dev/null +++ b/packages/cli/test/lib/wizard/sveltekit/sdk-setup/vite.test.ts @@ -0,0 +1,129 @@ +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"; + +vi.mock("@clack/prompts", () => ({ + log: { + warn: vi.fn(), + warning: vi.fn(), + success: vi.fn(), + info: vi.fn(), + step: vi.fn(), + }, + select: vi.fn(() => Promise.resolve(true)), +})); + +vi.mock("../../../../../src/lib/error-reporting.js", () => ({ + reportCliError: vi.fn(), +})); + +vi.mock("../../../../../src/lib/wizard/utils/clack/index.js", () => ({ + abortIfCancelled: vi.fn((v: unknown) => v), +})); + +import { log } from "@clack/prompts"; +import { modifyViteConfig } from "../../../../../src/lib/wizard/sveltekit/sdk-setup/vite.js"; +import type { ProjectInfo } from "../../../../../src/lib/wizard/sveltekit/sdk-setup/types.js"; + +const baseViteConfig = `import { sveltekit } from '@sveltejs/kit/vite'; +import { defineConfig } from 'vite'; + +export default defineConfig({ + plugins: [sveltekit()] +}); +`; + +describe("modifyViteConfig", () => { + let tmpDir: string; + let viteConfigPath: string; + + const projectInfo = (overrides: Partial): ProjectInfo => ({ + dsn: "https://public@dsn.ingest.sentry.io/1337", + org: "my-org", + project: "my-project", + selfHosted: false, + url: "https://sentry.io/", + vitePluginImportPath: "@sentry/sveltekit/vite", + reduceDataCollection: false, + ...overrides, + }); + + beforeEach(() => { + tmpDir = mkdtempSync(path.join(tmpdir(), "sveltekit-vite-test-")); + viteConfigPath = path.join(tmpDir, "vite.config.js"); + writeFileSync(viteConfigPath, baseViteConfig); + }); + + afterEach(() => { + rmSync(tmpDir, { recursive: true, force: true }); + }); + + it("imports sentrySvelteKit from the given path and writes sentryUrl for self-hosted", async () => { + await modifyViteConfig( + viteConfigPath, + projectInfo({ + selfHosted: true, + url: "https://sentry.example.com/", + vitePluginImportPath: "@sentry/sveltekit/vite", + }), + ); + + const result = readFileSync(viteConfigPath, "utf-8"); + expect(result).toContain( + 'import { sentrySvelteKit } from "@sentry/sveltekit/vite";', + ); + expect(result).toContain("sentrySvelteKit({"); + expect(result).toContain('org: "my-org"'); + expect(result).toContain('project: "my-project"'); + expect(result).toContain('sentryUrl: "https://sentry.example.com/"'); + expect(result).not.toMatch(/\burl:/); + // registered before sveltekit() + expect(result.indexOf("sentrySvelteKit(")).toBeLessThan( + result.indexOf("sveltekit()"), + ); + }); + + it("imports from the root export when the installed SDK requires it", async () => { + await modifyViteConfig( + viteConfigPath, + projectInfo({ vitePluginImportPath: "@sentry/sveltekit" }), + ); + + const result = readFileSync(viteConfigPath, "utf-8"); + expect(result).toContain( + 'import { sentrySvelteKit } from "@sentry/sveltekit";', + ); + expect(result).not.toContain("@sentry/sveltekit/vite"); + expect(result).not.toContain("sentryUrl"); + }); + + it("leaves a config that already contains Sentry code untouched", async () => { + const existing = `import { sentrySvelteKit } from "@sentry/sveltekit"; +import { sveltekit } from '@sveltejs/kit/vite'; +import { defineConfig } from 'vite'; + +export default defineConfig({ + plugins: [sentrySvelteKit({ org: "old" }), sveltekit()] +}); +`; + writeFileSync(viteConfigPath, existing); + + await modifyViteConfig(viteConfigPath, projectInfo({})); + + expect(readFileSync(viteConfigPath, "utf-8")).toBe(existing); + }); + + it("does not report success when the automatic edit fails", async () => { + vi.clearAllMocks(); + // A config that magicast can parse but `addVitePlugin` cannot handle. + writeFileSync(viteConfigPath, "export default 42;\n"); + + await modifyViteConfig(viteConfigPath, projectInfo({})); + + expect(log.warning).toHaveBeenCalledWith( + expect.stringContaining("Couldn't automatically modify"), + ); + expect(log.success).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/cli/test/lib/wizard/sveltekit/templates.test.ts b/packages/cli/test/lib/wizard/sveltekit/templates.test.ts new file mode 100644 index 000000000..94d41f69e --- /dev/null +++ b/packages/cli/test/lib/wizard/sveltekit/templates.test.ts @@ -0,0 +1,1201 @@ +import { describe, expect, it, vi } from "vitest"; +import { + getClientHooksTemplate, + getInstrumentationServerTemplate, + getSentryExampleApiRoute, + getSentryExampleSveltePage, + getServerHooksTemplate, +} from "../../../../src/lib/wizard/sveltekit/templates.js"; +import { insertClientInitCall } from "../../../../src/lib/wizard/sveltekit/sdk-setup/setup.js"; +import { parseModule } from "magicast"; + +vi.mock("../../../../src/lib/wizard/utils/clack/mcp-config.js", () => ({ + offerProjectScopedMcpConfig: vi.fn().mockResolvedValue(undefined), +})); + +describe("getClientHooksTemplate", () => { + it("generates client hooks template with all features enabled", () => { + const result = getClientHooksTemplate( + "https://sentry.io/123", + { + performance: true, + replay: true, + }, + false, + ); + + expect(result).toMatchInlineSnapshot(` + "import { handleErrorWithSentry, replayIntegration } from "@sentry/sveltekit"; + import * as Sentry from '@sentry/sveltekit'; + + Sentry.init({ + dsn: 'https://sentry.io/123', + + tracesSampleRate: 1.0, + + // This sets the sample rate to be 10%. You may want this to be 100% while + // in development and sample at a lower rate in production + replaysSessionSampleRate: 0.1, + + // If the entire session is not sampled, use the below sample rate to sample + // sessions when an error occurs. + replaysOnErrorSampleRate: 1.0, + + // If you don't want to use Session Replay, just remove the line below: + integrations: [replayIntegration()], + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/sveltekit/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + + // If you have a custom error handler, pass it to \`handleErrorWithSentry\` + export const handleError = handleErrorWithSentry(); + " + `); + }); + + it("generates client hooks template when performance disabled", () => { + const result = getClientHooksTemplate( + "https://sentry.io/123", + { + performance: false, + replay: true, + }, + false, + ); + + expect(result).toMatchInlineSnapshot(` + "import { handleErrorWithSentry, replayIntegration } from "@sentry/sveltekit"; + import * as Sentry from '@sentry/sveltekit'; + + Sentry.init({ + dsn: 'https://sentry.io/123', + + // This sets the sample rate to be 10%. You may want this to be 100% while + // in development and sample at a lower rate in production + replaysSessionSampleRate: 0.1, + + // If the entire session is not sampled, use the below sample rate to sample + // sessions when an error occurs. + replaysOnErrorSampleRate: 1.0, + + // If you don't want to use Session Replay, just remove the line below: + integrations: [replayIntegration()], + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/sveltekit/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + + // If you have a custom error handler, pass it to \`handleErrorWithSentry\` + export const handleError = handleErrorWithSentry(); + " + `); + }); + + it("generates client hooks template when replay disabled", () => { + const result = getClientHooksTemplate( + "https://sentry.io/123", + { + performance: true, + replay: false, + }, + false, + ); + + expect(result).toMatchInlineSnapshot(` + "import { handleErrorWithSentry, replayIntegration } from "@sentry/sveltekit"; + import * as Sentry from '@sentry/sveltekit'; + + Sentry.init({ + dsn: 'https://sentry.io/123', + + tracesSampleRate: 1.0, + + + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/sveltekit/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + + // If you have a custom error handler, pass it to \`handleErrorWithSentry\` + export const handleError = handleErrorWithSentry(); + " + `); + }); + + it("generates client hooks template with reduced data collection", () => { + const result = getClientHooksTemplate( + "https://sentry.io/123", + { + performance: true, + replay: true, + }, + true, + ); + + expect(result).toMatchInlineSnapshot(` + "import { handleErrorWithSentry, replayIntegration } from "@sentry/sveltekit"; + import * as Sentry from '@sentry/sveltekit'; + + Sentry.init({ + dsn: 'https://sentry.io/123', + + tracesSampleRate: 1.0, + + // This sets the sample rate to be 10%. You may want this to be 100% while + // in development and sample at a lower rate in production + replaysSessionSampleRate: 0.1, + + // If the entire session is not sampled, use the below sample rate to sample + // sessions when an error occurs. + replaysOnErrorSampleRate: 1.0, + + // If you don't want to use Session Replay, just remove the line below: + integrations: [replayIntegration()], + + // Turns off collection of data that could identify users. Adjust per category: + // https://docs.sentry.io/platforms/javascript/configuration/options/#dataCollection + dataCollection: { + userInfo: false, + graphQL: { document: false, variables: false }, + genAI: { inputs: false, outputs: false }, + databaseQueryData: false, + queues: false, + httpBodies: [], + httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + cookies: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + urlQueryParams: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + }, + }); + + // If you have a custom error handler, pass it to \`handleErrorWithSentry\` + export const handleError = handleErrorWithSentry(); + " + `); + }); +}); + +describe("getServerHooksTemplate", () => { + it("generates server hooks template with all features enabled", () => { + const result = getServerHooksTemplate( + "https://sentry.io/123", + { + performance: true, + replay: true, + }, + true, + false, + ); + + expect(result).toMatchInlineSnapshot(` + "import { sequence } from "@sveltejs/kit/hooks"; + import { handleErrorWithSentry, sentryHandle } from "@sentry/sveltekit"; + import * as Sentry from '@sentry/sveltekit'; + + Sentry.init({ + dsn: 'https://sentry.io/123', + + tracesSampleRate: 1.0, + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/sveltekit/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + + // uncomment the line below to enable Spotlight (https://spotlightjs.com) + // spotlight: import.meta.env.DEV, + }); + + // If you have custom handlers, make sure to place them after \`sentryHandle()\` in the \`sequence\` function. + export const handle = sequence(sentryHandle()); + + // If you have a custom error handler, pass it to \`handleErrorWithSentry\` + export const handleError = handleErrorWithSentry(); + " + `); + }); + + it("generates server hooks template when performance disabled", () => { + const result = getServerHooksTemplate( + "https://sentry.io/123", + { + performance: false, + replay: true, + }, + true, + false, + ); + + expect(result).toMatchInlineSnapshot(` + "import { sequence } from "@sveltejs/kit/hooks"; + import { handleErrorWithSentry, sentryHandle } from "@sentry/sveltekit"; + import * as Sentry from '@sentry/sveltekit'; + + Sentry.init({ + dsn: 'https://sentry.io/123', + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/sveltekit/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + + // uncomment the line below to enable Spotlight (https://spotlightjs.com) + // spotlight: import.meta.env.DEV, + }); + + // If you have custom handlers, make sure to place them after \`sentryHandle()\` in the \`sequence\` function. + export const handle = sequence(sentryHandle()); + + // If you have a custom error handler, pass it to \`handleErrorWithSentry\` + export const handleError = handleErrorWithSentry(); + " + `); + }); + + it("generates server hooks template without Sentry.init if includeSentryInit is false", () => { + const result = getServerHooksTemplate( + "https://sentry.io/123", + { + performance: false, + replay: false, + }, + false, + false, + ); + + expect(result).toMatchInlineSnapshot(` + "import { sequence } from "@sveltejs/kit/hooks"; + import { handleErrorWithSentry, sentryHandle } from "@sentry/sveltekit"; + + + // If you have custom handlers, make sure to place them after \`sentryHandle()\` in the \`sequence\` function. + export const handle = sequence(sentryHandle()); + + // If you have a custom error handler, pass it to \`handleErrorWithSentry\` + export const handleError = handleErrorWithSentry(); + " + `); + }); + + it("generates server hooks template with reduced data collection", () => { + const result = getServerHooksTemplate( + "https://sentry.io/123", + { + performance: true, + replay: true, + }, + true, + true, + ); + + expect(result).toMatchInlineSnapshot(` + "import { sequence } from "@sveltejs/kit/hooks"; + import { handleErrorWithSentry, sentryHandle } from "@sentry/sveltekit"; + import * as Sentry from '@sentry/sveltekit'; + + Sentry.init({ + dsn: 'https://sentry.io/123', + + tracesSampleRate: 1.0, + + // Turns off collection of data that could identify users. Adjust per category: + // https://docs.sentry.io/platforms/javascript/configuration/options/#dataCollection + dataCollection: { + userInfo: false, + graphQL: { document: false, variables: false }, + genAI: { inputs: false, outputs: false }, + databaseQueryData: false, + queues: false, + httpBodies: [], + httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + cookies: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + urlQueryParams: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + }, + + // uncomment the line below to enable Spotlight (https://spotlightjs.com) + // spotlight: import.meta.env.DEV, + }); + + // If you have custom handlers, make sure to place them after \`sentryHandle()\` in the \`sequence\` function. + export const handle = sequence(sentryHandle()); + + // If you have a custom error handler, pass it to \`handleErrorWithSentry\` + export const handleError = handleErrorWithSentry(); + " + `); + }); +}); + +describe("getInstrumentationServerTemplate", () => { + it("generates instrumentation.server template with all features enabled", () => { + const result = getInstrumentationServerTemplate( + "https://sentry.io/123", + { + performance: true, + }, + false, + ); + + expect(result).toMatchInlineSnapshot(` + "import * as Sentry from '@sentry/sveltekit'; + + Sentry.init({ + dsn: 'https://sentry.io/123', + + tracesSampleRate: 1.0, + // uncomment the line below to enable Spotlight (https://spotlightjs.com) + // spotlight: import.meta.env.DEV, + });" + `); + }); + + it("generates instrumentation.server template with only tracesSampleRate enabled", () => { + const result = getInstrumentationServerTemplate( + "https://sentry.io/123", + { + performance: true, + }, + false, + ); + + expect(result).toMatchInlineSnapshot(` + "import * as Sentry from '@sentry/sveltekit'; + + Sentry.init({ + dsn: 'https://sentry.io/123', + + tracesSampleRate: 1.0, + // uncomment the line below to enable Spotlight (https://spotlightjs.com) + // spotlight: import.meta.env.DEV, + });" + `); + }); + + it("generates instrumentation.server template without any extra features enabled", () => { + const result = getInstrumentationServerTemplate( + "https://sentry.io/123", + { + performance: false, + }, + false, + ); + + expect(result).toMatchInlineSnapshot(` + "import * as Sentry from '@sentry/sveltekit'; + + Sentry.init({ + dsn: 'https://sentry.io/123', + // uncomment the line below to enable Spotlight (https://spotlightjs.com) + // spotlight: import.meta.env.DEV, + });" + `); + }); + + it("generates instrumentation.server template with reduced data collection", () => { + const result = getInstrumentationServerTemplate( + "https://sentry.io/123", + { + performance: true, + }, + true, + ); + + expect(result).toMatchInlineSnapshot(` + "import * as Sentry from '@sentry/sveltekit'; + + Sentry.init({ + dsn: 'https://sentry.io/123', + + tracesSampleRate: 1.0, + // Turns off collection of data that could identify users. Adjust per category: + // https://docs.sentry.io/platforms/javascript/configuration/options/#dataCollection + dataCollection: { + userInfo: false, + graphQL: { document: false, variables: false }, + genAI: { inputs: false, outputs: false }, + databaseQueryData: false, + queues: false, + httpBodies: [], + httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + cookies: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + urlQueryParams: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + }, + // uncomment the line below to enable Spotlight (https://spotlightjs.com) + // spotlight: import.meta.env.DEV, + });" + `); + }); +}); + +describe("insertClientInitCall", () => { + it("should insert client init call with all features enabled", () => { + const originalHooksMod = parseModule(` + import { handleErrorWithSentry } from "@sentry/sveltekit"; + import * as Sentry from "@sentry/sveltekit"; + + export const handleError = handleErrorWithSentry(); + `); + + insertClientInitCall( + "https://sentry.io/123", + originalHooksMod, + { + performance: true, + replay: true, + }, + false, + ); + + const result = originalHooksMod.generate().code; + + expect(result).toMatchInlineSnapshot(` + "import { handleErrorWithSentry } from "@sentry/sveltekit"; + import * as Sentry from "@sentry/sveltekit"; + + // If you don't want to use Session Replay, remove the \`Replay\` integration, + // \`replaysSessionSampleRate\` and \`replaysOnErrorSampleRate\` options. + Sentry.init({ + dsn: "https://sentry.io/123", + tracesSampleRate: 1, + replaysSessionSampleRate: 0.1, + replaysOnErrorSampleRate: 1, + integrations: [Sentry.replayIntegration()], + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/sveltekit/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }) + + export const handleError = handleErrorWithSentry();" + `); + }); + + it("should insert client init call with performance disabled", () => { + const originalHooksMod = parseModule(` + import { handleErrorWithSentry } from "@sentry/sveltekit"; + import * as Sentry from "@sentry/sveltekit"; + + export const handleError = handleErrorWithSentry(); + `); + + insertClientInitCall( + "https://sentry.io/456", + originalHooksMod, + { + performance: false, + replay: true, + }, + false, + ); + + const result = originalHooksMod.generate().code; + + expect(result).toMatchInlineSnapshot(` + "import { handleErrorWithSentry } from "@sentry/sveltekit"; + import * as Sentry from "@sentry/sveltekit"; + + // If you don't want to use Session Replay, remove the \`Replay\` integration, + // \`replaysSessionSampleRate\` and \`replaysOnErrorSampleRate\` options. + Sentry.init({ + dsn: "https://sentry.io/456", + replaysSessionSampleRate: 0.1, + replaysOnErrorSampleRate: 1, + integrations: [Sentry.replayIntegration()], + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/sveltekit/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }) + + export const handleError = handleErrorWithSentry();" + `); + }); + + it("should insert client init call with replay disabled", () => { + const originalHooksMod = parseModule(` + import { handleErrorWithSentry } from "@sentry/sveltekit"; + import * as Sentry from "@sentry/sveltekit"; + + export const handleError = handleErrorWithSentry(); + `); + + insertClientInitCall( + "https://sentry.io/789", + originalHooksMod, + { + performance: true, + replay: false, + }, + false, + ); + + const result = originalHooksMod.generate().code; + + expect(result).toMatchInlineSnapshot(` + "import { handleErrorWithSentry } from "@sentry/sveltekit"; + import * as Sentry from "@sentry/sveltekit"; + + // If you don't want to use Session Replay, remove the \`Replay\` integration, + // \`replaysSessionSampleRate\` and \`replaysOnErrorSampleRate\` options. + Sentry.init({ + dsn: "https://sentry.io/789", + tracesSampleRate: 1, + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/sveltekit/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }) + + export const handleError = handleErrorWithSentry();" + `); + }); + + it("should insert client init call with all features disabled", () => { + const originalHooksMod = parseModule(` + import { handleErrorWithSentry } from "@sentry/sveltekit"; + import * as Sentry from "@sentry/sveltekit"; + + export const handleError = handleErrorWithSentry(); + `); + + insertClientInitCall( + "https://sentry.io/minimal", + originalHooksMod, + { + performance: false, + replay: false, + }, + false, + ); + + const result = originalHooksMod.generate().code; + + expect(result).toMatchInlineSnapshot(` + "import { handleErrorWithSentry } from "@sentry/sveltekit"; + import * as Sentry from "@sentry/sveltekit"; + + // If you don't want to use Session Replay, remove the \`Replay\` integration, + // \`replaysSessionSampleRate\` and \`replaysOnErrorSampleRate\` options. + Sentry.init({ + dsn: "https://sentry.io/minimal", + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/sveltekit/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }) + + export const handleError = handleErrorWithSentry();" + `); + }); + + it("should insert init call after imports", () => { + const originalHooksMod = parseModule(` + import { handleErrorWithSentry } from "@sentry/sveltekit"; + import { somethingElse } from "some-package"; + import * as Sentry from "@sentry/sveltekit"; + + export const handleError = handleErrorWithSentry(); + export const someOtherExport = somethingElse(); + `); + + insertClientInitCall( + "https://sentry.io/order-test", + originalHooksMod, + { + performance: true, + replay: false, + }, + false, + ); + + const result = originalHooksMod.generate().code; + + expect(result).toMatchInlineSnapshot(` + "import { handleErrorWithSentry } from "@sentry/sveltekit"; + import { somethingElse } from "some-package"; + import * as Sentry from "@sentry/sveltekit"; + + // If you don't want to use Session Replay, remove the \`Replay\` integration, + // \`replaysSessionSampleRate\` and \`replaysOnErrorSampleRate\` options. + Sentry.init({ + dsn: "https://sentry.io/order-test", + tracesSampleRate: 1, + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/sveltekit/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }) + + export const handleError = handleErrorWithSentry(); + export const someOtherExport = somethingElse();" + `); + }); + + it("should insert client init call with reduced data collection", () => { + const originalHooksMod = parseModule(` + import { handleErrorWithSentry } from "@sentry/sveltekit"; + import * as Sentry from "@sentry/sveltekit"; + + export const handleError = handleErrorWithSentry(); + `); + + insertClientInitCall( + "https://sentry.io/123", + originalHooksMod, + { + performance: true, + replay: true, + }, + true, + ); + + const result = originalHooksMod.generate().code; + + expect(result).toMatchInlineSnapshot(` + "import { handleErrorWithSentry } from "@sentry/sveltekit"; + import * as Sentry from "@sentry/sveltekit"; + + // If you don't want to use Session Replay, remove the \`Replay\` integration, + // \`replaysSessionSampleRate\` and \`replaysOnErrorSampleRate\` options. + Sentry.init({ + dsn: "https://sentry.io/123", + tracesSampleRate: 1, + replaysSessionSampleRate: 0.1, + replaysOnErrorSampleRate: 1, + integrations: [Sentry.replayIntegration()], + // Turns off collection of data that could identify users. Adjust per category: + // https://docs.sentry.io/platforms/javascript/configuration/options/#dataCollection + dataCollection: { + userInfo: false, + graphQL: { document: false, variables: false }, + genAI: { inputs: false, outputs: false }, + databaseQueryData: false, + queues: false, + httpBodies: [], + httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + cookies: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + urlQueryParams: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + }, + }) + + export const handleError = handleErrorWithSentry();" + `); + }); +}); + +describe("getSentryExampleSveltePage", () => { + it("generates example page template with Svelte 5", () => { + const result = getSentryExampleSveltePage({ + selfHosted: false, + url: "https://sentry.io", + orgSlug: "test-org", + projectId: "test-project", + isUsingSvelte5: true, + }); + + expect(result).toMatchInlineSnapshot(` + " + + + + sentry-example-page + +
+
+
+ + + +

+ sentry-example-page +

+ +

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

+ + + + {#if hasSentError} +

+ Sample error was sent to Sentry. +

+ {:else if !isConnected} +
+

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

+
+ {:else} +
+ {/if} +
+
+
+ + + " + `); + }); + + it("generates example page template pre-Svelte 5", () => { + const result = getSentryExampleSveltePage({ + selfHosted: false, + url: "https://sentry.io", + orgSlug: "test-org", + projectId: "test-project", + isUsingSvelte5: false, + }); + + expect(result).toMatchInlineSnapshot(` + " + + + + sentry-example-page + +
+
+
+ + + +

+ sentry-example-page +

+ +

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

+ + + + {#if hasSentError} +

+ Sample error was sent to Sentry. +

+ {:else if !isConnected} +
+

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

+
+ {:else} +
+ {/if} +
+
+
+ + + " + `); + }); + + it("generates an issues link for self-hosted", () => { + const result = getSentryExampleSveltePage({ + selfHosted: true, + url: "https://sAntry.com/", + orgSlug: "test-org", + projectId: "test-project", + isUsingSvelte5: true, + }); + + expect(result).toContain( + "https://sAntry.com/organizations/test-org/issues/?project=test-project", + ); + }); + + it("generates an issues link for saas", () => { + const result = getSentryExampleSveltePage({ + selfHosted: false, + url: "https://sentry.io", + orgSlug: "test-org", + projectId: "test-project", + isUsingSvelte5: true, + }); + + expect(result).toContain( + "https://test-org.sentry.io/issues/?project=test-project", + ); + }); +}); + +describe("getSentryExampleApiRoute", () => { + it("generates the correct API route template", () => { + const result = getSentryExampleApiRoute(); + expect(result).toMatchInlineSnapshot(` + "// This is just a very simple API route that throws an example error. + // Feel free to delete this file and the entire sentry route. + + export const GET = async () => { + throw new Error("Sentry Example API Route Error"); + }; + " + `); + }); +}); diff --git a/packages/cli/test/lib/wizard/sveltekit/utils.test.ts b/packages/cli/test/lib/wizard/sveltekit/utils.test.ts new file mode 100644 index 000000000..8fc6b3920 --- /dev/null +++ b/packages/cli/test/lib/wizard/sveltekit/utils.test.ts @@ -0,0 +1,143 @@ +import { describe, it, expect } from "vitest"; +import { + getKitVersionBucket, + getSentrySvelteKitVitePluginImportPath, + getSvelteVersionBucket, + SENTRY_SVELTEKIT_SDK_RANGE, +} from "../../../../src/lib/wizard/sveltekit/utils.js"; + +describe("getKitVersionBucket", () => { + it('returns "none" if version is undefined', () => { + expect(getKitVersionBucket(undefined)).toBe("none"); + }); + + it('returns "none" if version is empty string', () => { + expect(getKitVersionBucket("")).toBe("none"); + }); + + it('returns "invalid" if version is contradictory', () => { + expect(getKitVersionBucket(">1.0.0 <1.0.0")).toBe("invalid"); + }); + + it('returns "invalid" if version is invalid', () => { + expect(getKitVersionBucket("latest")).toBe("invalid"); + }); + + it.each(["0.1.0", "0.9.9", "^0.5.0", "~0.12.0", "0"])( + 'returns "0.x" for versions < 1.0.0', + (version: string) => { + expect(getKitVersionBucket(version)).toBe("0.x"); + }, + ); + + it.each(["1.0.0", "1.1.0", "1.23.9", "^1.0.0", "~1.20.0", ">=1.0.0 <1.24.0"])( + 'returns ">=1.0.0 <1.24.0" for versions >= 1.0.0 and < 1.24.0', + (version: string) => { + expect(getKitVersionBucket(version)).toBe(">=1.0.0 <1.24.0"); + }, + ); + + it.each([ + "1.24.0", + "1.25.0", + "2.0.0", + "2.30.9", + "^1.24.0", + "~2.0.0", + ">=1.24.0 <2.31.0", + ])( + 'returns ">=1.24.0 <2.31.0" for versions >= 1.24.0 and < 2.31.0', + (version: string) => { + expect(getKitVersionBucket(version)).toBe(">=1.24.0 <2.31.0"); + }, + ); + + it.each(["2.31.0", "2.32.0", "3.0.0", "^2.31.0", "~3.0.0", ">=2.31.0"])( + 'returns ">=2.31.0" for versions >= 2.31.0', + (version: string) => { + expect(getKitVersionBucket(version)).toBe(">=2.31.0"); + }, + ); +}); + +describe("getSvelteVersionBucket", () => { + it('returns "none" if version is undefined', () => { + expect(getSvelteVersionBucket(undefined)).toBe("none"); + }); + + it('returns "none" if version is empty string', () => { + expect(getSvelteVersionBucket("")).toBe("none"); + }); + + it('returns "invalid" if version is contradictory', () => { + expect(getSvelteVersionBucket(">1.0.0 <1.0.0")).toBe("invalid"); + }); + + it('returns "invalid" if version is invalid', () => { + expect(getSvelteVersionBucket("latest")).toBe("invalid"); + }); + + it.each(["0.1.0", "1.0.0", "2.9.9", "^2.5.0", "~2.0.0"])( + 'returns "<3.0.0" for versions < 3.0.0', + (version: string) => { + expect(getSvelteVersionBucket(version)).toBe("<3.0.0"); + }, + ); + + it.each(["3.0.0", "3.1.0", "3.59.9", "^3.0.0", "~3.50.0"])( + 'returns "3.x" for versions >= 3.0.0 and < 4.0.0', + (version: string) => { + expect(getSvelteVersionBucket(version)).toBe("3.x"); + }, + ); + + it.each(["4.0.0", "4.1.0", "4.99.9", "^4.0.0", "~4.50.0"])( + 'returns "4.x" for versions >= 4.0.0 and < 5.0.0', + (version: string) => { + expect(getSvelteVersionBucket(version)).toBe("4.x"); + }, + ); + + it.each(["5.0.0", "5.1.0", "5.99.9", "^5.0.0", "~5.50.0"])( + 'returns "5.x" for versions >= 5.0.0 and < 6.0.0', + (version: string) => { + expect(getSvelteVersionBucket(version)).toBe("5.x"); + }, + ); + + it.each(["6.0.0", "6.1.0", "10.0.0", "^6.0.0", "~10.0.0"])( + 'returns ">5.x" for versions >= 6.0.0', + (version: string) => { + expect(getSvelteVersionBucket(version)).toBe(">5.x"); + }, + ); +}); + +describe("getSentrySvelteKitVitePluginImportPath", () => { + it.each(["11.0.0", "^11.0.0", "11.0.0-beta.2", "~11.2.0", "12.0.0"])( + "returns the /vite subpath for SDK %s", + (version) => { + expect(getSentrySvelteKitVitePluginImportPath(version)).toBe( + "@sentry/sveltekit/vite", + ); + }, + ); + + it.each(["10.74.0", "^10.0.0", "~10.73.0", "9.47.1"])( + "returns the root export for SDK %s", + (version) => { + expect(getSentrySvelteKitVitePluginImportPath(version)).toBe( + "@sentry/sveltekit", + ); + }, + ); + + it.each([undefined, "", "latest", "workspace:*"])( + "falls back to the pinned install range when the version is unknown (%s)", + (version) => { + expect(getSentrySvelteKitVitePluginImportPath(version)).toBe( + getSentrySvelteKitVitePluginImportPath(SENTRY_SVELTEKIT_SDK_RANGE), + ); + }, + ); +}); diff --git a/packages/cli/test/tsconfig.json b/packages/cli/test/tsconfig.json index 97487f6ca..5089b3704 100644 --- a/packages/cli/test/tsconfig.json +++ b/packages/cli/test/tsconfig.json @@ -4,5 +4,5 @@ "lib": ["ESNext", "DOM"] }, "include": ["**/*.ts", "**/*.tsx", "../src/lib/wizard/xcode.d.ts"], - "exclude": ["wizard-e2e/test-applications"] + "exclude": ["lib/wizard/**/fixtures/**", "wizard-e2e/test-applications"] } diff --git a/scripts/tsconfig-policy.test.mjs b/scripts/tsconfig-policy.test.mjs index dd7837143..0e6f270c4 100644 --- a/scripts/tsconfig-policy.test.mjs +++ b/scripts/tsconfig-policy.test.mjs @@ -23,6 +23,11 @@ const UNCHECKED = [ reason: "codemod input and expected-output fixtures, compared as text by `jssg test`", }, + { + pattern: /^packages\/cli\/test\/lib\/wizard\/.*\/fixtures\//, + reason: + "wizard codemod input fixtures copied from sentry-wizard, read as text by the codemod tests", + }, { pattern: /^packages\/http\/test\/package\/consumer\//, reason: