diff --git a/.oxlintrc.json b/.oxlintrc.json index ff2085d06..4304d7920 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -69,6 +69,7 @@ "typescript/no-useless-default-assignment": "error", "jsx-a11y/interactive-supports-focus": "off", "unicorn/prefer-spread": "error", + "unicorn/no-array-for-each": "error", "typescript/no-misused-promises": "error", "typescript/switch-exhaustiveness-check": [ "error", diff --git a/apps/games-api/src/leaderboard.test.ts b/apps/games-api/src/leaderboard.test.ts index 09b62a983..cfd655cab 100644 --- a/apps/games-api/src/leaderboard.test.ts +++ b/apps/games-api/src/leaderboard.test.ts @@ -179,7 +179,9 @@ describe("games leaderboard route", () => { "kk", "ll", ]; - names.forEach((n, i) => rows.push([`${n}-${n}-100${i % 10}`, 300 - i])); + for (const [i, n] of names.entries()) { + rows.push([`${n}-${n}-100${i % 10}`, 300 - i]); + } fetchMock.mockResolvedValue(jsonResponse(upstreamBody(rows))); const res = await app.request(PATH, REQ, makeEnv()); diff --git a/apps/local/src/lib/profile-session.ts b/apps/local/src/lib/profile-session.ts index f29d4ae53..2099a05df 100644 --- a/apps/local/src/lib/profile-session.ts +++ b/apps/local/src/lib/profile-session.ts @@ -128,8 +128,8 @@ export function mergeProfileChunks( const frameMap = new Map(), stackMap = new Map(); if (Array.isArray(profile["frames"])) - profile["frames"].forEach((frame, index) => { - if (!Object.keys(record(frame)).length) return; + for (const [index, frame] of profile["frames"].entries()) { + if (!Object.keys(record(frame)).length) continue; const key = profileValueKey(frame); let id = frameIds.get(key); if (id === undefined) { @@ -138,15 +138,15 @@ export function mergeProfileChunks( frameIds.set(key, id); } frameMap.set(index, id); - }); + } if (Array.isArray(profile["stacks"])) - profile["stacks"].forEach((stack, index) => { - if (!Array.isArray(stack)) return; + stacks: for (const [index, stack] of profile["stacks"].entries()) { + if (!Array.isArray(stack)) continue; const mapped: number[] = []; for (const frame of stack) { const id = typeof frame === "number" ? frameMap.get(frame) : undefined; - if (id === undefined) return; // Broken indexes cannot silently describe another frame. + if (id === undefined) continue stacks; // Broken indexes cannot silently describe another frame. mapped.push(id); } const key = JSON.stringify(mapped); @@ -157,7 +157,7 @@ export function mergeProfileChunks( stackIds.set(key, id); } stackMap.set(index, id); - }); + } const chunkThreads = new Map[]>(); if (Array.isArray(profile["samples"])) for (const value of profile["samples"]) { diff --git a/packages/cli/package.json b/packages/cli/package.json index ebda84630..0e1e679f2 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -120,6 +120,7 @@ "@types/yauzl": "3.4.0", "@typescript/typescript6": "catalog:", "@vitest/coverage-v8": "catalog:", + "ast-types": "^0.16.3", "binpatch": "^0.4.2", "chalk": "^5.6.2", "cli-highlight": "^2.1.11", @@ -141,6 +142,7 @@ "pngjs": "^7.0.0", "pretty-ms": "^9.3.0", "qrcode-terminal": "^0.12.0", + "recast": "^0.23.21", "semver": "^7.8.5", "shell-quote": "^1.11.0", "string-width": "^8.2.1", diff --git a/packages/cli/src/commands/api.ts b/packages/cli/src/commands/api.ts index 3d2ff084d..e6f7e0c03 100644 --- a/packages/cli/src/commands/api.ts +++ b/packages/cli/src/commands/api.ts @@ -1487,9 +1487,9 @@ function logResponse(response: { log.debug( `< HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ""}`, ); - response.headers.forEach((value, key) => { + for (const [key, value] of response.headers) { log.debug(`< ${key}: ${value}`); - }); + } log.debug("<"); } diff --git a/packages/cli/src/lib/db/completion-cache.ts b/packages/cli/src/lib/db/completion-cache.ts index 3cd00d3cb..823608702 100644 --- a/packages/cli/src/lib/db/completion-cache.ts +++ b/packages/cli/src/lib/db/completion-cache.ts @@ -114,7 +114,7 @@ export function cacheCompletionEntities( ) .get(kind, orgSlug) as { latest: number | null } | undefined; const now = Math.max(Date.now(), (latest?.latest ?? 0) + valid.length); - valid.forEach((entity, index) => { + for (const [index, entity] of valid.entries()) { runUpsert( db, "completion_cache", @@ -127,7 +127,7 @@ export function cacheCompletionEntities( }, ["kind", "org_slug", "value"], ); - }); + } db.query( `DELETE FROM completion_cache WHERE kind = ? AND org_slug = ? AND rowid NOT IN ( diff --git a/packages/cli/src/lib/dsn/errors.ts b/packages/cli/src/lib/dsn/errors.ts index 9ad83c3ce..cccef4c34 100644 --- a/packages/cli/src/lib/dsn/errors.ts +++ b/packages/cli/src/lib/dsn/errors.ts @@ -22,14 +22,14 @@ import type { DsnDetectionResult } from "./types.js"; export function formatConflictError(result: DsnDetectionResult): string { const lines = ["Error: Multiple Sentry DSNs detected in this project.\n"]; - result.all.forEach((dsn, i) => { + for (const [i, dsn] of result.all.entries()) { lines.push(` DSN ${i + 1}: ${dsn.raw}`); lines.push(` Source: ${getDsnSourceDescription(dsn)}`); if (dsn.projectId) { lines.push(` Project ID: ${dsn.projectId}`); } lines.push(""); - }); + } lines.push("To resolve, specify which project to use:"); lines.push(` ${sentry` /`}`); diff --git a/packages/cli/src/lib/dsn/fs-utils.ts b/packages/cli/src/lib/dsn/fs-utils.ts index 9c954d068..1c28aebff 100644 --- a/packages/cli/src/lib/dsn/fs-utils.ts +++ b/packages/cli/src/lib/dsn/fs-utils.ts @@ -113,3 +113,25 @@ export async function isRegularFile( return false; } } + +/** + * Find the first of `basePath` + each extension that is a regular file, for + * config files whose extension isn't known yet (`next.config` → + * `next.config.mjs`). + * + * @param basePath - Path without the extension + * @param extensions - Extensions to try, in order, each with its leading dot + * @returns The first matching path, or undefined when none is a regular file + */ +export async function findFile( + basePath: string, + extensions: readonly string[] = [".js", ".ts", ".mjs", ".cjs"], +): Promise { + for (const extension of extensions) { + const candidate = `${basePath}${extension}`; + if (await isRegularFile(candidate, "findFile")) { + return candidate; + } + } + return undefined; +} diff --git a/packages/cli/src/lib/formatters/alerts.ts b/packages/cli/src/lib/formatters/alerts.ts index ecee15453..24e017135 100644 --- a/packages/cli/src/lib/formatters/alerts.ts +++ b/packages/cli/src/lib/formatters/alerts.ts @@ -81,9 +81,9 @@ function conditionRows(value: unknown, detector: boolean): Row[] { const rows: Row[] = [["Logic", valueText(group["logicType"])]]; const conditions = group["conditions"]; if (Array.isArray(conditions) && conditions.length > 0) { - conditions.forEach((condition, index) => { + for (const [index, condition] of conditions.entries()) { rows.push([`Condition ${index + 1}`, conditionText(condition, detector)]); - }); + } } else { rows.push([ "Conditions", @@ -150,11 +150,11 @@ function workflowSections(workflow: GetOrganizationWorkflowResponse): string[] { ...workflowGroupSections(workflow.triggers, "Triggers"), ]; if (workflow.actionFilters?.length) { - workflow.actionFilters.forEach((group, index) => { + for (const [index, group] of workflow.actionFilters.entries()) { sections.push( ...workflowGroupSections(group, `Action filter ${index + 1}`), ); - }); + } } else { sections.push(table([["Action filters", "none"]])); } diff --git a/packages/cli/src/lib/formatters/human.ts b/packages/cli/src/lib/formatters/human.ts index 2ee356406..e34818d54 100644 --- a/packages/cli/src/lib/formatters/human.ts +++ b/packages/cli/src/lib/formatters/human.ts @@ -1286,7 +1286,7 @@ function formatSpanSimple(span: TraceSpan, opts: FormatSpanOptions): void { if (currentDepth < maxDepth) { const children = span.children ?? []; const childCount = children.length; - children.forEach((child, i) => { + for (const [i, child] of children.entries()) { formatSpanSimple(child, { lines, prefix: childPrefix, @@ -1294,7 +1294,7 @@ function formatSpanSimple(span: TraceSpan, opts: FormatSpanOptions): void { currentDepth: currentDepth + 1, maxDepth, }); - }); + } } } @@ -1367,7 +1367,7 @@ export function formatSimpleSpanTree( const displaySpans = truncated ? spans.slice(0, MAX_ROOT_SPANS) : spans; const displayCount = displaySpans.length; - displaySpans.forEach((span, i) => { + for (const [i, span] of displaySpans.entries()) { formatSpanSimple(span, { lines, prefix: "", @@ -1375,7 +1375,7 @@ export function formatSimpleSpanTree( currentDepth: 1, maxDepth: effectiveMaxDepth, }); - }); + } if (truncated) { const remaining = totalRootSpans - MAX_ROOT_SPANS; diff --git a/packages/cli/src/lib/games/snake-game.ts b/packages/cli/src/lib/games/snake-game.ts index b4b3f4c05..5be8d6628 100644 --- a/packages/cli/src/lib/games/snake-game.ts +++ b/packages/cli/src/lib/games/snake-game.ts @@ -313,9 +313,9 @@ export function renderSnake( if (state.food) { cells[state.food.y * state.width + state.food.x] = FOOD; } - state.body.forEach((part, index) => { + for (const [index, part] of state.body.entries()) { cells[part.y * state.width + part.x] = index === 0 ? HEAD : BODY; - }); + } const lines: string[] = []; for (let row = 0; row < snakeTerminalRows(state.height); row++) { diff --git a/packages/cli/src/lib/select-ui/picker.ts b/packages/cli/src/lib/select-ui/picker.ts index 3e5a72979..7060a1a27 100644 --- a/packages/cli/src/lib/select-ui/picker.ts +++ b/packages/cli/src/lib/select-ui/picker.ts @@ -450,14 +450,14 @@ function renderPicker( const accent = chalk.hex(ACCENT); const lines = [""]; - titleLines.forEach((line, index) => { + for (const [index, line] of titleLines.entries()) { const icon = padIcon(index === 0 ? ICONS.diamondOpen : ""); const counter = index === 0 && isWindowed ? chalk.hex(MUTED_DIM)(` (${highlighted + 1}/${filtered.length})`) : ""; lines.push(`${accent.bold(icon)}${chalk.bold(line)}${counter}`); - }); + } lines.push(""); const optionLines = diff --git a/packages/cli/src/lib/sentry-urls.ts b/packages/cli/src/lib/sentry-urls.ts index 3e8dbd507..902e2fcdc 100644 --- a/packages/cli/src/lib/sentry-urls.ts +++ b/packages/cli/src/lib/sentry-urls.ts @@ -236,6 +236,24 @@ export function buildEventSearchUrl(orgSlug: string, eventId: string): string { return `${getSentryBaseUrl()}/organizations/${orgSlug}/issues/?query=event.id:${eventId}`; } +/** + * Build URL to a project's issue stream in Sentry. + * + * @param orgSlug - Organization slug + * @param projectId - Numeric project ID + * @returns Full URL to the issues list filtered to the project + */ +export function buildProjectIssuesUrl( + orgSlug: string, + projectId: string, +): string { + const project = encodeURIComponent(projectId); + if (isSaaS()) { + return `${getOrgBaseUrl(orgSlug)}/issues/?project=${project}`; + } + return `${getSentryBaseUrl()}/organizations/${orgSlug}/issues/?project=${project}`; +} + // Settings URLs /** diff --git a/packages/cli/src/lib/sentry-web-urls.ts b/packages/cli/src/lib/sentry-web-urls.ts index 2207e6a9d..f4805167f 100644 --- a/packages/cli/src/lib/sentry-web-urls.ts +++ b/packages/cli/src/lib/sentry-web-urls.ts @@ -11,6 +11,7 @@ import { buildMetricAlertsUrl as buildMetricAlertsUrlPure, buildOrgSettingsUrl as buildOrgSettingsUrlPure, buildOrgUrl as buildOrgUrlPure, + buildProjectIssuesUrl as buildProjectIssuesUrlPure, buildProjectUrl as buildProjectUrlPure, buildReleaseUrl as buildReleaseUrlPure, buildReplayUrl as buildReplayUrlPure, @@ -56,6 +57,13 @@ export function buildEventSearchUrl(orgSlug: string, eventId: string): string { return render(() => buildEventSearchUrlPure(orgSlug, eventId)); } +export function buildProjectIssuesUrl( + orgSlug: string, + projectId: string, +): string { + return render(() => buildProjectIssuesUrlPure(orgSlug, projectId)); +} + export function buildOrgSettingsUrl(orgSlug: string, hash?: string): string { return render(() => buildOrgSettingsUrlPure(orgSlug, hash)); } diff --git a/packages/cli/src/lib/sixel-image.ts b/packages/cli/src/lib/sixel-image.ts index 30b175ac3..a7ac0f314 100644 --- a/packages/cli/src/lib/sixel-image.ts +++ b/packages/cli/src/lib/sixel-image.ts @@ -601,9 +601,9 @@ export function encodeImageToSixel( // DCS: P1=0 aspect, P2=1 (unpainted = transparent), P3=0 grid; then raster // attributes "1;1;W;H so the terminal reserves the right pixel box. let out = `\x1bP0;1;0q"1;1;${width};${height}`; - palette.forEach(([r, g, b], i) => { + for (const [i, [r, g, b]] of palette.entries()) { out += `#${i};2;${to100(r)};${to100(g)};${to100(b)}`; - }); + } const totalBands = Math.ceil(height / 6); for (let band = 0; band < totalBands; band++) { diff --git a/packages/cli/src/lib/wizard/utils/ast-utils.ts b/packages/cli/src/lib/wizard/utils/ast-utils.ts new file mode 100644 index 000000000..9bf504f45 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/ast-utils.ts @@ -0,0 +1,350 @@ +/** + * Helpers that find and change nodes in a recast AST, shared by the wizards + * that edit JavaScript and TypeScript config files. + */ + +import recast from "recast"; + +import { debug } from "./debug.js"; +import type { namedTypes as t } from "ast-types"; + +const b = recast.types.builders; + +/** + * checks for require('@sentry/*') syntax + */ +export function hasSentryContent(program: t.Program): boolean { + let foundSentry: boolean | undefined = false; + recast.visit(program, { + visitStringLiteral(path) { + foundSentry = foundSentry || path.node.value.startsWith("@sentry/"); + this.traverse(path); + }, + visitLiteral(path) { + foundSentry = + foundSentry || path.node.value?.toString().startsWith("@sentry/"); + this.traverse(path); + }, + }); + + return !!foundSentry; +} + +/** + * Searches for a property of an ObjectExpression by name + * + * @param object the ObjectExpression to search in + * @param name the name of the property to search for + * + * @returns the property if it exists + */ +export function getObjectProperty( + object: t.ObjectExpression, + name: string, +): t.Property | undefined { + return object.properties.find((p): p is t.Property => { + const isObjectProp = p.type === "Property" || p.type === "ObjectProperty"; + + if (!isObjectProp) { + return false; + } + + const hasMatchingLiteralKey = + (p.key.type === "Literal" || p.key.type === "StringLiteral") && + p.key.value === name; + + if (hasMatchingLiteralKey) { + return true; + } + + // has matching identifier key + return p.key.type === "Identifier" && p.key.name === name; + }); +} + +/** + * Attempts to find a property of an ObjectExpression by name. If it doesn't exist, + * the property will be added to the ObjectExpression with the provided default value. + * + * @param object the parent object expression to search in + * @param name the name of the property to search for + * @param defaultValue the default value to set if the property doesn't exist + * + * @returns the + */ +export function getOrSetObjectProperty( + object: t.ObjectExpression, + name: string, + defaultValue: + | t.Literal + | t.BooleanLiteral + | t.StringLiteral + | t.ObjectExpression, +): t.Property { + const existingProperty = getObjectProperty(object, name); + + if (existingProperty) { + return existingProperty; + } + + const newProperty = b.property.from({ + kind: "init", + key: b.stringLiteral(name), + value: defaultValue, + }); + + object.properties.push(newProperty); + + return newProperty; +} + +/** + * Sets a property of an ObjectExpression if it exists, otherwise adds it + * to the ObjectExpression. Optionally, a comment can be added to the + * property. + * + * @param object the ObjectExpression to set the property on + * @param name the name of the property to set + * @param value the value of the property to set + * @param comment (optional) a comment to add to the property + */ +export function setOrUpdateObjectProperty( + object: t.ObjectExpression, + name: string, + value: + | t.Literal + | t.BooleanLiteral + | t.StringLiteral + | t.ObjectExpression + | t.ArrayExpression, + comment?: string, +): void { + const newComments = comment + ?.split("\n") + .map((c) => b.commentLine(` ${c}`, true, false)); + + const existingProperty = getObjectProperty(object, name); + + if (existingProperty) { + existingProperty.value = value; + if (newComments) { + existingProperty.comments = [ + ...(existingProperty.comments ?? []), + ...newComments, + ]; + } + } else { + object.properties.push( + b.objectProperty.from({ + key: b.stringLiteral(name), + value, + ...(newComments && { + comments: newComments, + }), + }), + ); + } +} + +type JsonCParseResult = + | { + jsonObject: t.ObjectExpression; + ast: t.Program; + } + | { + jsonObject: undefined; + ast: undefined; + }; + +/** + * Parses a JSON string with (potential) comments (JSON-C) and returns the JS AST + * that can be walked and modified with recast like a normal JS AST. + * + * This is done by wrapping the JSON-C string in parentheses, thereby making it + * a JS `Program` with an `ExpressionStatement` as its body. The expression is then + * extracted from the AST and returned alongside the AST. + * + * To preserve as much original formatting as possible, the returned `ast` + * property should be passed to {@link `printJsonC`} to get the JSON-C string back. + * + * If the input is not valid JSON-C, the result will be undefined. + * + * @see {@link JsonCParseResult} + * + * @param jsonString a JSON-C string + * + * @returns a {@link JsonCParseResult}, containing either the JSON-C object and the AST or undefined in both cases + */ +export function parseJsonC(jsonString: string): JsonCParseResult { + try { + const jsTsConfig = `(${jsonString})`; + // no idea why recast returns any here, this is dumb :/ + const ast = recast.parse(jsTsConfig.toString()).program as t.Program; + + const statement = ast.body[0]; + const jsonObject = + statement?.type === "ExpressionStatement" && + statement.expression.type === "ObjectExpression" + ? statement.expression + : undefined; + + if (jsonObject) { + return { jsonObject, ast }; + } + } catch (error) { + // Not valid JSON-C: the caller handles the undefined result. + debug(error); + return { jsonObject: undefined, ast: undefined }; + } + return { jsonObject: undefined, ast: undefined }; +} + +/** + * Takes the AST of a parsed JSON-C "program" and returns the JSON-C string without + * any of the temporary JS wrapper code that was previously applied. + * + * Only use this in conjunction with {@link `parseJsonC`} + * + * @param ast the `ast` returned from {@link `parseJsonC`} + * + * @returns the JSON-C string + */ +export function printJsonC(ast: t.Program): string { + const js = recast.print(ast).code; + return js.substring(1, js.length - 1); +} + +/** + * Walks the program body and returns index of the last variable assignment initialized by require statement. + * Only counts top level require statements. + * + * @returns index of the last `const foo = require('bar');` statement or -1 if none was found. + */ +export function getLastRequireIndex(program: t.Program): number { + let lastRequireIdex = -1; + for (const [i, s] of program.body.entries()) { + const declaration = + s.type === "VariableDeclaration" ? s.declarations[0] : undefined; + if ( + declaration?.type === "VariableDeclarator" && + declaration.init?.type === "CallExpression" && + declaration.init.callee.type === "Identifier" && + declaration.init.callee.name === "require" + ) { + lastRequireIdex = i; + } + } + return lastRequireIdex; +} + +/** + * Safely checks if a callee is an identifier with the given name + * Prevents crashes when accessing callee.name on non-identifier nodes + */ +export function safeCalleeIdentifierMatch( + callee: unknown, + name: string, +): boolean { + return Boolean( + callee && + typeof callee === "object" && + "type" in callee && + (callee as { type: string }).type === "Identifier" && + "name" in callee && + (callee as { name: string }).name === name, + ); +} + +/** + * Safely gets the name of an identifier node + * Returns null if the node is not an identifier or is undefined + */ +export function safeGetIdentifierName(node: unknown): string | null { + return node && + typeof node === "object" && + "type" in node && + node.type === "Identifier" && + "name" in node + ? String(node.name) + : null; +} + +/** + * Safely access function body array with proper validation + * Prevents crashes when accessing body.body on nodes that don't have a body + */ +export function safeGetFunctionBody(node: unknown): t.Statement[] | null { + if (!node || typeof node !== "object" || !("body" in node)) { + return null; + } + + const nodeBody = node.body; + if (!nodeBody || typeof nodeBody !== "object" || !("body" in nodeBody)) { + return null; + } + + const bodyArray = nodeBody.body; + return Array.isArray(bodyArray) ? (bodyArray as t.Statement[]) : null; +} + +/** + * Safely insert statement before last statement in function body + * Typically used to insert code before a return statement + * Returns true if insertion was successful, false otherwise + */ +export function safeInsertBeforeReturn( + body: t.Statement[], + statement: t.Statement, +): boolean { + if (body.length === 0) { + return false; + } + + // Insert before the last statement (typically a return statement) + const insertIndex = Math.max(0, body.length - 1); + body.splice(insertIndex, 0, statement); + return true; +} + +/** + * Finds a property in an ObjectExpression by name. + * Commonly used for traversing Vite/React Router config objects. + * + * @param configObj - The ObjectExpression to search + * @param name - The property name to find + * @returns The matching ObjectProperty, or undefined if not found + */ +export function findProperty( + configObj: t.ObjectExpression, + name: string, +): t.ObjectProperty | undefined { + return configObj.properties.find( + (p) => + p.type === "ObjectProperty" && + p.key.type === "Identifier" && + p.key.name === name, + ) as t.ObjectProperty | undefined; // Safe: predicate guarantees type +} + +/** + * Preserves trailing newline from original content if present. + * Code generators like magicast/recast don't preserve trailing newlines, + * so this ensures we don't unnecessarily modify user files. + * + * @param originalContent - The original file content + * @param generatedCode - The code generated by AST transformation + * @returns The generated code with trailing newline preserved if original had one + */ +export function preserveTrailingNewline( + originalContent: string, + generatedCode: string, +): string { + const hadTrailingNewline = originalContent.endsWith("\n"); + const hasTrailingNewline = generatedCode.endsWith("\n"); + + if (hadTrailingNewline && !hasTrailingNewline) { + return generatedCode + "\n"; + } + + return generatedCode; +} diff --git a/packages/cli/test/lib/api/traces.test.ts b/packages/cli/test/lib/api/traces.test.ts index 1b7b0d06a..2cdc4baba 100644 --- a/packages/cli/test/lib/api/traces.test.ts +++ b/packages/cli/test/lib/api/traces.test.ts @@ -594,9 +594,9 @@ describe("getSpanDetails", () => { const req = new Request(input, init); capturedUrl = req.url; const url = new URL(capturedUrl); - url.searchParams.forEach((v, k) => { + for (const [k, v] of url.searchParams) { capturedParams[k] = v; - }); + } return new Response(JSON.stringify(body), { status: 200, headers: { "Content-Type": "application/json" }, diff --git a/packages/cli/test/lib/dsn/fs-utils.test.ts b/packages/cli/test/lib/dsn/fs-utils.test.ts index a1b47c0da..c637ac276 100644 --- a/packages/cli/test/lib/dsn/fs-utils.test.ts +++ b/packages/cli/test/lib/dsn/fs-utils.test.ts @@ -5,6 +5,10 @@ * errors (ignored, debug-logged) from unexpected ones (reported to Sentry). */ +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; const { reportCliError } = vi.hoisted(() => ({ @@ -16,7 +20,8 @@ vi.mock("@sentry/node", () => ({ startSpan: (_opts: unknown, fn: () => unknown) => fn(), })); -const { handleFileError } = await import("../../../src/lib/dsn/fs-utils.js"); +const { findFile, handleFileError } = + await import("../../../src/lib/dsn/fs-utils.js"); /** Create an Error with a `code` property, mimicking Node/Bun errno errors. */ function errnoError(code: string, message?: string): Error { @@ -184,3 +189,39 @@ describe("handleFileError", () => { }); }); }); + +describe("findFile", () => { + let dir: string; + + beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), "find-file-")); + }); + + afterEach(async () => { + await rm(dir, { recursive: true, force: true }); + }); + + test("returns the first extension that exists, in order", async () => { + await writeFile(join(dir, "next.config.mjs"), ""); + await writeFile(join(dir, "next.config.cjs"), ""); + + expect(await findFile(join(dir, "next.config"))).toBe( + join(dir, "next.config.mjs"), + ); + }); + + test("skips a directory with a matching name", async () => { + await mkdir(join(dir, "next.config.js")); + await writeFile(join(dir, "next.config.ts"), ""); + + expect(await findFile(join(dir, "next.config"))).toBe( + join(dir, "next.config.ts"), + ); + }); + + test("returns undefined when no extension matches", async () => { + expect( + await findFile(join(dir, "vite.config"), [".js", ".ts"]), + ).toBeUndefined(); + }); +}); diff --git a/packages/cli/test/lib/sdk-positionals.property.test.ts b/packages/cli/test/lib/sdk-positionals.property.test.ts index 15b53cb35..b1a45e503 100644 --- a/packages/cli/test/lib/sdk-positionals.property.test.ts +++ b/packages/cli/test/lib/sdk-positionals.property.test.ts @@ -26,9 +26,9 @@ describe("positionals", () => { fcAssert( property(valuesArb, (values) => { const result = positionals(...values); - result.forEach((token, i) => { + for (const [i, token] of result.entries()) { expect(token).toBe(values[i] ?? ""); - }); + } }), { numRuns: DEFAULT_NUM_RUNS }, ); diff --git a/packages/cli/test/lib/sentry-urls.credential.test.ts b/packages/cli/test/lib/sentry-urls.credential.test.ts index 38e9d87be..e5000fe36 100644 --- a/packages/cli/test/lib/sentry-urls.credential.test.ts +++ b/packages/cli/test/lib/sentry-urls.credential.test.ts @@ -3,6 +3,7 @@ import { setAuthToken } from "../../src/lib/db/auth.js"; import { resetEnvTokenHostForTesting } from "../../src/lib/env-token-host.js"; import { buildOrgUrl, + buildProjectIssuesUrl, buildProjectUrl, getSentryBaseUrl, isSaaS, @@ -40,6 +41,9 @@ describe("web URLs for active credential hosts", () => { expect(buildProjectUrl("acme", "site")).toBe( "https://sentry.example.com/settings/acme/projects/site/", ); + expect(buildProjectIssuesUrl("acme", "42")).toBe( + "https://sentry.example.com/organizations/acme/issues/?project=42", + ); }); test("stored OAuth host wins over an inactive environment token", () => { diff --git a/packages/cli/test/lib/sentry-urls.property.test.ts b/packages/cli/test/lib/sentry-urls.property.test.ts index 22027bdf1..1d4227b1a 100644 --- a/packages/cli/test/lib/sentry-urls.property.test.ts +++ b/packages/cli/test/lib/sentry-urls.property.test.ts @@ -19,6 +19,7 @@ import { buildDashboardsListUrl, buildDashboardUrl, buildEventSearchUrl, + buildProjectIssuesUrl, buildLogsUrl, buildOrgSettingsUrl, buildOrgUrl, @@ -301,6 +302,21 @@ describe("buildEventSearchUrl properties", () => { }); }); +describe("buildProjectIssuesUrl", () => { + test("filters the org-subdomain issue stream to the project on SaaS", () => { + expect(buildProjectIssuesUrl("my-org", "1234567")).toBe( + "https://my-org.sentry.io/issues/?project=1234567", + ); + }); + + test("uses the organizations path on self-hosted", () => { + process.env["SENTRY_URL"] = "https://sentry.example.com"; + expect(buildProjectIssuesUrl("my-org", "42")).toBe( + "https://sentry.example.com/organizations/my-org/issues/?project=42", + ); + }); +}); + describe("buildOrgSettingsUrl properties", () => { test("without hash, output ends with trailing slash", async () => { fcAssert( diff --git a/packages/cli/test/lib/wizard/nextjs/utils.test.ts b/packages/cli/test/lib/wizard/nextjs/utils.test.ts index df026e57e..cddd02381 100644 --- a/packages/cli/test/lib/wizard/nextjs/utils.test.ts +++ b/packages/cli/test/lib/wizard/nextjs/utils.test.ts @@ -89,13 +89,13 @@ describe("Next.js Utils", () => { const mockAppFolderPath = "/mock/app"; const supportedExtensions = ["jsx", "tsx", "js"]; - supportedExtensions.forEach((ext) => { + for (const ext of supportedExtensions) { (fs.existsSync as Mock).mockImplementation((filePath: string) => { return filePath === `/mock/app/layout.${ext}`; }); expect(hasRootLayoutFile(mockAppFolderPath)).toBe(true); - }); + } }); it("returns false when no layout file exists", () => { diff --git a/packages/cli/test/lib/wizard/utils/ast-utils.test.ts b/packages/cli/test/lib/wizard/utils/ast-utils.test.ts new file mode 100644 index 000000000..f42f1de88 --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/ast-utils.test.ts @@ -0,0 +1,297 @@ +import { + getObjectProperty, + getOrSetObjectProperty, + hasSentryContent, + parseJsonC, + preserveTrailingNewline, + printJsonC, + setOrUpdateObjectProperty, +} from "../../../../src/lib/wizard/utils/ast-utils.js"; + +import recast from "recast"; +const b = recast.types.builders; + +import { describe, it, expect } from "vitest"; + +describe("hasSentryContent", () => { + it.each([ + ` + const { sentryVitePlugin } = require("@sentry/bundler-plugins/vite"); + const somethingelse = require('gs'); + `, + ` + import { sentryVitePlugin } from "@sentry/bundler-plugins/vite"; + import * as somethingelse from 'gs'; + + export default { + plugins: [sentryVitePlugin()] + } + `, + ])( + "returns true if a require('@sentry/') call was found in the parsed module", + (code) => { + // recast.parse returns a Program node (or fails) but it's badly typed as any + const program = recast.parse(code) + .program as recast.types.namedTypes.Program; + expect(hasSentryContent(program)).toBe(true); + }, + ); + + it.each([ + `const whatever = require('something')`, + `// const {sentryWebpackPlugin} = require('@sentry/bundler-plugins/webpack')`, + `const {sAntryWebpackPlugin} = require('webpack-plugin-@sentry')`, + ` + import * as somethingelse from 'gs'; + export default { + plugins: [] + } + `, + `import * as somethingelse from 'gs'; + // import { sentryVitePlugin } from "@sentry/bundler-plugins/vite" + export default { + plugins: [] + } + `, + `import * as thirdPartyVitePlugin from "vite-plugin-@sentry" + export default { + plugins: [thirdPartyVitePlugin()] + } + `, + ])( + "returns false if the file doesn't contain any require('@sentry/') calls", + (code) => { + // recast.parse returns a Program node (or fails) but it's badly typed as any + const program = recast.parse(code) + .program as recast.types.namedTypes.Program; + expect(hasSentryContent(program)).toBe(false); + }, + ); +}); + +describe("getObjectProperty", () => { + it.each([ + [ + "literal", + b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + b.objectProperty( + b.stringLiteral("needle"), + b.stringLiteral("haystack"), + ), + ]), + ], + [ + "stringLiteral", + b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + b.objectProperty(b.literal("needle"), b.stringLiteral("haystack")), + ]), + ], + [ + "identifier", + b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + b.objectProperty(b.identifier("needle"), b.stringLiteral("haystack")), + ]), + ], + ])("returns the poperty (%s) if it exists", (_, object) => { + const property = getObjectProperty(object, "needle"); + expect(property).toBeDefined(); + // @ts-expect-error we know it's defined due to the expect above + expect(recast.print(property).code).toEqual( + expect.stringContaining("needle"), + ); + }); + + it("returns undefined if the property does not exist", () => { + const object = b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + ]); + const property = getObjectProperty(object, "needle"); + expect(property).toBeUndefined(); + }); + + it("handles objects without simple properties", () => { + const object = b.objectExpression([b.spreadElement(b.identifier("foo"))]); + const property = getObjectProperty(object, "needle"); + expect(property).toBeUndefined(); + }); +}); + +describe("getOrSetObjectProperty", () => { + it("returns the property if it exists", () => { + const object = b.objectExpression([ + b.objectProperty(b.identifier("needle"), b.stringLiteral("haystack")), + ]); + + const property = getOrSetObjectProperty( + object, + "needle", + b.stringLiteral("nope"), + ); + + expect(property).toBeDefined(); + expect(property.type).toBe("ObjectProperty"); + // @ts-expect-error we know its type + expect(property.key.name).toBe("needle"); + // @ts-expect-error we know its type + expect(property.value.value).toBe("haystack"); + }); + + it("adds the property if it does not exist", () => { + const object = b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + ]); + + const property = getOrSetObjectProperty( + object, + "needle", + b.stringLiteral("haystack"), + ); + + expect(property).toBeDefined(); + expect(property.type).toBe("Property"); + // @ts-expect-error we know its type + expect(property.key.value).toBe("needle"); + // @ts-expect-error we know its type + expect(property.value.value).toBe("haystack"); + }); +}); + +describe("setOrUpdateObjectProperty", () => { + it("sets a new property if it does not exist yet", () => { + const object = b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + ]); + + setOrUpdateObjectProperty(object, "needle", b.stringLiteral("haystack")); + + expect(getObjectProperty(object, "needle")).toBeDefined(); + }); + + it("updates an existing property if it exists", () => { + const object = b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + b.objectProperty(b.identifier("needle"), b.stringLiteral("haystack")), + ]); + + setOrUpdateObjectProperty(object, "needle", b.stringLiteral("haystack2")); + + const property = getObjectProperty(object, "needle"); + // @ts-expect-error it must be defiend, otherwise we fail anyway + expect(property?.value.value).toBe("haystack2"); + }); + + it("adds a comment to the existing property if provided", () => { + const object = b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + ]); + + setOrUpdateObjectProperty( + object, + "needle", + b.stringLiteral("haystack"), + "This is a comment", + ); + + const property = getObjectProperty(object, "needle"); + expect(property?.comments).toHaveLength(1); + // @ts-expect-error it must be defiend, otherwise we fail anyway + expect(property?.comments[0].value).toBe(" This is a comment"); + }); + + it("adds a comment to the new property if provided", () => { + const object = b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + ]); + + setOrUpdateObjectProperty( + object, + "needle", + b.stringLiteral("haystack"), + "This is a comment", + ); + + const property = getObjectProperty(object, "needle"); + expect(property?.comments).toHaveLength(1); + // @ts-expect-error it must be defiend, otherwise we fail anyway + expect(property?.comments[0].value).toBe(" This is a comment"); + }); +}); + +describe("preserveTrailingNewline", () => { + it("adds trailing newline if original had one but generated does not", () => { + const original = "const foo = 1;\n"; + const generated = "const foo = 1;"; + expect(preserveTrailingNewline(original, generated)).toBe( + "const foo = 1;\n", + ); + }); + + it("does not add trailing newline if original did not have one", () => { + const original = "const foo = 1;"; + const generated = "const foo = 1;"; + expect(preserveTrailingNewline(original, generated)).toBe("const foo = 1;"); + }); + + it("does not double trailing newline if both already have one", () => { + const original = "const foo = 1;\n"; + const generated = "const foo = 1;\n"; + expect(preserveTrailingNewline(original, generated)).toBe( + "const foo = 1;\n", + ); + }); + + it("does not remove trailing newline if original did not have one but generated does", () => { + const original = "const foo = 1;"; + const generated = "const foo = 1;\n"; + expect(preserveTrailingNewline(original, generated)).toBe( + "const foo = 1;\n", + ); + }); +}); + +describe("parse and print JSON-C", () => { + it.each([ + ["simple JSON", "{'foo': 'bar'}"], + [ + "JSON-C with inline comment", + ` + { + "foo": "bar" // with an inline comment + } + `, + ], + [ + "JSON-C with multiple comments", + ` + /* + * let's throw in a block comment for good measure + */ + { + // one line comment + "foo": "bar", // another inline comment + /* one more here */ + "dogs": /* and here */ "awesome", + } + /* and here */ + `, + ], + ])(`parses and prints JSON-C (%s)`, (_, json) => { + const { ast, jsonObject } = parseJsonC(json); + expect(ast?.type).toBe("Program"); + expect(jsonObject).toBeDefined(); + expect(jsonObject?.type).toBe("ObjectExpression"); + // @ts-expect-error we know it's defined due to the expect above + expect(printJsonC(ast)).toEqual(json); + }); + + it("returns undefined if the input is not valid JSON-C", () => { + const { ast, jsonObject } = parseJsonC(`{ + "invalid": // "json" + }`); + expect(ast).toBeUndefined(); + expect(jsonObject).toBeUndefined(); + }); +}); diff --git a/packages/cli/test/mocks/server.ts b/packages/cli/test/mocks/server.ts index 364b5b3f9..9e5b466d8 100644 --- a/packages/cli/test/mocks/server.ts +++ b/packages/cli/test/mocks/server.ts @@ -69,12 +69,12 @@ function matchRoute( if (match) { const [, ...values] = match; const params: Record = {}; - route.paramNames.forEach((name, i) => { + for (const [i, name] of route.paramNames.entries()) { const value = values[i]; if (value !== undefined) { params[name] = value; } - }); + } return { route, params }; } } diff --git a/packages/mcp-cloudflare/src/client/components/chat/chat-messages.tsx b/packages/mcp-cloudflare/src/client/components/chat/chat-messages.tsx index 9aedb5d57..242541ed7 100644 --- a/packages/mcp-cloudflare/src/client/components/chat/chat-messages.tsx +++ b/packages/mcp-cloudflare/src/client/components/chat/chat-messages.tsx @@ -24,34 +24,32 @@ function processMessages( // Only the very last text part of the very last message should be streaming const lastMessageIndex = messages.length - 1; - messages.forEach((message, messageIndex) => { + for (const [messageIndex, message] of messages.entries()) { const isLastMessage = messageIndex === lastMessageIndex; // Handle messages with parts array if (message.parts.length > 0) { const lastPartIndex = message.parts.length - 1; - message.parts.forEach( - (part: UIMessage["parts"][number], partIndex: number) => { - const isLastPartOfLastMessage = - isLastMessage && partIndex === lastPartIndex; + for (const [partIndex, part] of message.parts.entries()) { + const isLastPartOfLastMessage = + isLastMessage && partIndex === lastPartIndex; - allParts.push({ - part, - messageId: message.id, - messageRole: message.role, - partIndex, - // Stream if it's AI response OR local streaming simulation - isStreaming: - (isLastPartOfLastMessage && - isChatLoading && - part.type === "text") || - (part.type === "text" && !!isMessageStreaming?.(message.id)), - }); - }, - ); + allParts.push({ + part, + messageId: message.id, + messageRole: message.role, + partIndex, + // Stream if it's AI response OR local streaming simulation + isStreaming: + (isLastPartOfLastMessage && + isChatLoading && + part.type === "text") || + (part.type === "text" && !!isMessageStreaming?.(message.id)), + }); + } } - }); + } return allParts; } diff --git a/packages/mcp-core/chart-app/chart.ts b/packages/mcp-core/chart-app/chart.ts index 569d49cdd..78c9f684e 100644 --- a/packages/mcp-core/chart-app/chart.ts +++ b/packages/mcp-core/chart-app/chart.ts @@ -256,7 +256,7 @@ export function drawChart( const single = chart.series.length === 1; const path = (pts: readonly Point[]) => pts.map(([px, py], i) => `${i ? "L" : "M"}${px},${py}`).join(""); - chart.series.forEach((series, index) => { + for (const [index, series] of chart.series.entries()) { const color = SERIES_COLORS[index % SERIES_COLORS.length] ?? "#7553ff"; // Runs of buckets with data. A null bucket ends a run, so it draws as a // gap instead of a drop to 0. @@ -306,7 +306,7 @@ export function drawChart( ); } } - }); + } const crosshair = svg( "line", @@ -397,11 +397,11 @@ export function drawChart( } const time = first + ((px - MARGIN.left) / plotWidth) * span; let nearest = 0; - times.forEach((t, i) => { + for (const [i, t] of times.entries()) { if (Math.abs(t - time) < Math.abs((times[nearest] ?? 0) - time)) { nearest = i; } - }); + } showAt(nearest); }); root.addEventListener("pointerleave", hide); diff --git a/packages/mcp-core/src/api-client/client-request-paths.test.ts b/packages/mcp-core/src/api-client/client-request-paths.test.ts index c4b347c85..b0f893bb4 100644 --- a/packages/mcp-core/src/api-client/client-request-paths.test.ts +++ b/packages/mcp-core/src/api-client/client-request-paths.test.ts @@ -35,9 +35,9 @@ describe("client.ts request path invariant", () => { it("interpolates every request path through apiPath", () => { const offenders: string[] = []; - source.split("\n").forEach((line, index) => { + for (const [index, line] of source.split("\n").entries()) { const trimmed = line.trim(); - if (trimmed.startsWith("//") || trimmed.startsWith("*")) return; + if (trimmed.startsWith("//") || trimmed.startsWith("*")) continue; // A template literal opening with a slash is an API request path. for (let i = 0; i < line.length - 1; i++) { @@ -53,7 +53,7 @@ describe("client.ts request path invariant", () => { offenders.push(`${index + 1}: ${trimmed}`); } } - }); + } expect( offenders, diff --git a/packages/mcp-core/src/internal/issue-side-quests.test.ts b/packages/mcp-core/src/internal/issue-side-quests.test.ts index 894aab0c0..6fa41fde2 100644 --- a/packages/mcp-core/src/internal/issue-side-quests.test.ts +++ b/packages/mcp-core/src/internal/issue-side-quests.test.ts @@ -24,11 +24,9 @@ function eventWithFourFiles() { if (!("rawStacktrace" in value)) { continue; } - value.rawStacktrace.frames.forEach( - (frame: { absPath: string | null }, index: number) => { - frame.absPath = files[index] ?? frame.absPath; - }, - ); + for (const [index, frame] of value.rawStacktrace.frames.entries()) { + frame.absPath = files[index] ?? frame.absPath; + } } } return EventSchema.parse({ diff --git a/packages/mcp-core/src/internal/side-quests.ts b/packages/mcp-core/src/internal/side-quests.ts index be29b1e1a..06e18f95d 100644 --- a/packages/mcp-core/src/internal/side-quests.ts +++ b/packages/mcp-core/src/internal/side-quests.ts @@ -122,9 +122,9 @@ function recordSideQuests(ids: string[], max: number) { "app.side_quests.detected": ids.length, "app.side_quests.shown": shown.length, }; - ids.forEach((id, index) => { + for (const [index, id] of ids.entries()) { attributes[`app.side_quest.${id}`] = index < max ? "shown" : "capped"; - }); + } getActiveSpan()?.setAttributes(attributes); for (const id of shown) { metrics.count("app.side_quest.shown", 1, { diff --git a/packages/mcp-core/src/internal/source-map-diagnosis.ts b/packages/mcp-core/src/internal/source-map-diagnosis.ts index 6ae0968df..d1519414f 100644 --- a/packages/mcp-core/src/internal/source-map-diagnosis.ts +++ b/packages/mcp-core/src/internal/source-map-diagnosis.ts @@ -101,17 +101,17 @@ function getDebugFramesByPath(event: Event, debug: SourceMapDebug) { } return parsed.data.values ?? (parsed.data.value ? [parsed.data.value] : []); }); - values.forEach((value, exceptionIndex) => { + for (const [exceptionIndex, value] of values.entries()) { const rawFrames = value?.rawStacktrace?.frames ?? []; - rawFrames.forEach((rawFrame, frameIndex) => { + for (const [frameIndex, rawFrame] of rawFrames.entries()) { const path = rawFrame.absPath; // the check can return fewer exceptions or frames than the event has const frame = debug.exceptions.at(exceptionIndex)?.frames.at(frameIndex); if (path && frame && !frames.has(path)) { frames.set(path, frame); } - }); - }); + } + } return frames; } diff --git a/packages/mcp-core/src/server.ui-resources.test.ts b/packages/mcp-core/src/server.ui-resources.test.ts index bd31394ab..b17369868 100644 --- a/packages/mcp-core/src/server.ui-resources.test.ts +++ b/packages/mcp-core/src/server.ui-resources.test.ts @@ -15,7 +15,7 @@ vi.mock("@sentry/core/server", () => ({ wrapMcpServerWithSentry: vi.fn((server) => server), })); -const CHART_URI = "ui://sentry/chart/v5.html"; +const CHART_URI = "ui://sentry/chart/v6.html"; const MCP_APP_MIME_TYPE = "text/html;profile=mcp-app"; async function connect(skills: Skill[]) { diff --git a/packages/mcp-core/src/tools/catalog/get-event-attachment.ts b/packages/mcp-core/src/tools/catalog/get-event-attachment.ts index 44591e0df..1ab6b1073 100644 --- a/packages/mcp-core/src/tools/catalog/get-event-attachment.ts +++ b/packages/mcp-core/src/tools/catalog/get-event-attachment.ts @@ -221,7 +221,7 @@ export default defineTool({ output += `Found ${attachments.length} attachment(s):\n\n`; - attachments.forEach((attachment, index) => { + for (const [index, attachment] of attachments.entries()) { output += `## Attachment ${index + 1}\n\n`; output += `**ID:** ${attachment.id}\n`; output += `**Name:** ${attachment.name}\n`; @@ -242,7 +242,7 @@ export default defineTool({ availableToolNames: context.availableToolNames, directToolNames: context.directToolNames, })}\n\n`; - }); + } return output; }, diff --git a/packages/mcp-core/src/tools/support/profile/analyzer.ts b/packages/mcp-core/src/tools/support/profile/analyzer.ts index 70c89eeac..8900f03c6 100644 --- a/packages/mcp-core/src/tools/support/profile/analyzer.ts +++ b/packages/mcp-core/src/tools/support/profile/analyzer.ts @@ -338,15 +338,15 @@ export function compareFrameStats( { baselineIdx?: number; currentIdx?: number } >(); - baselineFrames.forEach((frame, idx) => { + for (const [idx, frame] of baselineFrames.entries()) { const existing = frameMap.get(frame.fingerprint) || {}; frameMap.set(frame.fingerprint, { ...existing, baselineIdx: idx }); - }); + } - currentFrames.forEach((frame, idx) => { + for (const [idx, frame] of currentFrames.entries()) { const existing = frameMap.get(frame.fingerprint) || {}; frameMap.set(frame.fingerprint, { ...existing, currentIdx: idx }); - }); + } // Compare frames that exist in both const comparisons: FrameComparison[] = []; diff --git a/packages/mcp-core/src/tools/support/profile/flamegraph-output.ts b/packages/mcp-core/src/tools/support/profile/flamegraph-output.ts index 848a6963e..16df286e8 100644 --- a/packages/mcp-core/src/tools/support/profile/flamegraph-output.ts +++ b/packages/mcp-core/src/tools/support/profile/flamegraph-output.ts @@ -178,15 +178,15 @@ export function buildFlamegraphAnalysis( // both overlap across nested frames, so they cannot be summed. const totalNs = sumOf(mainProfile?.sample_durations_ns); let userCodeNs = 0; - mainProfile?.samples.forEach((stack, index) => { + for (const [index, stack] of (mainProfile?.samples ?? []).entries()) { const leafIndex = stack.at(-1); if ( leafIndex !== undefined && flamegraph.shared.frames[leafIndex]?.is_application ) { - userCodeNs += mainProfile.sample_durations_ns[index] ?? 0; + userCodeNs += mainProfile?.sample_durations_ns[index] ?? 0; } - }); + } const outputFrames: FlamegraphAnalysis["frames"] = []; const outputIndexBySource = new Map(); diff --git a/packages/mcp-core/src/tools/support/search-events/replays.ts b/packages/mcp-core/src/tools/support/search-events/replays.ts index 9d3dc817b..45b900386 100644 --- a/packages/mcp-core/src/tools/support/search-events/replays.ts +++ b/packages/mcp-core/src/tools/support/search-events/replays.ts @@ -312,7 +312,7 @@ export function formatReplayResults(params: FormatReplayResultsParams): string { output += `Found **${replays.length}** replay${replays.length === 1 ? "" : "s"}:\n\n`; - replays.forEach((replay, index) => { + for (const [index, replay] of replays.entries()) { const replayUrl = apiService.getReplayUrl(organizationSlug, replay.id); const user = formatReplayUser(replay); const clickSummary = [ @@ -343,7 +343,7 @@ export function formatReplayResults(params: FormatReplayResultsParams): string { } output += "\n"; - }); + } output += "## Next Steps\n\n"; const replayDetailsInstruction = formatToolCallInstruction({ diff --git a/packages/mcp-core/src/tools/support/search-events/utils.ts b/packages/mcp-core/src/tools/support/search-events/utils.ts index af4975d8b..131472ef9 100644 --- a/packages/mcp-core/src/tools/support/search-events/utils.ts +++ b/packages/mcp-core/src/tools/support/search-events/utils.ts @@ -1348,21 +1348,18 @@ export function createDatasetAttributesTool(options: { let commonFields: Record = {}; let datasetFields: Record = {}; if (substringMatch) { - Object.entries(BASE_COMMON_FIELDS).forEach(([key, value]) => { + for (const [key, value] of Object.entries(BASE_COMMON_FIELDS)) { if (key.includes(substringMatch) || value.includes(substringMatch)) { commonFields[key] = value; } - }); - Object.entries(DATASET_FIELDS[normalizedDataset]).forEach( - ([key, value]) => { - if ( - key.includes(substringMatch) || - value.includes(substringMatch) - ) { - datasetFields[key] = value; - } - }, - ); + } + for (const [key, value] of Object.entries( + DATASET_FIELDS[normalizedDataset], + )) { + if (key.includes(substringMatch) || value.includes(substringMatch)) { + datasetFields[key] = value; + } + } } else { commonFields = BASE_COMMON_FIELDS; datasetFields = DATASET_FIELDS[normalizedDataset]; diff --git a/packages/mcp-core/src/ui-resources.ts b/packages/mcp-core/src/ui-resources.ts index 4c19d2787..590c9101e 100644 --- a/packages/mcp-core/src/ui-resources.ts +++ b/packages/mcp-core/src/ui-resources.ts @@ -57,13 +57,13 @@ export interface UiResource { * chart-app/ by generate-chart-app. */ export const CHART_UI_RESOURCE: UiResource = { - uri: "ui://sentry/chart/v5.html", + uri: "ui://sentry/chart/v6.html", name: "sentry_chart", title: "Sentry Chart", description: "Interactive time series chart for render_sentry_chart and render_issue_chart results, with a range picker, fullscreen, and a link to Sentry.", htmlSha256: - "7957519bcbf3a3855250904467784362573af55eb36cc11bac53d0625c2d2d22", + "079fa3cb185c5fdf7ad4e5983657af34093d2a477963d10be7c6da909aeaeaf5", // About 1.5x the current view, so a new dependency cannot slip in. budgetBytes: 24 * 1024, loadHtml: async () => diff --git a/packages/mcp-core/src/ui/chart-app.generated.ts b/packages/mcp-core/src/ui/chart-app.generated.ts index ed6b4b9e2..f1a79316d 100644 --- a/packages/mcp-core/src/ui/chart-app.generated.ts +++ b/packages/mcp-core/src/ui/chart-app.generated.ts @@ -1,2 +1,2 @@ // Generated by scripts/generate-chart-app.ts from chart-app/. Do not edit. -export const CHART_APP_HTML = "Sentry chart"; +export const CHART_APP_HTML = "Sentry chart"; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 363032cd0..aa38f6486 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -759,6 +759,9 @@ importers: '@vitest/coverage-v8': specifier: 'catalog:' version: 5.0.5(vitest@5.0.5) + ast-types: + specifier: ^0.16.3 + version: 0.16.3 binpatch: specifier: ^0.4.2 version: 0.4.2 @@ -822,6 +825,9 @@ importers: qrcode-terminal: specifier: ^0.12.0 version: 0.12.0 + recast: + specifier: ^0.23.21 + version: 0.23.21 semver: specifier: ^7.8.5 version: 7.8.5