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 index dc4be67ef..5d82509a0 100644 --- a/packages/cli/src/lib/wizard/react-router/codemods/server-entry.ts +++ b/packages/cli/src/lib/wizard/react-router/codemods/server-entry.ts @@ -344,94 +344,128 @@ export function instrumentHandleError( )) ) { 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 { + } else { + const handleErrorFunction = getHandleErrorFunction( + handleErrorFunctionExport ?? handleErrorFunctionVariableDeclarationExport, + ); + const bindings = + handleErrorFunction && bindErrorAndRequest(handleErrorFunction.params); + if (!handleErrorFunction || !bindings) { debug( - "Cannot safely access handleError function body, skipping instrumentation", + "Cannot safely access handleError function body or parameters, skipping instrumentation", ); + return; } - } else if (handleErrorFunctionVariableDeclarationExport) { - // Create the Sentry captureException call as an IfStatement - const sentryCall = recast.parse(`if (!request.signal.aborted) { - Sentry.captureException(error); + + const sentryCall = recast.parse(`if (!${bindings.request}.signal.aborted) { + Sentry.captureException(${bindings.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; - } + // Capture first, so an early return or rethrow in the existing handler + // can't skip it. + handleErrorFunction.body.body.unshift(sentryCall); + } +} + +type BlockBodiedFunction = ( + | t.FunctionDeclaration + | t.FunctionExpression + | t.ArrowFunctionExpression +) & { body: t.BlockStatement }; + +/** + * The function of an exported `handleError` declaration, when it is a + * function declaration or a function/arrow expression with a block body. + */ +function getHandleErrorFunction( + exportNode: t.Program["body"][number] | undefined, +): BlockBodiedFunction | undefined { + if (exportNode?.type !== "ExportNamedDeclaration") { + return undefined; + } + const declaration = exportNode.declaration; + let fn: t.FunctionDeclaration | t.VariableDeclarator["init"] | undefined; + if (declaration?.type === "FunctionDeclaration") { + fn = declaration; + } else if (declaration?.type === "VariableDeclaration") { + const declarator = declaration.declarations[0]; + fn = + declarator?.type === "VariableDeclarator" ? declarator.init : undefined; + } + if ( + (fn?.type === "FunctionDeclaration" || + fn?.type === "FunctionExpression" || + fn?.type === "ArrowFunctionExpression") && + fn.body.type === "BlockStatement" + ) { + return fn as BlockBodiedFunction; + } + return undefined; +} - const firstDeclaration = exportDeclaration.declaration.declarations[0]; - const existingHandleErrorImplementation = - firstDeclaration?.type === "VariableDeclarator" - ? firstDeclaration.init +/** + * Make sure `handleError(error, { request })` binds the error and the + * request, adding the missing parameters, and return the expressions that + * reach them. `undefined` when an existing parameter has a shape we can't + * extend safely. + */ +function bindErrorAndRequest( + params: t.Function["params"], +): { error: string; request: string } | undefined { + const b = recast.types.builders; + const requestProperty = () => ({ + ...b.property("init", b.identifier("request"), b.identifier("request")), + shorthand: true, + }); + + const [errorParam, contextParam] = params; + if (!errorParam) { + params.push(b.identifier("error")); + } else if (errorParam.type !== "Identifier") { + return undefined; + } + const error = errorParam?.type === "Identifier" ? errorParam.name : "error"; + + if (!contextParam) { + params.push(b.objectPattern([requestProperty()])); + return { error, request: "request" }; + } + // `{ request } = {}` binds like `{ request }`. + const context = + contextParam.type === "AssignmentPattern" + ? contextParam.left + : contextParam; + if (context.type === "Identifier") { + return { error, request: `${context.name}.request` }; + } + if (context.type !== "ObjectPattern") { + return undefined; + } + const existing = context.properties.find( + (prop) => "key" in prop && safeGetIdentifierName(prop.key) === "request", + ); + if (!existing) { + // A property can't follow `...rest`, and `request` is already in it. + const rest = context.properties.find( + (prop) => prop.type === "RestElement" || prop.type === "RestProperty", + ); + if (rest) { + return "argument" in rest && rest.argument.type === "Identifier" + ? { error, request: `${rest.argument.name}.request` } : 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); - } + context.properties.push(requestProperty()); + return { error, request: "request" }; + } + if (existing.type === "Property" || existing.type === "ObjectProperty") { + // `{ request = fallback }` binds `request` too. + const value = + existing.value.type === "AssignmentPattern" + ? existing.value.left + : existing.value; + if (value.type === "Identifier") { + return { error, request: value.name }; } - - // Add the Sentry call to the function body - existingBody.body.push(sentryCall); } + return undefined; } diff --git a/packages/cli/src/lib/wizard/react-router/codemods/vite.ts b/packages/cli/src/lib/wizard/react-router/codemods/vite.ts index 3c1554148..849d0ed02 100644 --- a/packages/cli/src/lib/wizard/react-router/codemods/vite.ts +++ b/packages/cli/src/lib/wizard/react-router/codemods/vite.ts @@ -65,11 +65,14 @@ function extractFromFunctionBody( * * @param orgSlug - Sentry organization slug * @param projectSlug - Sentry project slug + * @param configEnvName - The `defineConfig` callback parameter that holds + * Vite's config env * @returns CallExpression node for the Sentry Vite plugin */ function createSentryPluginCall( orgSlug: string, projectSlug: string, + configEnvName: string, ): t.CallExpression { const b = recast.types.builders; return b.callExpression(b.identifier("sentryReactRouter"), [ @@ -84,10 +87,78 @@ function createSentryPluginCall( ), ), ]), - b.identifier("config"), + b.identifier(configEnvName), ]); } +/** + * A name for Vite's config env parameter that no identifier in the file uses + * yet, so it can't shadow or redeclare one of the project's own bindings. + */ +function getUnusedConfigEnvName(program: t.Program): string { + const used = new Set(); + recast.visit(program, { + visitIdentifier(path) { + used.add(path.node.name); + this.traverse(path); + }, + }); + const candidates = ["config", "configEnv", "viteConfigEnv"]; + for (let i = 2; ; i++) { + const name = candidates.shift() ?? `viteConfigEnv${i}`; + if (!used.has(name)) { + return name; + } + } +} + +/** + * Name of the `defineConfig` callback parameter that holds Vite's config + * env, so `sentryReactRouter` can receive it. An identifier parameter (also + * with a default) is used as is. A missing parameter is added under + * `unusedName`; a destructured one (`({ mode }) => ...`, also with a default) + * is renamed to `unusedName` and destructured again at the start of the body. + */ +function ensureConfigEnvParam( + fn: t.ArrowFunctionExpression | t.FunctionExpression, + unusedName: string, +): string { + const b = recast.types.builders; + const [firstParam] = fn.params; + if (firstParam?.type === "Identifier") { + return firstParam.name; + } + if ( + firstParam?.type === "AssignmentPattern" && + firstParam.left.type === "Identifier" + ) { + return firstParam.left.name; + } + const configEnv = b.identifier(unusedName); + if (!firstParam) { + fn.params.push(configEnv); + return unusedName; + } + + // `({ mode } = {}) =>` keeps its default on the renamed parameter. + const hasDefault = firstParam.type === "AssignmentPattern"; + fn.params[0] = hasDefault + ? b.assignmentPattern(configEnv, firstParam.right) + : configEnv; + const destructure = b.variableDeclaration("const", [ + b.variableDeclarator( + hasDefault ? firstParam.left : firstParam, + b.identifier(unusedName), + ), + ]); + if (fn.body.type === "BlockStatement") { + fn.body.body.unshift(destructure); + } else { + fn.body = b.blockStatement([destructure, b.returnStatement(fn.body)]); + } + return unusedName; +} + /** Adds @sentry/react-router to optimizeDeps.exclude to prevent 504 errors during dev. */ function addOptimizeDepsExclude(configObj: t.ObjectExpression): void { const b = recast.types.builders; @@ -160,6 +231,7 @@ export function addReactRouterPluginToViteConfig( } let configObj: t.ObjectExpression | undefined; + let configEnvName = "config"; let defineConfigCall: t.CallExpression | undefined; if ( @@ -179,8 +251,9 @@ export function addReactRouterPluginToViteConfig( if (arg.type === "ObjectExpression") { configObj = arg; // Convert to function form + configEnvName = getUnusedConfigEnvName(program); const arrowFunction = b.arrowFunctionExpression( - [b.identifier("config")], + [b.identifier(configEnvName)], configObj, ); defineConfigCall.arguments[0] = arrowFunction; @@ -190,6 +263,12 @@ export function addReactRouterPluginToViteConfig( arg.type === "FunctionExpression" ) { configObj = extractFromFunctionBody(arg.body); + if (configObj) { + configEnvName = ensureConfigEnvParam( + arg, + getUnusedConfigEnvName(program), + ); + } } } @@ -198,7 +277,11 @@ export function addReactRouterPluginToViteConfig( } const pluginsProp = findProperty(configObj, "plugins"); - const sentryPluginCall = createSentryPluginCall(orgSlug, projectSlug); + const sentryPluginCall = createSentryPluginCall( + orgSlug, + projectSlug, + configEnvName, + ); if (!pluginsProp) { configObj.properties.push( diff --git a/packages/cli/src/lib/wizard/react-router/sdk-setup.ts b/packages/cli/src/lib/wizard/react-router/sdk-setup.ts index 9ef3c991e..dc67d6634 100644 --- a/packages/cli/src/lib/wizard/react-router/sdk-setup.ts +++ b/packages/cli/src/lib/wizard/react-router/sdk-setup.ts @@ -302,28 +302,23 @@ export async function updatePackageJsonScripts(): Promise { 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))/, + // Shell semantics: an unquoted value ends at the first whitespace, so + // `NODE_OPTIONS=--a PORT=3000 node` keeps `PORT=3000` as its own variable. + const nodeOptions = /(^|\s)NODE_OPTIONS=(?:'([^']*)'|"([^"]*)"|(\S*))/.exec( + scriptCommand, ); - if (unquotedMatch) { - const existingOptions = unquotedMatch[1]; - const commandPart = unquotedMatch[2]; + if (nodeOptions) { + const existingOptions = + nodeOptions[2] ?? nodeOptions[3] ?? nodeOptions[4] ?? ""; const mergedOptions = `${existingOptions} --import ${instrumentPath}`.trim(); + // Single-quote the result, unless that would close on a `'` inside a + // double-quoted value. + const quote = mergedOptions.includes("'") ? '"' : "'"; return scriptCommand.replace( - /NODE_OPTIONS=([^\s]+(?:\s+[^\s]+)*?)(\s+(?:react-router-serve|react-router|node|npx|tsx))/, - `NODE_OPTIONS='${mergedOptions}'${commandPart}`, + nodeOptions[0], + () => + `${nodeOptions[1] ?? ""}NODE_OPTIONS=${quote}${mergedOptions}${quote}`, ); } @@ -334,16 +329,9 @@ export async function updatePackageJsonScripts(): Promise { 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); - } + // Keep the project's own start command (custom server, port, flags) and + // only add the instrumentation import to it. + packageJson.scripts["start"] = mergeNodeOptions(packageJson.scripts["start"]); // Prevent React CJS dev/prod bundle mismatch when --import loads react // before react-router-serve sets NODE_ENV diff --git a/packages/cli/src/lib/wizard/remix/codemods/handle-error.ts b/packages/cli/src/lib/wizard/remix/codemods/handle-error.ts index 8d741f2f5..825338ae9 100644 --- a/packages/cli/src/lib/wizard/remix/codemods/handle-error.ts +++ b/packages/cli/src/lib/wizard/remix/codemods/handle-error.ts @@ -75,30 +75,56 @@ export function instrumentHandleError( )) ) { 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, + } else if ( + handleErrorFunctionExport?.type === "ExportNamedDeclaration" && + handleErrorFunctionExport.declaration?.type === "FunctionDeclaration" + ) { + // Wrap the whole function, so `async`, its parameters and its body stay + // as they are. + const fn = handleErrorFunctionExport.declaration; + const b = recast.types.builders; + const functionExpression = b.functionExpression( + null, + fn.params, + fn.body, + fn.generator, ); - - // @ts-expect-error - declaration works here because the AST is proxified by magicast - handleErrorFunctionVariableDeclarationExport.declaration = implementation; + functionExpression.async = fn.async ?? false; + handleErrorFunctionExport.declaration = b.variableDeclaration("const", [ + b.variableDeclarator( + b.identifier("handleError"), + wrapWithSentry(functionExpression), + ), + ]); + } else if ( + handleErrorFunctionVariableDeclarationExport?.type === + "ExportNamedDeclaration" && + handleErrorFunctionVariableDeclarationExport.declaration?.type === + "VariableDeclaration" + ) { + const declarator = + handleErrorFunctionVariableDeclarationExport.declaration.declarations[0]; + if (declarator?.type !== "VariableDeclarator" || !declarator.init) { + return false; + } + // Any initializer works: an arrow or function expression, or a handler + // built elsewhere. + declarator.init = wrapWithSentry(declarator.init); } return true; } + +/** `Sentry.wrapHandleErrorWithSentry()` */ +function wrapWithSentry( + handler: Parameters[1][number], +): ReturnType { + const b = recast.types.builders; + return b.callExpression( + b.memberExpression( + b.identifier("Sentry"), + b.identifier("wrapHandleErrorWithSentry"), + ), + [handler], + ); +} diff --git a/packages/cli/src/lib/wizard/remix/codemods/root.ts b/packages/cli/src/lib/wizard/remix/codemods/root.ts index a132bdb35..b74d9464e 100644 --- a/packages/cli/src/lib/wizard/remix/codemods/root.ts +++ b/packages/cli/src/lib/wizard/remix/codemods/root.ts @@ -102,37 +102,10 @@ export async function instrumentRoot(rootFileName: string): Promise { 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 errorBoundaryName = findErrorBoundaryLocalName(exportsAst); + const foundErrorBoundary = errorBoundaryName !== undefined; 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", @@ -176,62 +149,27 @@ export async function instrumentRoot(rootFileName: string): Promise { 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); - }, - }); + const errorBoundaryFunction = errorBoundaryName + ? findFunction(exportsAst, errorBoundaryName) + : undefined; + if (errorBoundaryFunction) { + const usesRouteErrorHook = captureErrorInBoundary(errorBoundaryFunction); + if (!usesRouteErrorHook) { + rootRouteAst.imports.$add({ + from: "@remix-run/react", + imported: "useRouteError", + local: "useRouteError", + }); + } + } else { + clack.log.warn( + `Couldn't find the ${chalk.cyan("ErrorBoundary")} function in ${chalk.cyan( + rootFileName, + )}. Call ${chalk.cyan( + "captureRemixErrorBoundaryError(useRouteError())", + )} in it to report errors to Sentry.`, + ); + } } else if (!withSentryAlreadyUsed) { // Even if we have Sentry content but withSentry is not used, we should still wrap the app wrapAppWithSentry(rootRouteAst, rootFileName); @@ -242,3 +180,162 @@ export async function instrumentRoot(rootFileName: string): Promise { path.join(process.cwd(), "app", rootFileName), ); } + +type FunctionNode = + | t.FunctionDeclaration + | t.FunctionExpression + | t.ArrowFunctionExpression; + +/** + * Local name of the root route's `ErrorBoundary` export, for + * `export function ErrorBoundary`, `export const ErrorBoundary = ...` and + * `export { Boundary as ErrorBoundary }`. + */ +function findErrorBoundaryLocalName(program: t.Program): string | undefined { + for (const node of program.body) { + if (node.type !== "ExportNamedDeclaration") { + continue; + } + const declaration = node.declaration; + if ( + declaration?.type === "FunctionDeclaration" && + declaration.id?.name === "ErrorBoundary" + ) { + return "ErrorBoundary"; + } + if ( + declaration?.type === "VariableDeclaration" && + declaration.declarations.some( + (d) => + d.type === "VariableDeclarator" && + d.id.type === "Identifier" && + d.id.name === "ErrorBoundary", + ) + ) { + return "ErrorBoundary"; + } + if (!node.source) { + for (const specifier of node.specifiers ?? []) { + if ( + specifier.type === "ExportSpecifier" && + specifier.exported.name === "ErrorBoundary" + ) { + const local = specifier.local?.name; + return typeof local === "string" ? local : "ErrorBoundary"; + } + } + } + } + return undefined; +} + +/** The top-level function (declaration or `const` initializer) named `name`. */ +function findFunction( + program: t.Program, + name: string, +): FunctionNode | undefined { + for (const node of program.body) { + const statement = + node.type === "ExportNamedDeclaration" ? node.declaration : node; + if ( + statement?.type === "FunctionDeclaration" && + statement.id?.name === name + ) { + return statement; + } + if (statement?.type === "VariableDeclaration") { + for (const declarator of statement.declarations) { + if ( + declarator.type === "VariableDeclarator" && + declarator.id.type === "Identifier" && + declarator.id.name === name && + (declarator.init?.type === "ArrowFunctionExpression" || + declarator.init?.type === "FunctionExpression") + ) { + return declarator.init; + } + } + } + } + return undefined; +} + +/** + * Report the boundary's error to Sentry right after it is read with + * `useRouteError()`, reading it first when the boundary doesn't. Returns + * whether the boundary already called `useRouteError`. + */ +function captureErrorInBoundary(fn: FunctionNode): boolean { + const b = recast.types.builders; + if (fn.body.type !== "BlockStatement") { + fn.body = b.blockStatement([b.returnStatement(fn.body)]); + } + const statements = fn.body.body; + + const isRouteErrorRead = ( + d: t.VariableDeclaration["declarations"][number], + ): d is t.VariableDeclarator => + d.type === "VariableDeclarator" && + d.id.type === "Identifier" && + isUseRouteErrorCall(d.init); + const hookIndex = statements.findIndex( + (statement) => + statement.type === "VariableDeclaration" && + statement.declarations.some(isRouteErrorRead), + ); + const hookStatement = statements[hookIndex]; + const hookDeclarator = + hookStatement?.type === "VariableDeclaration" + ? hookStatement.declarations.find(isRouteErrorRead) + : undefined; + const errorName = + hookDeclarator?.id.type === "Identifier" + ? hookDeclarator.id.name + : undefined; + + const capture = (name: string) => + b.expressionStatement( + b.callExpression(b.identifier("captureRemixErrorBoundaryError"), [ + b.identifier(name), + ]), + ); + + if (errorName) { + statements.splice(hookIndex + 1, 0, capture(errorName)); + return true; + } + statements.unshift( + b.variableDeclaration("const", [ + b.variableDeclarator( + b.identifier("error"), + b.callExpression(b.identifier("useRouteError"), []), + ), + ]), + capture("error"), + ); + return false; +} + +/** + * `useRouteError()`, also behind TypeScript wrappers such as + * `useRouteError() as Error` or `useRouteError()!`. + */ +function isUseRouteErrorCall(node: unknown): boolean { + let expression = node as { type?: string; expression?: unknown } | null; + while ( + expression && + (expression.type === "TSAsExpression" || + expression.type === "TSSatisfiesExpression" || + expression.type === "TSNonNullExpression" || + expression.type === "TSTypeAssertion" || + expression.type === "ParenthesizedExpression") + ) { + expression = expression.expression as typeof expression; + } + const call = expression as t.CallExpression | null; + return ( + call?.type === "CallExpression" && + call.callee.type === "Identifier" && + call.callee.name === "useRouteError" + ); +} diff --git a/packages/cli/src/lib/wizard/remix/sdk-example.ts b/packages/cli/src/lib/wizard/remix/sdk-example.ts index 6ebaf06b5..f6c32ee06 100644 --- a/packages/cli/src/lib/wizard/remix/sdk-example.ts +++ b/packages/cli/src/lib/wizard/remix/sdk-example.ts @@ -32,15 +32,49 @@ export async function createExamplePage(options: { exampleRoutePath, )}). Skipping creation of example route.`, ); - return; + } else { + await promises.writeFile( + exampleRoutePath, + getSentryExamplePageContents(options), + ); + clack.log.info(`Created sentry example page at ${exampleRoutePath}.`); } - await promises.writeFile( - exampleRoutePath, - getSentryExamplePageContents(options), - ); + // The page's button fetches this route to raise a backend error. + const exampleApiPath = `${routesPath}/api.sentry-example-api.${ + options.isTS ? "ts" : "js" + }`; + if (!existsSync(exampleApiPath)) { + await promises.writeFile( + exampleApiPath, + getSentryExampleApiContents(options), + ); + clack.log.info(`Created sentry example API route at ${exampleApiPath}.`); + } +} + +export function getSentryExampleApiContents(options: { isTS?: boolean }) { + return `import * as Sentry from "@sentry/remix"; - clack.log.info(`Created sentry example page at ${exampleRoutePath}.`); +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 of the example page."); +} +`; } export function getSentryExamplePageContents(options: { diff --git a/packages/cli/src/lib/wizard/remix/sdk-setup.ts b/packages/cli/src/lib/wizard/remix/sdk-setup.ts index b17bda52e..6af23be13 100644 --- a/packages/cli/src/lib/wizard/remix/sdk-setup.ts +++ b/packages/cli/src/lib/wizard/remix/sdk-setup.ts @@ -277,13 +277,35 @@ Skipping adding instrumentation functionality to ${chalk.cyan( return true; } - originalExpressServerMod.$code = `import './${instrumentationFile}';\n${originalExpressServerMod.$code}`; + const importPath = getInstrumentationImportPath( + expressServerPath, + instrumentationFile, + ); + originalExpressServerMod.$code = `import '${importPath}';\n${originalExpressServerMod.$code}`; writeFileSync(expressServerPath, originalExpressServerMod.$code); return true; } +/** + * Import specifier for the instrumentation file (written to the project root) + * from the server file, which can live in `server/` or `app/server/`. + */ +export function getInstrumentationImportPath( + serverFilePath: string, + instrumentationFile: string, +): string { + const relativePath = path + .relative( + path.dirname(path.resolve(serverFilePath)), + path.resolve(instrumentationFile), + ) + .split(path.sep) + .join("/"); + return relativePath.startsWith(".") ? relativePath : `./${relativePath}`; +} + export function isRemixV2(packageJson: PackageDotJson): boolean { const remixVersion = getPackageVersion("@remix-run/react", packageJson); if (!remixVersion) { diff --git a/packages/cli/src/lib/wizard/sveltekit/templates.ts b/packages/cli/src/lib/wizard/sveltekit/templates.ts index 936a9b6aa..eca73839e 100644 --- a/packages/cli/src/lib/wizard/sveltekit/templates.ts +++ b/packages/cli/src/lib/wizard/sveltekit/templates.ts @@ -156,7 +156,7 @@ Feel free to delete this file and the entire sentry route. import { onMount } from 'svelte'; let hasSentError = ${options.isUsingSvelte5 ? "$state(false)" : "false"}; - let isConnected = true; + let isConnected = ${options.isUsingSvelte5 ? "$state(true)" : "true"}; onMount(async () => { const result = await Sentry.diagnoseSdkConnectivity(); 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 index 72b6afb78..e964ec423 100644 --- 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 @@ -2,10 +2,12 @@ import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; import { existsSync, mkdirSync, + mkdtempSync, readFileSync, rmSync, writeFileSync, } from "node:fs"; +import { tmpdir } from "node:os"; import path from "node:path"; import recast from "recast"; import { @@ -372,6 +374,86 @@ export const handleError = (error: unknown) => { }); }); +describe("instrumentHandleError capture placement and bindings", () => { + let tmpDir: string; + + beforeEach(() => { + tmpDir = mkdtempSync(path.join(tmpdir(), "handle-error-bindings-")); + }); + + afterEach(() => { + rmSync(tmpDir, { recursive: true, force: true }); + }); + + async function instrument(content: string): Promise { + const file = path.join(tmpDir, "entry.server.tsx"); + writeFileSync(file, content); + const mod = await loadFile(file); + instrumentHandleError(mod); + return generateCode(mod.$ast).code; + } + + it("captures before an early return in a variable-declared handler", async () => { + const code = await instrument(` +export const handleError = (error: unknown, { request }: { request: Request }) => { + if (request.method === "HEAD") { + return; + } + console.error(error); +}; +`); + expect(code.indexOf("Sentry.captureException(error)")).toBeLessThan( + code.indexOf("return;"), + ); + }); + + it("adds a request binding to an error-only function declaration", async () => { + const code = await instrument(` +export function handleError(error: unknown) { + console.error(error); +} +`); + expect(code).toMatch( + /function handleError\(\s*error: unknown,\s*\{\s*request\s*\}\s*\)/, + ); + expect(code).toContain("if (!request.signal.aborted)"); + }); + + it("uses the existing parameter names", async () => { + const code = await instrument(` +export function handleError(err: unknown, args: { request: Request }) { + console.error(err); +} +`); + expect(code).toContain("if (!args.request.signal.aborted)"); + expect(code).toContain("Sentry.captureException(err)"); + }); + + it.each([ + ["a defaulted context", "error: any, { request } = {} as any"], + ["a defaulted request", "error: any, { request = fallback }: any"], + ])("captures with %s", async (_, params) => { + const code = await instrument(` +export function handleError(${params}) { + console.error(error); +} +`); + expect(code).toContain("if (!request.signal.aborted)"); + expect(code).toContain("Sentry.captureException(error)"); + }); + + it("reads request from a rest binding instead of adding a property after it", async () => { + const code = await instrument(` +export function handleError(error: unknown, { params, ...rest }: any) { + console.error(error); +} +`); + expect(code).toContain("{ params, ...rest }"); + expect(code).toContain("if (!rest.request.signal.aborted)"); + expect(code).not.toMatch(/\.\.\.rest,\s*request/); + }); +}); + describe("instrumentHandleError AST manipulation edge cases", () => { let tmpDir: string; @@ -436,7 +518,11 @@ export const handleError = (error: unknown, context: any) => { const modifiedCode = generateCode(mod.$ast).code; expect(modifiedCode).toContain("Sentry.captureException(error)"); - expect(modifiedCode).toContain("if (!request.signal.aborted)"); + expect(modifiedCode).toContain("if (!context.request.signal.aborted)"); + // Capture runs before the handler's own `return`. + expect(modifiedCode.indexOf("captureException")).toBeLessThan( + modifiedCode.indexOf("return new Response"), + ); }); it("should demonstrate that the AST bug is now fixed - no longer throws TypeError", async () => { 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 index 12232b891..b118de9e5 100644 --- a/packages/cli/test/lib/wizard/react-router/codemods/vite.test.ts +++ b/packages/cli/test/lib/wizard/react-router/codemods/vite.test.ts @@ -152,6 +152,63 @@ export default defineConfig(config => ({ expect(writtenConfig).toMatch(/exclude.*@sentry\/react-router/s); }); + it.each([ + [ + "a differently named parameter", + "defineConfig((env) => ({ plugins: [] }))", + /sentryReactRouter\(\{[\s\S]*\}, env\)/, + ], + [ + "a destructured parameter", + "defineConfig(({ mode }) => ({ plugins: [], define: { mode } }))", + /\(?config\)? => \{\s*const \{\s*mode\s*\} = config;[\s\S]*\}, config\)/, + ], + [ + "no parameter", + "defineConfig(function () { return { plugins: [] }; })", + /function\s*\(config\)[\s\S]*\}, config\)/, + ], + [ + "a destructured parameter with a default", + "defineConfig(({ mode } = {}) => ({ plugins: [], define: { mode } }))", + /\(config = \{\}\) => \{\s*const \{\s*mode\s*\} = config;[\s\S]*\}, config\)/, + ], + [ + "an identifier parameter with a default", + "defineConfig((env = {}) => ({ plugins: [] }))", + /\}, env\)/, + ], + [ + "a file that already binds config", + "defineConfig(({ mode }) => { const config = { mode }; return { plugins: [], define: config }; })", + /\(?configEnv\)? => \{\s*const \{\s*mode\s*\} = configEnv;[\s\S]*\}, configEnv\)/, + ], + [ + "an object config next to a module-level config", + "defineConfig({ plugins: [] }); const config = 1", + /\(?configEnv\)? => [\s\S]*\}, configEnv\)/, + ], + ])( + "passes the config env to sentryReactRouter for %s", + async (_name, defineConfig, expected) => { + const writtenFiles: Record = {}; + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue( + `import { defineConfig } from 'vite';\n\nexport default ${defineConfig};`, + ); + vi.mocked(promises.writeFile).mockImplementation( + (filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }, + ); + + await instrumentViteConfig("my-org", "my-project"); + + expect(Object.values(writtenFiles)[0]).toMatch(expected); + }, + ); + it("should add @sentry/react-router to existing optimizeDeps.exclude", async () => { const configWithExistingExclude = `import { defineConfig } from 'vite'; 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 index 80b4be7ab..f7fb08fec 100644 --- a/packages/cli/test/lib/wizard/react-router/sdk-setup.test.ts +++ b/packages/cli/test/lib/wizard/react-router/sdk-setup.test.ts @@ -599,7 +599,7 @@ describe("updatePackageJsonScripts", () => { const mockPackageJson: { scripts: Record } = { scripts: { dev: "react-router dev", - start: "react-router serve", + start: "react-router-serve ./build/server/index.js", build: "react-router build", }, }; @@ -640,7 +640,7 @@ describe("updatePackageJsonScripts", () => { it("should handle package.json with only start script", async () => { const mockPackageJson: { scripts: Record } = { scripts: { - start: "react-router serve", + start: "react-router-serve ./build/server/index.js", }, }; @@ -683,8 +683,8 @@ describe("updatePackageJsonScripts", () => { 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", + dev: "NODE_OPTIONS=--enable-source-maps react-router dev", + start: "react-router-serve ./build/server/index.js", }, }; @@ -703,7 +703,7 @@ describe("updatePackageJsonScripts", () => { // 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", + "NODE_OPTIONS='--enable-source-maps --import ./instrument.server.mjs' react-router dev", ); }); @@ -711,7 +711,7 @@ describe("updatePackageJsonScripts", () => { const mockPackageJson: { scripts: Record } = { scripts: { start: - "NODE_OPTIONS=--require ./dotenv-config.js react-router-serve ./build/server/index.js", + "NODE_OPTIONS=--require=./dotenv-config.js react-router-serve ./build/server/index.js", }, }; @@ -730,7 +730,7 @@ describe("updatePackageJsonScripts", () => { // 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", + "NODE_ENV=production NODE_OPTIONS='--require=./dotenv-config.js --import ./instrument.server.mjs' react-router-serve ./build/server/index.js", ); }); @@ -766,6 +766,69 @@ describe("updatePackageJsonScripts", () => { }); }); +describe("updatePackageJsonScripts keeps the project's commands", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + async function updatedScripts( + scripts: Record, + ): Promise> { + getPackageDotJsonMock.mockResolvedValue({ scripts }); + const fsPromises = await import("node:fs"); + const writeFileMock = vi + .spyOn(fsPromises.promises, "writeFile") + .mockResolvedValue(); + await updatePackageJsonScripts(); + return ( + JSON.parse(writeFileMock.mock.calls[0]?.[1] as string) as { + scripts: Record; + } + ).scripts; + } + + it.each([ + [ + "react-router-serve ./build/server/index.js --port 3000", + "NODE_ENV=production NODE_OPTIONS='--import ./instrument.server.mjs' react-router-serve ./build/server/index.js --port 3000", + ], + [ + "node ./server.js", + "NODE_ENV=production NODE_OPTIONS='--import ./instrument.server.mjs' node ./server.js", + ], + ])("prepends the import to the start script %s", async (start, expected) => { + expect((await updatedScripts({ start }))["start"]).toBe(expected); + }); + + it("keeps a double-quoted NODE_OPTIONS with single quotes double-quoted", async () => { + const scripts = await updatedScripts({ + start: `NODE_OPTIONS="--title='my app'" node ./server.js`, + }); + expect(scripts["start"]).toBe( + `NODE_ENV=production NODE_OPTIONS="--title='my app' --import ./instrument.server.mjs" node ./server.js`, + ); + }); + + it("merges into an unquoted NODE_OPTIONS before any command", async () => { + const scripts = await updatedScripts({ + start: "NODE_OPTIONS=--max-old-space-size=4096 pm2 start ./server.js", + }); + expect(scripts["start"]).toBe( + "NODE_ENV=production NODE_OPTIONS='--max-old-space-size=4096 --import ./instrument.server.mjs' pm2 start ./server.js", + ); + }); + + it("keeps a sibling environment variable after an unquoted NODE_OPTIONS", async () => { + const scripts = await updatedScripts({ + start: + "NODE_OPTIONS=--max-old-space-size=4096 PORT=3000 node ./server.js", + }); + expect(scripts["start"]).toBe( + "NODE_ENV=production NODE_OPTIONS='--max-old-space-size=4096 --import ./instrument.server.mjs' PORT=3000 node ./server.js", + ); + }); +}); + describe("getEntryFilename", () => { beforeEach(() => { vi.clearAllMocks(); diff --git a/packages/cli/test/lib/wizard/remix/handle-error.test.ts b/packages/cli/test/lib/wizard/remix/handle-error.test.ts new file mode 100644 index 000000000..7f6d2c840 --- /dev/null +++ b/packages/cli/test/lib/wizard/remix/handle-error.test.ts @@ -0,0 +1,58 @@ +import { parseModule } from "magicast"; +import { describe, expect, it, vi } from "vitest"; +import { instrumentHandleError } from "../../../../src/lib/wizard/remix/codemods/handle-error.js"; + +vi.mock("@clack/prompts", () => ({ + log: { warn: vi.fn(), info: vi.fn(), success: vi.fn() }, +})); + +function instrument(source: string): { changed: boolean; code: string } { + const mod = parseModule(source); + const changed = instrumentHandleError(mod, "entry.server.tsx"); + return { changed, code: mod.generate().code }; +} + +describe("instrumentHandleError (Remix)", () => { + it("wraps an async function declaration and keeps its parameters", () => { + const { changed, code } = instrument(` +export async function handleError(error, args) { + await log(args.request, error); +} +`); + + expect(changed).toBe(true); + expect(code).toMatch( + /export const handleError = Sentry\.wrapHandleErrorWithSentry\(async function\s*\(error, args\) \{\s*await log\(args\.request, error\);\s*\}\);/, + ); + }); + + it("wraps an arrow function with an expression body", () => { + const { changed, code } = instrument(` +export const handleError = (error) => console.error(error); +`); + + expect(changed).toBe(true); + expect(code).toContain( + "export const handleError = Sentry.wrapHandleErrorWithSentry((error) => console.error(error));", + ); + }); + + it("wraps a handler that is built elsewhere", () => { + const { code } = instrument(` +export const handleError = createHandler(); +`); + + expect(code).toContain( + "export const handleError = Sentry.wrapHandleErrorWithSentry(createHandler());", + ); + }); + + it("leaves an already wrapped handler alone", () => { + const { changed } = instrument(` +import * as Sentry from "@sentry/remix"; +export const handleError = Sentry.wrapHandleErrorWithSentry((error) => {}); +`); + + expect(changed).toBe(false); + }); +}); diff --git a/packages/cli/test/lib/wizard/remix/root.test.ts b/packages/cli/test/lib/wizard/remix/root.test.ts index 4f37e7bb4..1b70da3a3 100644 --- a/packages/cli/test/lib/wizard/remix/root.test.ts +++ b/packages/cli/test/lib/wizard/remix/root.test.ts @@ -9,6 +9,7 @@ import { rmdirSync, statSync, unlinkSync, + writeFileSync, } from "node:fs"; import path from "node:path"; import { @@ -307,5 +308,82 @@ describe("instrumentRoot", () => { 'import { captureRemixErrorBoundaryError, withSentry } from "@sentry/remix";', ); expect(modifiedContent).toContain("withSentry(App)"); + // The existing boundary is instrumented, not duplicated. + expect(modifiedContent.match(/const ErrorBoundary/g)).toHaveLength(1); + expect(modifiedContent).toMatch( + /const ErrorBoundary = \(\) => \{\s*const error = useRouteError\(\);\s*captureRemixErrorBoundaryError\(error\);/, + ); }); + + async function instrumentRootSource(source: string): Promise { + const appDir = path.join(tmpDir, "app"); + mkdirSync(appDir, { recursive: true }); + writeFileSync(path.join(appDir, "root.tsx"), source); + vi.spyOn(process, "cwd").mockReturnValue(tmpDir); + await instrumentRoot("root.tsx"); + return readFileSync(path.join(appDir, "root.tsx"), "utf8"); + } + + it("instruments an exported const ErrorBoundary", async () => { + const result = + await instrumentRootSource(`import { Outlet } from '@remix-run/react'; + +export const ErrorBoundary = () =>
Error occurred
; + +export default function App() { + return ; +} +`); + + expect(result).toMatch( + /export const ErrorBoundary = \(\) => \{\s*const error = useRouteError\(\);\s*captureRemixErrorBoundaryError\(error\);\s*return
Error occurred<\/div>;/, + ); + expect(result).toMatch( + /import \{[^}]*useRouteError[^}]*\} from ["']@remix-run\/react["']/, + ); + }); + + it("captures the error under the name the boundary already uses", async () => { + const result = + await instrumentRootSource(`import { Outlet, useRouteError } from '@remix-run/react'; + +export function ErrorBoundary() { + const routeError = useRouteError(); + if (!routeError) { + return null; + } + return
Error occurred
; +} + +export default function App() { + return ; +} +`); + + expect(result).toMatch( + /const routeError = useRouteError\(\);\s*captureRemixErrorBoundaryError\(routeError\);/, + ); + expect(result).not.toContain("captureRemixErrorBoundaryError(error)"); + }); + + it.each([["useRouteError() as Error"], ["useRouteError()!"]])( + "reuses a typed read: %s", + async (read) => { + const result = + await instrumentRootSource(`import { Outlet, useRouteError } from '@remix-run/react'; + +export function ErrorBoundary() { + const error = ${read}; + return
{String(error)}
; +} + +export default function App() { + return ; +} +`); + + expect(result.match(/const error =/g)).toHaveLength(1); + expect(result).toContain("captureRemixErrorBoundaryError(error);"); + }, + ); }); diff --git a/packages/cli/test/lib/wizard/remix/sdk-example.test.ts b/packages/cli/test/lib/wizard/remix/sdk-example.test.ts new file mode 100644 index 000000000..83fd8204a --- /dev/null +++ b/packages/cli/test/lib/wizard/remix/sdk-example.test.ts @@ -0,0 +1,85 @@ +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("@clack/prompts", () => ({ + log: { info: vi.fn(), warn: vi.fn(), success: vi.fn() }, +})); + +import { createExamplePage } from "../../../../src/lib/wizard/remix/sdk-example.js"; + +describe("createExamplePage (Remix)", () => { + let tmpDir: string; + let originalCwd: string; + + beforeEach(() => { + originalCwd = process.cwd(); + tmpDir = mkdtempSync(path.join(tmpdir(), "remix-example-test-")); + process.chdir(tmpDir); + }); + + afterEach(() => { + process.chdir(originalCwd); + rmSync(tmpDir, { recursive: true, force: true }); + }); + + it.each([ + [true, "ts"], + [false, "js"], + ])( + "creates the API route the example page fetches (isTS: %s)", + async (isTS, ext) => { + await createExamplePage({ + selfHosted: false, + orgSlug: "org", + projectId: "1", + url: "https://sentry.io/", + isTS, + }); + + const page = readFileSync( + path.join(tmpDir, `app/routes/sentry-example-page.${ext}x`), + "utf-8", + ); + expect(page).toContain('fetch("/api/sentry-example-api")'); + + // Remix flat routes map api.sentry-example-api to /api/sentry-example-api. + const apiRoute = path.join( + tmpDir, + `app/routes/api.sentry-example-api.${ext}`, + ); + expect(existsSync(apiRoute)).toBe(true); + const api = readFileSync(apiRoute, "utf-8"); + expect(api).toContain('import * as Sentry from "@sentry/remix";'); + expect(api).toContain("export async function loader()"); + expect(api).toContain("throw new SentryExampleBackendError("); + }, + ); + + it("adds the API route when the example page already exists", async () => { + mkdirSync(path.join(tmpDir, "app/routes"), { recursive: true }); + const pagePath = path.join(tmpDir, "app/routes/sentry-example-page.tsx"); + writeFileSync(pagePath, "// user's page"); + + await createExamplePage({ + selfHosted: false, + orgSlug: "org", + projectId: "1", + url: "https://sentry.io/", + isTS: true, + }); + + expect(readFileSync(pagePath, "utf-8")).toBe("// user's page"); + expect( + existsSync(path.join(tmpDir, "app/routes/api.sentry-example-api.ts")), + ).toBe(true); + }); +}); diff --git a/packages/cli/test/lib/wizard/remix/server-instrumentation.test.ts b/packages/cli/test/lib/wizard/remix/server-instrumentation.test.ts index 2a5d2effa..be0fbbd18 100644 --- a/packages/cli/test/lib/wizard/remix/server-instrumentation.test.ts +++ b/packages/cli/test/lib/wizard/remix/server-instrumentation.test.ts @@ -1,5 +1,8 @@ import { describe, expect, it } from "vitest"; -import { generateServerInstrumentationFile } from "../../../../src/lib/wizard/remix/sdk-setup.js"; +import { + generateServerInstrumentationFile, + getInstrumentationImportPath, +} from "../../../../src/lib/wizard/remix/sdk-setup.js"; describe("generateServerInstrumentationFile", () => { it("should generate server instrumentation file", () => { @@ -77,3 +80,16 @@ describe("generateServerInstrumentationFile", () => { `); }); }); + +describe("getInstrumentationImportPath", () => { + it.each([ + ["server.ts", "./instrumentation.server.mjs"], + ["server/index.ts", "../instrumentation.server.mjs"], + ["app/server.ts", "../instrumentation.server.mjs"], + ["app/server/index.ts", "../../instrumentation.server.mjs"], + ])("points %s at the root instrumentation file", (serverFile, expected) => { + expect( + getInstrumentationImportPath(serverFile, "instrumentation.server.mjs"), + ).toBe(expected); + }); +}); diff --git a/packages/cli/test/lib/wizard/sveltekit/templates.test.ts b/packages/cli/test/lib/wizard/sveltekit/templates.test.ts index 94d41f69e..1b6fd4714 100644 --- a/packages/cli/test/lib/wizard/sveltekit/templates.test.ts +++ b/packages/cli/test/lib/wizard/sveltekit/templates.test.ts @@ -730,7 +730,7 @@ describe("getSentryExampleSveltePage", () => { import { onMount } from 'svelte'; let hasSentError = $state(false); - let isConnected = true; + let isConnected = $state(true); onMount(async () => { const result = await Sentry.diagnoseSdkConnectivity();