Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
194 changes: 114 additions & 80 deletions packages/cli/src/lib/wizard/react-router/codemods/server-entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}
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" };
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}
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;
}
89 changes: 86 additions & 3 deletions packages/cli/src/lib/wizard/react-router/codemods/vite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"), [
Expand All @@ -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<string>();
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;
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

/** Adds @sentry/react-router to optimizeDeps.exclude to prevent 504 errors during dev. */
function addOptimizeDepsExclude(configObj: t.ObjectExpression): void {
const b = recast.types.builders;
Expand Down Expand Up @@ -160,6 +231,7 @@ export function addReactRouterPluginToViteConfig(
}

let configObj: t.ObjectExpression | undefined;
let configEnvName = "config";
let defineConfigCall: t.CallExpression | undefined;

if (
Expand All @@ -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;
Expand All @@ -190,6 +263,12 @@ export function addReactRouterPluginToViteConfig(
arg.type === "FunctionExpression"
) {
configObj = extractFromFunctionBody(arg.body);
if (configObj) {
configEnvName = ensureConfigEnvParam(
arg,
getUnusedConfigEnvName(program),
);
}
}
}

Expand All @@ -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(
Expand Down
Loading
Loading