diff --git a/packages/cli/src/lib/wizard/android/android-wizard.ts b/packages/cli/src/lib/wizard/android/android-wizard.ts new file mode 100644 index 000000000..3d58347bd --- /dev/null +++ b/packages/cli/src/lib/wizard/android/android-wizard.ts @@ -0,0 +1,234 @@ +/** + * The Android wizard: adds the Sentry Android Gradle plugin, configures the + * SDK in `AndroidManifest.xml`, patches the main activity with a test error, + * and writes `sentry.properties` for the plugin's ProGuard mapping upload. + * Ported from sentry-wizard's `src/android`. + */ + +import { readdirSync } from "node:fs"; +import path from "node:path"; +import chalk from "chalk"; +import { Sentry, traceStep, withTelemetry } from "../telemetry.js"; +import { abortIfSpotlightNotSupported } from "../utils/abort-if-sportlight-not-supported.js"; +import { + type CliSetupConfig, + abort, + abortIfCancelled, + addSentryCliConfig, + confirmContinueIfNoOrDirtyGitRepo, + getOrAskForProjectData, + printWelcome, + propertiesCliSetupConfig, +} from "../utils/clack/index.js"; +import { offerProjectScopedMcpConfig } from "../utils/clack/mcp-config.js"; +import { clack } from "../utils/clack/prompts.js"; +import { fixLineEndings } from "../utils/line-endings.js"; +import type { WizardOptions } from "../utils/types.js"; +import { findActivitySourceFile, patchMainActivity } from "./code-tools.js"; +import { addGradlePlugin, getNamespace, selectAppFile } from "./gradle.js"; +import { addManifestSnippet, getMainActivity } from "./manifest.js"; + +const proguardMappingCliSetupConfig: CliSetupConfig = { + ...propertiesCliSetupConfig, + name: "proguard mappings", +}; + +/** Run the Android wizard in its telemetry span. */ +export async function runAndroidWizard(options: WizardOptions): Promise { + return await withTelemetry( + { + enabled: options.telemetryEnabled, + integration: "android", + wizardOptions: options, + }, + () => runAndroidWizardWithTelemetry(options), + ); +} + +async function runAndroidWizardWithTelemetry( + options: WizardOptions, +): Promise { + printWelcome({ + wizardName: "Sentry Android Wizard", + }); + + await confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: options.ignoreGitChanges, + cwd: undefined, + }); + + const projectDir = process.cwd(); + const buildGradleFiles = findFilesWithExtensions(projectDir, [ + ".gradle", + "gradle.kts", + ]); + + if (buildGradleFiles.length === 0) { + clack.log.error( + "No Gradle project found. Please run this command from the root of your project.", + ); + return await abort(); + } + + const appFile = await traceStep("Select App File", () => + selectAppFile(buildGradleFiles), + ); + + const projectData = await getOrAskForProjectData(options, "android"); + + if (projectData.spotlight) { + return await abortIfSpotlightNotSupported("Android"); + } + + const { selectedProject, selfHosted, sentryUrl, authToken } = projectData; + + // Ask if user wants to enable Sentry Logs + const enableLogs = await abortIfCancelled( + clack.confirm({ + message: + "Do you want to enable Logs? (See https://docs.sentry.io/platforms/android/logs/)", + }), + ); + Sentry.setTag("enable-logs", enableLogs); + + if (enableLogs) { + clack.log.info( + "Logs will be enabled with default settings. You can send logs using the Sentry.logger() APIs or use one of the integrations: https://docs.sentry.io/platforms/android/logs/#integrations.", + ); + } + + // ======== STEP 1. Add Sentry Gradle Plugin to build.gradle(.kts) ============ + clack.log.step( + `Adding ${chalk.bold("Sentry Gradle plugin")} to your app's ${chalk.cyan( + "build.gradle", + )} file.`, + ); + const pluginAdded = await traceStep("Add Gradle Plugin", () => + addGradlePlugin( + appFile, + selectedProject.organization.slug, + selectedProject.slug, + ), + ); + Sentry.setTag("gradle-plugin-added", pluginAdded); + if (!pluginAdded) { + clack.log.error( + `The Gradle sync failed after adding the ${chalk.bold("Sentry Gradle plugin")} to ${chalk.cyan(appFile)}. Fix the build, or set up the plugin by hand.\nPlease follow the instructions at https://docs.sentry.io/platforms/android/#install`, + ); + return await abort(); + } + + // ======== STEP 2. Configure Sentry SDK via AndroidManifest ============ + clack.log.step( + `Configuring Sentry SDK via ${chalk.cyan("AndroidManifest.xml")}`, + ); + const appDir = path.dirname(appFile); + const manifestFile = path.join(appDir, "src", "main", "AndroidManifest.xml"); + + const manifestUpdated = traceStep("Update Android Manifest", () => + addManifestSnippet( + manifestFile, + selectedProject.keys[0].dsn.public, + enableLogs, + ), + ); + if (!manifestUpdated) { + clack.log.warn( + "Could not configure the Sentry SDK. You'll have to do it manually.\nPlease follow the instructions at https://docs.sentry.io/platforms/android/#configure", + ); + } + Sentry.setTag("android-manifest-updated", manifestUpdated); + + // ======== STEP 3. Patch Main Activity with a test error snippet ============ + clack.log.step( + `Patching ${chalk.bold("Main Activity")} with a test error snippet.`, + ); + const mainActivity = traceStep("Find Main Activity", () => + getMainActivity(manifestFile), + ); + let packageName = mainActivity.packageName; + if (!packageName) { + // if no package name in AndroidManifest, look into gradle script + packageName = getNamespace(appFile); + } + const activityName = mainActivity.activityName; + Sentry.setTag("has-activity-name", !!activityName); + Sentry.setTag("has-package-name", !!packageName); + if (!activityName || !packageName) { + clack.log.error( + "Could not find the Activity with intent action MAIN, or the app's package name. You'll have to finish the setup by hand.\nPlease follow the instructions at https://docs.sentry.io/platforms/android/#verify", + ); + return await abort(); + } + const packageNameStable = packageName; + const activityFile = await traceStep("Find Main Activity Source File", () => + findActivitySourceFile(appDir, packageNameStable, activityName), + ); + + const activityPatched = traceStep("Patch Main Activity", () => + patchMainActivity(activityFile), + ); + if (!activityPatched) { + clack.log.warn( + "Could not patch main activity. You'll have to manually verify the setup.\nPlease follow the instructions at https://docs.sentry.io/platforms/android/#verify", + ); + } + Sentry.setTag("main-activity-patched", activityPatched); + + // ======== STEP 4. Add sentry.properties for the Gradle plugin ============ + clack.log.step( + `Adding the auth token for the ${chalk.bold( + "Sentry Android Gradle plugin", + )} to ${chalk.cyan("sentry.properties")}.`, + ); + + await addSentryCliConfig( + { authToken, url: selfHosted ? sentryUrl : undefined }, + proguardMappingCliSetupConfig, + ); + + // Offer optional project-scoped MCP config for Sentry with org and project scope + await offerProjectScopedMcpConfig( + selectedProject.organization.slug, + selectedProject.slug, + ); + + // Fix mixed line endings caused by inserting LF content into CRLF files (Windows) + fixLineEndings(); + + // ======== OUTRO ======== + const issuesPageLink = selfHosted + ? `${sentryUrl}organizations/${selectedProject.organization.slug}/issues/?project=${selectedProject.id}` + : `https://${selectedProject.organization.slug}.sentry.io/issues/?project=${selectedProject.id}`; + + clack.outro(` +${chalk.greenBright("Successfully installed the Sentry Android SDK!")} + +${chalk.cyan( + `You can validate your setup by launching your application and checking Sentry issues page afterwards +${issuesPageLink}`, +)} + +Check out the SDK documentation for further configuration: +https://docs.sentry.io/platforms/android/ + `); +} + +//find files with the given extension +function findFilesWithExtensions( + dir: string, + extensions: string[], + filesWithExtensions: string[] = [], +): string[] { + const cwd = process.cwd(); + const files = readdirSync(dir, { withFileTypes: true }); + for (const file of files) { + if (file.isDirectory()) { + const childDir = path.join(dir, file.name); + findFilesWithExtensions(childDir, extensions, filesWithExtensions); + } else if (extensions.some((ext) => file.name.endsWith(ext))) { + filesWithExtensions.push(path.relative(cwd, path.join(dir, file.name))); + } + } + return filesWithExtensions; +} diff --git a/packages/cli/src/lib/wizard/android/code-tools.ts b/packages/cli/src/lib/wizard/android/code-tools.ts new file mode 100644 index 000000000..6843412f5 --- /dev/null +++ b/packages/cli/src/lib/wizard/android/code-tools.ts @@ -0,0 +1,182 @@ +/** + * Finds the app's main activity source file and patches it with the Sentry + * import and a test error snippet. + */ + +import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { reportCliError } from "../../error-reporting.js"; +import { clack } from "../utils/clack/prompts.js"; +import chalk from "chalk"; +import { + sentryImport, + sentryImportKt, + testErrorSnippet, + testErrorSnippetKt, +} from "./templates.js"; +import { findFile } from "../../dsn/fs-utils.js"; + +/** + * Looks in src/main/java or src/main/kotlin for the specified {@link packageName} and + * {@link activityName} by concatenating them. For example: + * + * src/ + * main/ + * java/ or kotlin/ + * my.package.name/ + * ui/ + * MainActivity.kt + * + * src/main/java can contain both .java and .kt sources, whilst src/main/kotlin only .kt + * + * @param appDir + * @param packageName + * @param activityName + * @returns path to the Main Activity + */ +export async function findActivitySourceFile( + appDir: string, + packageName: string, + activityName: string, +): Promise { + const javaSrcDir = path.join(appDir, "src", "main", "java"); + let possibleActivityPath; + // A name that starts with a dot or has no dot is relative to the package + // (Android prefixes the package name); otherwise it is fully qualified. + const packageNameParts = + activityName.startsWith(".") || !activityName.includes(".") + ? packageName.split(".") + : []; + const activityNameParts = activityName.split("."); + + if (existsSync(javaSrcDir)) { + possibleActivityPath = await findFile( + path.join(javaSrcDir, ...packageNameParts, ...activityNameParts), + [".kt", ".java"], + ); + } + + if (!possibleActivityPath || !existsSync(possibleActivityPath)) { + const kotlinSrcDir = path.join(appDir, "src", "main", "kotlin"); + if (existsSync(kotlinSrcDir)) { + possibleActivityPath = await findFile( + path.join(kotlinSrcDir, ...packageNameParts, ...activityNameParts), + [".kt"], + ); + } + } + return possibleActivityPath; +} + +/** + * Patches Main Activity with the test error code snippet by the specified path {@link activityFile}. + * Finds activity's `onCreate` method, adds the snippet and necessary imports. + * + * ```kotlin + * import something + * import something.something + * import io.sentry.Sentry <-- this is added by us + * + * override fun onCreate(savedInstanceState: Bundle?) { + * super.onCreate(savedInstanceState) + * // the snippet goes here <-- + * doSomething() + * } + * ``` + * + * @param activityFile + * @returns true if successfully patched, false otherwise + */ +export function patchMainActivity(activityFile: string | undefined): boolean { + if (!activityFile || !existsSync(activityFile)) { + clack.log.warn("No main activity source file found in filesystem."); + reportCliError(new Error("No main activity source file")); + return false; + } + + const activityContent = readFileSync(activityFile, "utf8"); + + if (/import\s+io\.sentry\.Sentry\b(?!\.)/.test(activityContent)) { + // sentry is already configured + clack.log.success( + chalk.greenBright( + `${chalk.bold( + "Main Activity", + )} is already patched with test error snippet.`, + ), + ); + return true; + } + + const importIndex = getLastImportLineLocation(activityContent); + + let newActivityContent; + if (activityFile.endsWith(".kt")) { + newActivityContent = + activityContent.slice(0, importIndex) + + sentryImportKt + + activityContent.slice(importIndex); + } else { + newActivityContent = + activityContent.slice(0, importIndex) + + sentryImport + + activityContent.slice(importIndex); + } + + const onCreateMatch = /super\.onCreate\(.*?\);?/i.exec(newActivityContent); + if (!onCreateMatch) { + clack.log.warn("No onCreate method found in main activity."); + reportCliError(new Error("No onCreate method")); + return false; + } + + const onCreateIndex = onCreateMatch.index + onCreateMatch[0].length; + if (activityFile.endsWith(".kt")) { + newActivityContent = + newActivityContent.slice(0, onCreateIndex) + + testErrorSnippetKt + + newActivityContent.slice(onCreateIndex); + } else { + newActivityContent = + newActivityContent.slice(0, onCreateIndex) + + testErrorSnippet + + newActivityContent.slice(onCreateIndex); + } + writeFileSync(activityFile, newActivityContent, "utf8"); + + clack.log.success( + chalk.greenBright( + `Patched ${chalk.bold( + "Main Activity", + )} with the Sentry test error snippet.`, + ), + ); + + return true; +} + +/** + * Returns the string index of the last import statement in the given code file. + * Works for both Java and Kotlin import statements. + * + * @param sourceCode + * @returns the insert index, or 0 if none found. + */ +export function getLastImportLineLocation(sourceCode: string): number { + const importRegex = /import(?:\sstatic)?\s+[\w.*]+(?: as [\w.]+)?;?/gim; + + let importsMatch = importRegex.exec(sourceCode); + let importIndex = 0; + while (importsMatch) { + importIndex = importsMatch.index + importsMatch[0].length + 1; + importsMatch = importRegex.exec(sourceCode); + } + if (importIndex === 0) { + // No imports: an import must still come after the package declaration. + const packageMatch = /^package\s+[\w.]+;?[ \t]*$/m.exec(sourceCode); + if (packageMatch) { + importIndex = packageMatch.index + packageMatch[0].length + 1; + } + } + return importIndex; +} diff --git a/packages/cli/src/lib/wizard/android/gradle.ts b/packages/cli/src/lib/wizard/android/gradle.ts new file mode 100644 index 000000000..d56168bc2 --- /dev/null +++ b/packages/cli/src/lib/wizard/android/gradle.ts @@ -0,0 +1,260 @@ +/** + * Gradle edits of the Android wizard: picks the app module, adds the Sentry + * Android Gradle plugin and its `sentry {}` block, and reads the namespace. + */ + +import { + appendFileSync, + existsSync, + readFileSync, + writeFileSync, +} from "node:fs"; +import { abortIfCancelled, askForItemSelection } from "../utils/clack/index.js"; +import { + plugin, + pluginKts, + pluginsBlock, + pluginsBlockKts, + sourceContext, + sourceContextKts, +} from "./templates.js"; +import { execute } from "../utils/bash.js"; +import { debug } from "../utils/debug.js"; +import { Sentry } from "../telemetry.js"; +import { clack } from "../utils/clack/prompts.js"; +import chalk from "chalk"; +import { fetchSdkVersion } from "../utils/release-registry.js"; + +/** + * A Gradle project may contain multiple modules, some of them may be applications, some of them may be libraries. + * We are only interested in applications. For example: + * + * myproject/ + * app/ + * lib1/ + * lib2/ + * wearApp/ + * + * In this case^ we are interested in app/ and wearApp/ + * + * @param buildGradleFiles a list of build.gradle(.kts) paths that contain the com.android.application plugin + * @returns the selected project for setting up + */ +export async function selectAppFile( + buildGradleFiles: string[], +): Promise { + const appFiles: string[] = []; + for (const file of buildGradleFiles) { + const text = readFileSync(file, "utf8"); + if (/\(?["']com\.android\.application["']\)?(?!.*\S)/.test(text)) { + appFiles.push(file); + } + } + + if (appFiles.length === 0) { + Sentry.setTag("custom-build-logic", true); + const appFile = await abortIfCancelled( + clack.text({ + message: `Unable to find your app's directory. + Please enter the relative path to your app's build.gradle file from the root project`, + placeholder: "app/build.gradle.kts", + validate(value) { + if (!value.includes(".gradle") || !existsSync(value)) { + return `Not a valid gradle file.`; + } + return undefined; + }, + }), + ); + return appFile; + } + + let appFile: string; + const [onlyAppFile] = appFiles; + if (appFiles.length === 1 && onlyAppFile) { + Sentry.setTag("multiple-projects", false); + appFile = onlyAppFile; + } else { + Sentry.setTag("multiple-projects", true); + appFile = ( + await askForItemSelection( + appFiles, + "Which project do you want to add Sentry to?", + ) + ).value; + } + Sentry.setTag("custom-build-logic", false); + return appFile; +} + +/** + * Patches a build.gradle(.kts) file that contains `com.android.application` plugin. + * There are multiple cases we have to handle here: + * - An existing `plugins {}` block: + * - We just have to add our plugin inside the block + * - No existing `plugins {}` block + * - We have to add the entire block in the beginning of the file, BUT *after imports* + * + * For example (2nd case): + * + * ``` + * import net.ltgt.gradle.errorprone.errorprone + * + * // our plugins block goes here <-- + * plugins { + * id("io.sentry.android.gradle") version "3.12.0" + * } + * + * apply(plugin = "com.android.application") + * + * android { + * ... + * } + * ``` + * + * In the end we run `./gradlew` to verify the config is build-able and not broken. + * + * @param appFile the selected Gradle application project + * @returns true if successfully added Sentry Gradle config, false otherwise + */ +export async function addGradlePlugin( + appFile: string, + orgSlug: string, + projectSlug: string, +): Promise { + const gradleScript = readFileSync(appFile, "utf8"); + + if (/\(?["']io\.sentry\.android\.gradle["']\)?/.test(gradleScript)) { + // sentry gradle plugin is already installed + clack.log.success( + chalk.greenBright( + `${chalk.bold( + "Sentry Gradle plugin", + )} is already added to the project.`, + ), + ); + maybeAddSourceContextConfig(appFile, gradleScript, orgSlug, projectSlug); + return true; + } + + const pluginVersion = await fetchSdkVersion( + "sentry.java.android.gradle-plugin", + ); + const pluginsBlockMatch = /plugins\s*{[^{}]*}/.exec(gradleScript); + let newGradleScript; + if (!pluginsBlockMatch) { + // no "plugins {}" block, we can just add our own after imports + const regex = /^import\s.*$/gm; + let importsMatch = regex.exec(gradleScript); + let insertIndex = 0; + while (importsMatch) { + insertIndex = importsMatch.index + importsMatch[0].length + 1; + importsMatch = regex.exec(gradleScript); + } + + if (appFile.endsWith(".kts")) { + newGradleScript = + gradleScript.slice(0, insertIndex) + + pluginsBlockKts(pluginVersion) + + gradleScript.slice(insertIndex); + } else { + newGradleScript = + gradleScript.slice(0, insertIndex) + + pluginsBlock(pluginVersion) + + gradleScript.slice(insertIndex); + } + } else { + const insertIndex = + pluginsBlockMatch.index + pluginsBlockMatch[0].length - 1; + if (appFile.endsWith(".kts")) { + newGradleScript = + gradleScript.slice(0, insertIndex) + + pluginKts(pluginVersion) + + gradleScript.slice(insertIndex); + } else { + newGradleScript = + gradleScript.slice(0, insertIndex) + + plugin(pluginVersion) + + gradleScript.slice(insertIndex); + } + } + writeFileSync(appFile, newGradleScript, "utf8"); + + maybeAddSourceContextConfig(appFile, newGradleScript, orgSlug, projectSlug); + + const buildSpinner = clack.spinner(); + // cmd.exe can't run `./gradlew`; the Windows wrapper is gradlew.bat. + const gradlew = process.platform === "win32" ? "gradlew.bat" : "./gradlew"; + + buildSpinner.start( + `Running ${gradlew} to verify changes (this may take a few minutes)...`, + ); + + try { + await execute(gradlew); + buildSpinner.stop( + chalk.greenBright( + `${chalk.bold("Sentry Gradle plugin")} added to the project.`, + ), + ); + } catch (error) { + // A failed sync is a problem with the user's build: the caller stops + // the wizard with a message instead of reporting it. + debug(error); + buildSpinner.stop(`${gradlew} failed.`); + return false; + } + + return true; +} + +/** + * Looks for the applications packageName (namespace) in the specified build.gradle(.kts) file. + * + * ``` + * android { + * namespace 'my.package.name' <-- this is what we extract + * + * compileSdkVersion = 31 + * ... + * } + * ``` + * @param appFile + * @returns the packageName(namespace) of the app if available + */ +export function getNamespace(appFile: string): string | undefined { + const gradleScript = readFileSync(appFile, "utf8"); + + const namespaceMatch = /namespace\s*=?\s*['"]([^'"]+)['"]/i.exec( + gradleScript, + ); + if (!namespaceMatch || namespaceMatch.length <= 1) { + clack.log.warn("Unable to determine application package name."); + return undefined; + } + + const namespace = namespaceMatch[1]; + return namespace; +} + +/** + * Adds source context configuration to the gradleScript if `sentry {}` block is not yet configured, + * + * @param appFile + * @param gradleScript + */ +function maybeAddSourceContextConfig( + appFile: string, + gradleScript: string, + orgSlug: string, + projectSlug: string, +) { + if (!/sentry\s*\{[^}]*\}/i.test(gradleScript)) { + // if no sentry {} block is configured, we add our own with source context enabled + if (appFile.endsWith(".kts")) { + appendFileSync(appFile, sourceContextKts(orgSlug, projectSlug), "utf8"); + } else { + appendFileSync(appFile, sourceContext(orgSlug, projectSlug), "utf8"); + } + } +} diff --git a/packages/cli/src/lib/wizard/android/manifest.ts b/packages/cli/src/lib/wizard/android/manifest.ts new file mode 100644 index 000000000..842251e4c --- /dev/null +++ b/packages/cli/src/lib/wizard/android/manifest.ts @@ -0,0 +1,160 @@ +/** + * Reads and patches the app's `AndroidManifest.xml`: adds the Sentry SDK's + * `` options and finds the main activity. + */ + +import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import chalk from "chalk"; +import { reportCliError } from "../../error-reporting.js"; +import { debug } from "../utils/debug.js"; +import { clack } from "../utils/clack/prompts.js"; +import { manifest } from "./templates.js"; +import { childElements, parseXml, type XmlElement } from "../utils/xml.js"; + +/** + * Looks for the closing tag in the manifest and adds the Sentry config after it. + * + * For example: + * ```xml + * + * + * + * ... + * // this is what we add and more + * + * + + + + + + + + + + + + + +${ + enableLogs + ? ' \n ' + : "" +} +`; + +export const sentryImport = `import io.sentry.Sentry;\n`; + +export const sentryImportKt = `import io.sentry.Sentry\n`; + +export const testErrorSnippet = ` + // waiting for view to draw to better represent a captured error with a screenshot + findViewById(android.R.id.content).getViewTreeObserver().addOnGlobalLayoutListener(() -> { + try { + throw new Exception("This app uses Sentry! :)"); + } catch (Exception e) { + Sentry.captureException(e); + } + }); +`; + +export const testErrorSnippetKt = ` + // waiting for view to draw to better represent a captured error with a screenshot + findViewById(android.R.id.content).viewTreeObserver.addOnGlobalLayoutListener { + try { + throw Exception("This app uses Sentry! :)") + } catch (e: Exception) { + Sentry.captureException(e) + } + } +`; + +export const sourceContext = (orgSlug: string, projectSlug: string) => ` + +sentry { + org = "${orgSlug}" + projectName = "${projectSlug}" + + // this will upload your source code to Sentry to show it as part of the stack traces + // disable if you don't want to expose your sources + includeSourceContext = true +} +`; + +export const sourceContextKts = (orgSlug: string, projectSlug: string) => ` + +sentry { + org.set("${orgSlug}") + projectName.set("${projectSlug}") + + // this will upload your source code to Sentry to show it as part of the stack traces + // disable if you don't want to expose your sources + includeSourceContext.set(true) +} +`; diff --git a/packages/cli/src/lib/wizard/apple/snapshots/xml-scan.ts b/packages/cli/src/lib/wizard/apple/snapshots/xml-scan.ts index 5e683ef4c..5edc4e5d6 100644 --- a/packages/cli/src/lib/wizard/apple/snapshots/xml-scan.ts +++ b/packages/cli/src/lib/wizard/apple/snapshots/xml-scan.ts @@ -8,42 +8,17 @@ * element it extracts not to nest inside itself (true for `TestAction`). */ +import { decodeXmlEntities } from "../../utils/xml.js"; + /** Matches comments, CDATA sections, and `` / `` declarations. */ const IGNORED_MARKUP_RE = /||<[?!][^>]*>/g; -/** The five predefined XML entities plus numeric character references. */ -const ENTITY_RE = /&(?:#(\d+)|#x([\da-f]+)|(amp|lt|gt|quot|apos));/gi; - -const NAMED_ENTITIES: Record = { - amp: "&", - lt: "<", - gt: ">", - quot: '"', - apos: "'", -}; - /** Escape `value` for use inside a regular expression. */ function escapeRegExp(value: string): string { return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } -/** Decode XML entity and character references in `value`. */ -export function decodeXmlEntities(value: string): string { - return value.replace( - ENTITY_RE, - (match, decimal?: string, hex?: string, named?: string) => { - if (decimal) { - return String.fromCodePoint(Number.parseInt(decimal, 10)); - } - if (hex) { - return String.fromCodePoint(Number.parseInt(hex, 16)); - } - return NAMED_ENTITIES[named?.toLowerCase() ?? ""] ?? match; - }, - ); -} - /** * `xml` without comments, CDATA sections and declarations. Strips until * nothing changes, so removing one span can't leave another behind, such as diff --git a/packages/cli/src/lib/wizard/flutter/code-tools.ts b/packages/cli/src/lib/wizard/flutter/code-tools.ts new file mode 100644 index 000000000..6ea8a0bbc --- /dev/null +++ b/packages/cli/src/lib/wizard/flutter/code-tools.ts @@ -0,0 +1,491 @@ +/** + * Edits of a Flutter project: adds the Sentry packages and plugin options to + * `pubspec.yaml` and the SDK init to `main.dart`, as string edits that keep + * the user's formatting, and writes the plugin's `sentry.properties`. + */ + +import { + appendFileSync, + existsSync, + readFileSync, + readdirSync, + statSync, + writeFileSync, + type Stats, +} from "node:fs"; +import path from "node:path"; +import { reportCliError } from "../../error-reporting.js"; +import { WizardExitError } from "../../errors.js"; +import { clack } from "../utils/clack/prompts.js"; +import chalk from "chalk"; +import { + sentryImport, + pubspecOptions, + sentryProperties, + initSnippet, + sessionReplaySampleRate, + sessionReplayOnErrorSampleRate, +} from "./templates.js"; +import { featureSelectionPrompt } from "../utils/clack/index.js"; + +/** + * Recursively finds a file per name in subfolders. + * @param dir - The directory to start searching. + * @param name - The name of the file including path extension. + * @returns The path to the main.dart file or null if not found. + */ +export function findFile(dir: string, name: string): string | null { + if (!existsSync(dir)) { + return null; + } + const files: string[] = readdirSync(dir); + + for (const file of files) { + const fullPath: string = path.join(dir, file); + const stats: Stats = statSync(fullPath); + + if (stats.isDirectory()) { + const result: string | null = findFile(fullPath, name); + if (result) { + return result; + } + } else if (file === name) { + return fullPath; + } + } + + return null; +} + +export function patchPubspec( + pubspecFile: string | null, + sentryDartFlutterVersion: string, + sentryDartPluginVersion: string, + project: string, + org: string, +): boolean { + try { + if (!pubspecFile) { + throw new Error("pubspec.yaml is not provided or invalid."); + } + + let pubspecContent = readFileSync(pubspecFile, "utf8"); + + if (!/^[ \t]*sentry_flutter:/m.test(pubspecContent)) { + pubspecContent = addToSection( + pubspecContent, + "dependencies", + getDependenciesLocation(pubspecContent), + ` sentry_flutter: ${sentryDartFlutterVersion}\n`, + ); + + clack.log.success( + chalk.greenBright( + `${chalk.bold("sentry_flutter")} added to pubspec.yaml`, + ), + ); + } else { + clack.log.success( + chalk.greenBright( + `${chalk.bold("sentry_flutter")} is already included in pubspec.yaml`, + ), + ); + } + + if (!/^[ \t]*sentry_dart_plugin:/m.test(pubspecContent)) { + pubspecContent = addToSection( + pubspecContent, + "dev_dependencies", + getDevDependenciesLocation(pubspecContent), + ` sentry_dart_plugin: ${sentryDartPluginVersion}\n`, + ); + + clack.log.success( + chalk.greenBright( + `${chalk.bold("sentry_dart_plugin")} added to pubspec.yaml`, + ), + ); + } else { + clack.log.success( + chalk.greenBright( + `${chalk.bold( + "sentry_dart_plugin", + )} is already included in pubspec.yaml`, + ), + ); + } + + if (!/^sentry:/m.test(pubspecContent)) { + pubspecContent += "\n"; + pubspecContent += pubspecOptions(project, org); + + clack.log.success( + chalk.greenBright( + `${chalk.bold("sentry plugin configuration")} added to pubspec.yaml`, + ), + ); + } else { + clack.log.success( + chalk.greenBright( + `${chalk.bold( + "sentry plugin configuration", + )} is already included in pubspec.yaml`, + ), + ); + } + + writeFileSync(pubspecFile, pubspecContent, "utf8"); + + return true; + } catch (error) { + clack.log.warn(`Failed to read/write ${chalk.cyan("pubspec.yaml")} file.`); + reportCliError(error); + return false; + } +} + +export function addProperties(pubspecFile: string | null, authToken: string) { + try { + if (!pubspecFile) { + throw new Error("pubspec.yaml is not provided or invalid."); + } + + const pubspecDir = path.dirname(pubspecFile); + const sentryPropertiesFileName = "sentry.properties"; + const sentryPropertiesFile = path.join( + pubspecDir, + sentryPropertiesFileName, + ); + const sentryPropertiesContent = sentryProperties(authToken); + + writeFileSync(sentryPropertiesFile, sentryPropertiesContent, "utf8"); + + const gitignoreFile = path.join(pubspecDir, ".gitignore"); + if (existsSync(gitignoreFile)) { + appendFileSync(gitignoreFile, `\n${sentryPropertiesFileName}\n`); + } else { + writeFileSync(gitignoreFile, `${sentryPropertiesFileName}\n`, "utf8"); + } + return true; + } catch (error) { + clack.log.warn(`Failed to read/write ${chalk.cyan("pubspec.yaml")} file.`); + reportCliError(error); + return false; + } +} + +export async function patchMain( + mainFile: string | null, + dsn: string, +): Promise { + // No main.dart is an expected project state: the caller shows the + // snippet to add by hand. + if (!mainFile) { + return false; + } + try { + let mainContent = readFileSync(mainFile, "utf8"); + if (matchesCode(mainContent, /\bSentryFlutter\.init\(/g)) { + // sentry is already configured + clack.log.success( + chalk.greenBright( + `${chalk.bold("main.dart")} already has Sentry configured.`, + ), + ); + return true; + } + + const selectedFeatures = await featureSelectionPrompt([ + { + id: "tracing", + prompt: `Do you want to enable ${chalk.bold( + "Tracing", + )} to track the performance of your application?`, + enabledHint: "recommended", + }, + { + id: "replay", + prompt: `Do you want to enable ${chalk.bold( + "Session Replay", + )} to record user interactions and debug issues?`, + enabledHint: "recommended", + }, + ] as const); + mainContent = patchMainContent(dsn, mainContent, selectedFeatures); + if (!mainContent.includes("SentryFlutter.init(")) { + // No `runApp(...);` to wrap: the caller shows the snippet to add by hand. + return false; + } + + if (selectedFeatures.replay) { + clack.log.info( + `Session Replay will be enabled with default settings (replaysSessionSampleRate: ${sessionReplaySampleRate}, replaysOnErrorSampleRate: ${sessionReplayOnErrorSampleRate}).`, + ); + clack.log.message( + "By default, all text content, images, and webviews will be masked for privacy. You can customize this in your code later.", + ); + } + + writeFileSync(mainFile, mainContent, "utf8"); + + clack.log.success( + chalk.greenBright( + `Patched ${chalk.bold( + "main.dart", + )} with the Sentry setup and test error snippet.`, + ), + ); + + return true; + } catch (error) { + if (error instanceof WizardExitError) { + throw error; + } + clack.log.warn(`Failed to read/write ${chalk.cyan("main.dart")} file.`); + reportCliError(error); + return false; + } +} + +export function patchMainContent( + dsn: string, + mainContent: string, + selectedFeatures: { + tracing: boolean; + replay: boolean; + }, +): string { + if (!matchesCode(mainContent, SENTRY_IMPORT)) { + const importIndex = getLastImportLineLocation(mainContent); + mainContent = + mainContent.slice(0, importIndex) + + sentryImport + + mainContent.slice(importIndex); + } + + mainContent = arrowMainToBlock(mainContent); + + mainContent = replaceRunAppCalls(mainContent, (runAppArgs) => + initSnippet(dsn, selectedFeatures, runAppArgs), + ); + + // Make the `main` function async if it's not already + const source = mainContent; + mainContent = source.replace( + /(?:Future|void)\s+main\s*\(([^)]*)\)\s*\{/g, + (match, params: string, offset: number) => + isCode(source, offset) ? `Future main(${params}) async {` : match, + ); + + return mainContent; +} + +/** + * Rewrite an expression-bodied `main` (`void main() => runApp(...);`) as a + * block, so the init snippet's statements fit in it. + */ +function arrowMainToBlock(source: string): string { + const arrowMains = + /(?:Future|void)\s+main\s*\(([^)]*)\)\s*(?:async\s*)?=>/g; + let arrowMain = arrowMains.exec(source); + while (arrowMain && !isCode(source, arrowMain.index)) { + arrowMain = arrowMains.exec(source); + } + if (!arrowMain) { + return source; + } + const bodyStart = arrowMain.index + arrowMain[0].length; + const bodyEnd = scanCode( + source, + bodyStart, + (char, depth) => char === ";" && depth === 0, + ); + if (bodyEnd === -1) { + return source; + } + const params = arrowMain[1] ?? ""; + const body = source.slice(bodyStart, bodyEnd).trim(); + return `${source.slice(0, arrowMain.index)}Future main(${params}) async {\n ${body};\n}${source.slice(bodyEnd + 1)}`; +} + +/** + * Replace each `runApp(...);` statement with `replace()`, + * matching the call's own closing parenthesis. + */ +function replaceRunAppCalls( + source: string, + replace: (runAppArgs: string) => string, +): string { + const runAppCall = /\brunApp\s*\(/g; + let result = ""; + let cursor = 0; + for ( + let match = runAppCall.exec(source); + match; + match = runAppCall.exec(source) + ) { + if (!isCode(source, match.index)) { + continue; + } + const open = match.index + match[0].length - 1; + const close = scanCode( + source, + open, + (char, depth) => char === ")" && depth === 0, + ); + if (close === -1) { + break; + } + const semicolon = /^\s*;/.exec(source.slice(close + 1)); + if (!semicolon) { + continue; + } + result += + source.slice(cursor, match.index) + + replace(source.slice(open + 1, close)); + cursor = close + 1 + semicolon[0].length; + runAppCall.lastIndex = cursor; + } + return result + source.slice(cursor); +} + +const SENTRY_IMPORT = + /import\s+['"]package:sentry_flutter\/sentry_flutter\.dart['"]/g; + +/** Whether the global `pattern` matches outside every comment and string. */ +function matchesCode(source: string, pattern: RegExp): boolean { + pattern.lastIndex = 0; + for (let match = pattern.exec(source); match; match = pattern.exec(source)) { + if (isCode(source, match.index)) { + return true; + } + } + return false; +} + +/** Whether `index` is outside every comment and string in `source`. */ +function isCode(source: string, index: number): boolean { + return scanCode(source, 0, (_char, _depth, i) => i >= index) === index; +} + +/** + * Index of the first character from `start` where `stop(char, depth, index)` holds, + * where `depth` counts open brackets after `char`. Skips strings and comments. + * Returns -1 when there is none, or when a bracket closes below `start`'s level. + */ +function scanCode( + source: string, + start: number, + stop: (char: string, depth: number, index: number) => boolean, +): number { + let depth = 0; + for (let i = start; i < source.length; i++) { + const char = source.charAt(i); + if (char === "'" || char === '"') { + i = endOfString(source, i); + continue; + } + if (source.startsWith("//", i)) { + i = source.indexOf("\n", i); + if (i === -1) { + return -1; + } + continue; + } + if (source.startsWith("/*", i)) { + i = source.indexOf("*/", i); + if (i === -1) { + return -1; + } + i += 1; + continue; + } + if ("([{".includes(char)) { + depth++; + } else if (")]}".includes(char)) { + depth--; + } + if (stop(char, depth, i)) { + return i; + } + if (depth < 0) { + return -1; + } + } + return -1; +} + +/** Index of the closing quote of the Dart string starting at `start`. */ +function endOfString(source: string, start: number): number { + const quote = source.charAt(start); + const delimiter = source.startsWith(quote.repeat(3), start) + ? quote.repeat(3) + : quote; + for (let i = start + delimiter.length; i < source.length; i++) { + if (source.charAt(i) === "\\") { + i++; + } else if (source.startsWith(delimiter, i)) { + return i + delimiter.length - 1; + } + } + return source.length; +} + +export function getLastImportLineLocation(sourceCode: string): number { + const importRegex = /import\s+['"].*['"].*;/gim; + let importIndex = 0; + for ( + let match = importRegex.exec(sourceCode); + match; + match = importRegex.exec(sourceCode) + ) { + if (isCode(sourceCode, match.index)) { + importIndex = match.index + match[0].length + 1; + } + } + return importIndex; +} + +/** Offset of the line after the `dependencies:` header, or -1 without one. */ +export function getDependenciesLocation(sourceCode: string): number { + const dependencyRegex = /^dependencies:[ \t]*(?:#[^\r\n]*)?\r?$/gim; + return getLastReqExpLocation(sourceCode, dependencyRegex); +} + +/** Offset of the line after the `dev_dependencies:` header, or -1 without one. */ +export function getDevDependenciesLocation(sourceCode: string): number { + const dependencyRegex = /^dev_dependencies:[ \t]*(?:#[^\r\n]*)?\r?$/gim; + return getLastReqExpLocation(sourceCode, dependencyRegex); +} + +// Helper + +/** + * Insert `entry` at `index`, the start of the `section` body, or append the + * section with `entry` when `index` is -1 (the pubspec has no such section). + */ +function addToSection( + content: string, + section: string, + index: number, + entry: string, +): string { + if (index === -1) { + const separator = content.endsWith("\n") || content === "" ? "" : "\n"; + return `${content}${separator}\n${section}:\n${entry}`; + } + if (index > content.length) { + return `${content}\n${entry}`; + } + return content.slice(0, index) + entry + content.slice(index); +} + +function getLastReqExpLocation(sourceCode: string, regExp: RegExp): number { + let match = regExp.exec(sourceCode); + let importIndex = -1; + while (match) { + importIndex = match.index + match[0].length + 1; + match = regExp.exec(sourceCode); + } + return importIndex; +} diff --git a/packages/cli/src/lib/wizard/flutter/flutter-wizard.ts b/packages/cli/src/lib/wizard/flutter/flutter-wizard.ts new file mode 100644 index 000000000..6ea6e26da --- /dev/null +++ b/packages/cli/src/lib/wizard/flutter/flutter-wizard.ts @@ -0,0 +1,210 @@ +/** + * The Flutter wizard: adds `sentry_flutter` and `sentry_dart_plugin` to + * `pubspec.yaml`, writes the plugin's `sentry.properties` with the auth + * token, and patches `main.dart` with `SentryFlutter.init` and a test error. + * Ported from sentry-wizard's `src/flutter`. + */ + +import { existsSync } from "node:fs"; +import path from "node:path"; +import chalk from "chalk"; +import { Sentry, traceStep, withTelemetry } from "../telemetry.js"; +import { abortIfSpotlightNotSupported } from "../utils/abort-if-sportlight-not-supported.js"; +import { + abort, + confirmContinueIfNoOrDirtyGitRepo, + getOrAskForProjectData, + printWelcome, + showCopyPasteInstructions, +} from "../utils/clack/index.js"; +import { offerProjectScopedMcpConfig } from "../utils/clack/mcp-config.js"; +import { clack } from "../utils/clack/prompts.js"; +import { fixLineEndings } from "../utils/line-endings.js"; +import { fetchSdkVersion } from "../utils/release-registry.js"; +import type { WizardOptions } from "../utils/types.js"; +import { + addProperties, + findFile, + patchMain, + patchPubspec, +} from "./code-tools.js"; +import { initSnippetColored, pubspecSnippetColored } from "./templates.js"; + +/** Docs on how the Sentry Dart plugin reads its auth token. */ +const DART_PLUGIN_AUTH_TOKEN_DOCS = + "https://docs.sentry.io/platforms/dart/guides/flutter/debug-symbols/dart-plugin/#set-your-auth-token"; + +/** Run the Flutter wizard in its telemetry span. */ +export async function runFlutterWizard(options: WizardOptions): Promise { + return await withTelemetry( + { + enabled: options.telemetryEnabled, + integration: "flutter", + wizardOptions: options, + }, + () => runFlutterWizardWithTelemetry(options), + ); +} + +async function runFlutterWizardWithTelemetry( + options: WizardOptions, +): Promise { + printWelcome({ + wizardName: "Sentry Flutter Wizard", + }); + + await confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: options.ignoreGitChanges, + cwd: undefined, + }); + + const projectData = await getOrAskForProjectData(options, "flutter"); + + if (projectData.spotlight) { + return await abortIfSpotlightNotSupported("Flutter"); + } + + const { selectedProject, selfHosted, sentryUrl, authToken } = projectData; + + const projectDir = process.cwd(); + const pubspecFile = path.join(projectDir, "pubspec.yaml"); + if (!existsSync(pubspecFile)) { + clack.log.error( + `Could not find ${chalk.cyan( + "pubspec.yaml", + )}. Make sure you run the wizard in the projects root folder.`, + ); + return await abort(); + } + + // ======== STEP 1. Add sentry_flutter and sentry_dart_plugin to pubspec.yaml ============ + + clack.log.step( + `Adding ${chalk.bold("Sentry")} to your apps ${chalk.cyan( + "pubspec.yaml", + )} file.`, + ); + + const flutterVersion = await fetchSdkVersion("sentry.dart.flutter"); + const flutterVersionOrAny = flutterVersion ? `^${flutterVersion}` : "any"; + + const pluginVersion = await fetchSdkVersion("sentry.dart.plugin"); + const pluginVersionOrAny = pluginVersion ? `^${pluginVersion}` : "any"; + + const pubspecPatched = traceStep("Patch pubspec.yaml", () => + patchPubspec( + pubspecFile, + flutterVersionOrAny, + pluginVersionOrAny, + selectedProject.slug, + selectedProject.organization.slug, + ), + ); + if (!pubspecPatched) { + clack.log.warn( + `Could not patch ${chalk.cyan( + "pubspec.yaml", + )}. Add the dependencies to it.`, + ); + await showCopyPasteInstructions({ + filename: "pubspec.yaml", + codeSnippet: pubspecSnippetColored( + flutterVersionOrAny, + pluginVersionOrAny, + selectedProject.slug, + selectedProject.organization.slug, + ), + hint: "This ensures the Sentry SDK and plugin can be imported.", + }); + } + Sentry.setTag("pubspec-patched", pubspecPatched); + + // ======== STEP 2. Add sentry.properties with auth token ============ + + const propertiesAdded = traceStep("Add sentry.properties", () => + addProperties(pubspecFile, authToken), + ); + if (!propertiesAdded) { + clack.log.warn( + `We could not add ${chalk.cyan( + "sentry.properties", + )} file in your project directory in order to provide an auth token for the Sentry Dart plugin. You'll have to add it manually, or you can set the SENTRY_AUTH_TOKEN environment variable instead. See ${DART_PLUGIN_AUTH_TOKEN_DOCS} for more information.`, + ); + } else { + clack.log.info( + `Created a ${chalk.cyan( + "sentry.properties", + )} file in your project directory to provide an auth token for the Sentry Dart plugin. +It was also added to your ${chalk.cyan(".gitignore")} file. +Set the ${chalk.cyan( + "SENTRY_AUTH_TOKEN", + )} environment variable in your CI environment. See ${DART_PLUGIN_AUTH_TOKEN_DOCS} for more information.`, + ); + } + Sentry.setTag("sentry-properties-added", propertiesAdded); + + // ======== STEP 3. Patch main.dart with setup and a test error snippet ============ + + clack.log.step( + `Next, the wizard will patch your ${chalk.cyan( + "main.dart", + )} file with the SDK init and a test error snippet.`, + ); + + const mainFile = findFile(`${projectDir}/lib`, "main.dart"); + const dsn = selectedProject.keys[0].dsn.public; + const mainPatched = await traceStep("Patch main.dart", () => + patchMain(mainFile, dsn), + ); + if (!mainPatched) { + clack.log.warn( + `Could not patch ${chalk.cyan( + "main.dart", + )} file. Place the following code snippet within the apps main function.`, + ); + await showCopyPasteInstructions({ + filename: "main.dart", + codeSnippet: initSnippetColored(dsn), + hint: "This ensures the Sentry SDK is ready to capture errors.", + }); + } + Sentry.setTag("main-patched", mainPatched); + + // ======== OUTRO ======== + + // Offer optional project-scoped MCP config for Sentry with org and project scope + await offerProjectScopedMcpConfig( + selectedProject.organization.slug, + selectedProject.slug, + ); + + // Fix mixed line endings caused by inserting LF content into CRLF files (Windows) + fixLineEndings(); + + const issuesPageLink = selfHosted + ? `${sentryUrl}organizations/${selectedProject.organization.slug}/issues/?project=${selectedProject.id}` + : `https://${selectedProject.organization.slug}.sentry.io/issues/?project=${selectedProject.id}`; + + const testStep = mainPatched + ? "to test the setup - we've added a test error that will trigger on app start" + : "after adding the snippet above to check the setup"; + + clack.outro(`${chalk.greenBright( + "Successfully installed the Sentry Flutter SDK!", + )} + + ${chalk.cyan("Next steps:")} + 1. Run ${chalk.bold("flutter run")} ${testStep} + 2. For production builds, run ${chalk.bold( + "flutter build apk --obfuscate --split-debug-info=build/debug-info", + )} (or ios/macos) then ${chalk.bold( + "flutter pub run sentry_dart_plugin", + )} to upload debug symbols + 3. View your ${mainPatched ? "test error" : "errors"} and transaction data at ${issuesPageLink} + + ${chalk.cyan("Learn more:")} + - Debug Symbols: https://docs.sentry.io/platforms/dart/guides/flutter/debug-symbols/ + - Performance Monitoring: https://docs.sentry.io/platforms/dart/guides/flutter/performance/ + - Integrations: https://docs.sentry.io/platforms/dart/guides/flutter/integrations/ + `); +} diff --git a/packages/cli/src/lib/wizard/flutter/templates.ts b/packages/cli/src/lib/wizard/flutter/templates.ts new file mode 100644 index 000000000..bf59160dc --- /dev/null +++ b/packages/cli/src/lib/wizard/flutter/templates.ts @@ -0,0 +1,111 @@ +/** + * Code and config snippets the Flutter wizard writes or shows. + */ + +import { makeCodeSnippet } from "../utils/clack/index.js"; + +export const sentryImport = `import 'package:sentry_flutter/sentry_flutter.dart';\n`; +export const sessionReplaySampleRate = 0.1; +export const sessionReplayOnErrorSampleRate = 1.0; + +export function pubspecOptions(project: string, org: string): string { + return `sentry: + upload_debug_symbols: true + upload_source_maps: true + project: ${project} + org: ${org} +`; +} + +export function sentryProperties(authToken: string): string { + return `auth_token=${authToken}`; +} + +export function initSnippet( + dsn: string, + selectedFeaturesMap: { + tracing: boolean; + replay: boolean; + }, + runApp: string, +): string { + let snippet = `await SentryFlutter.init( + (options) { + options.dsn = '${dsn}'; + // Adds request headers and IP for users, for more info visit: + // https://docs.sentry.io/platforms/dart/guides/flutter/data-management/data-collected/ + options.sendDefaultPii = true;`; + + if (selectedFeaturesMap.tracing) { + snippet += ` + // Set tracesSampleRate to 1.0 to capture 100% of transactions for tracing. + // We recommend adjusting this value in production. + options.tracesSampleRate = 1.0;`; + } + + if (selectedFeaturesMap.replay) { + snippet += ` + // Configure Session Replay + options.replay.sessionSampleRate = ${ + sessionReplaySampleRate % 1 === 0 + ? `${sessionReplaySampleRate}.0` + : sessionReplaySampleRate + }; + options.replay.onErrorSampleRate = ${ + sessionReplayOnErrorSampleRate % 1 === 0 + ? `${sessionReplayOnErrorSampleRate}.0` + : sessionReplayOnErrorSampleRate + };`; + } + + snippet += ` + }, + appRunner: () => runApp(SentryWidget(child: ${runApp})), + ); + // TODO: Remove this line after sending the first sample event to sentry. + await Sentry.captureException(StateError('This is a sample exception.'));`; + + return snippet; +} + +export function pubspecSnippetColored( + sentryVersion: string, + pluginVersion: string, + project: string, + org: string, +): string { + const snippet = `dependencies: + sentry_flutter: ${sentryVersion} + +dev_dependencies: + sentry_dart_plugin: ${pluginVersion} + +${pubspecOptions(project, org)}`; + + return makeCodeSnippet(true, (_unchanged, plus, _minus) => { + return plus(snippet); + }); +} + +export function initSnippetColored(dsn: string): string { + const snippet = `import 'package:sentry_flutter/sentry_flutter.dart'; + +Future main() async { + await SentryFlutter.init( + (options) { + options.dsn = '${dsn}'; + // Adds request headers and IP for users, for more info visit: + // https://docs.sentry.io/platforms/dart/guides/flutter/data-management/data-collected/ + options.sendDefaultPii = true; + + // Set tracesSampleRate to 1.0 to capture 100% of transactions for tracing. + // We recommend adjusting this value in production. + options.tracesSampleRate = 1.0; + }, + appRunner: () => runApp(SentryWidget(child: YourApp())), + ); +}`; + return makeCodeSnippet(true, (_unchanged, plus, _minus) => { + return plus(snippet); + }); +} diff --git a/packages/cli/src/lib/wizard/run.ts b/packages/cli/src/lib/wizard/run.ts index 7adbdd846..eaa33e567 100644 --- a/packages/cli/src/lib/wizard/run.ts +++ b/packages/cli/src/lib/wizard/run.ts @@ -56,6 +56,14 @@ const WIZARD_RUNNERS: Partial> = { const { runNextjsWizard } = await import("./nextjs/nextjs-wizard.js"); await runNextjsWizard(options); }, + android: async (options) => { + const { runAndroidWizard } = await import("./android/android-wizard.js"); + await runAndroidWizard(options); + }, + flutter: async (options) => { + const { runFlutterWizard } = await import("./flutter/flutter-wizard.js"); + await runFlutterWizard(options); + }, ios: async (options) => { const { runAppleWizard } = await import("./apple/apple-wizard.js"); await runAppleWizard(options); @@ -74,6 +82,11 @@ const WIZARD_RUNNERS: Partial> = { }, }; +/** Whether `integration` has a flow in this version. */ +export function hasWizardRunner(integration: WizardIntegration): boolean { + return integration in WIZARD_RUNNERS; +} + /** What `sentry wizard` passes to {@link runWizard}. */ export type RunWizardArgs = { /** The integration to set up; prompts for one when unset. */ @@ -108,7 +121,7 @@ async function askForIntegration(): Promise { const integration = await abortIfCancelled( clack.select({ message: "What do you want to set up?", - options: WIZARD_INTEGRATIONS.filter(({ id }) => id in WIZARD_RUNNERS).map( + options: WIZARD_INTEGRATIONS.filter(({ id }) => hasWizardRunner(id)).map( ({ id, label }) => ({ value: id, label }), ), }), diff --git a/packages/cli/src/lib/wizard/utils/line-endings.ts b/packages/cli/src/lib/wizard/utils/line-endings.ts new file mode 100644 index 000000000..c3a3997a0 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/line-endings.ts @@ -0,0 +1,57 @@ +/** + * Fixes mixed line endings in files modified by the wizard. + * + * When the wizard reads a CRLF file and inserts content with hardcoded \n, + * the result is mixed line endings. {@link fixLineEndings} detects files with + * CRLF and normalizes all line endings to CRLF. + */ + +import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { getUncommittedOrUntrackedFilePaths } from "./git.js"; + +const TEXT_EXTENSIONS = new Set([ + ".dart", + ".yaml", + ".yml", + ".properties", + ".java", + ".kt", + ".xml", + ".gradle", + ".kts", + ".gitignore", + ".json", +]); + +/** + * Normalize every changed text file that has a CRLF to CRLF only. Call it at + * the end of a wizard run, like `runPrettierIfInstalled()`. + */ +export function fixLineEndings(): void { + const files = getUncommittedOrUntrackedFilePaths().filter(Boolean); + + for (const file of files) { + const filePath = path.resolve(file); + + if (!existsSync(filePath) || !statSync(filePath).isFile()) { + continue; + } + + const ext = path.extname(filePath).toLowerCase(); + const basename = path.basename(filePath); + if (!TEXT_EXTENSIONS.has(ext) && !TEXT_EXTENSIONS.has(basename)) { + continue; + } + + const content = readFileSync(filePath, "utf8"); + + if (!content.includes("\r\n")) { + continue; + } + + // File has CRLF — normalize all line endings to CRLF + const normalized = content.replace(/\r\n/g, "\n").replace(/\n/g, "\r\n"); + writeFileSync(filePath, normalized, "utf8"); + } +} diff --git a/packages/cli/src/lib/wizard/utils/release-registry.ts b/packages/cli/src/lib/wizard/utils/release-registry.ts new file mode 100644 index 000000000..380d7d785 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/release-registry.ts @@ -0,0 +1,35 @@ +/** + * Latest SDK versions from Sentry's release registry, which the wizards use + * to pin the packages and plugins they add. + */ + +import { debug } from "./debug.js"; + +const registryUrl = "https://release-registry.services.sentry.io"; + +/** + * The latest released version of `sdk` (a registry key such as + * `sentry.dart.flutter`), or `undefined` when the registry can't be reached + * or doesn't list it. + */ +export async function fetchSdkVersion( + sdk: string, +): Promise { + try { + const response = await fetch(`${registryUrl}/sdks`); + if (!response.ok) { + debug(`Release registry responded with ${response.status}.`); + return undefined; + } + const data = (await response.json()) as Record< + string, + { version?: unknown } | undefined + >; + const version = data[sdk]?.version; + return typeof version === "string" ? version : undefined; + } catch (error) { + // Callers fall back to a default version, so a failed lookup is fine. + debug("Failed to fetch latest version from release registry.", error); + } + return undefined; +} diff --git a/packages/cli/src/lib/wizard/utils/xml.ts b/packages/cli/src/lib/wizard/utils/xml.ts new file mode 100644 index 000000000..f41f68855 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/xml.ts @@ -0,0 +1,156 @@ +/** + * A minimal XML reader for the wizards. + * + * It parses elements and attributes into a tree and skips everything else: + * text, comments, CDATA, processing instructions, and the doctype. It never + * writes XML; wizards edit files as strings to keep their formatting. The + * Android wizard uses it to read `AndroidManifest.xml`. + */ + +/** One XML element: its tag name, attributes, and child elements. */ +export type XmlElement = { + name: string; + attributes: Record; + children: XmlElement[]; +}; + +const NAME_PATTERN = /[A-Za-z_:][\w.:-]*/y; +const ATTRIBUTE_PATTERN = + /\s*([A-Za-z_:][\w.:-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/y; + +const NAMED_ENTITIES: Record = { + amp: "&", + lt: "<", + gt: ">", + quot: '"', + apos: "'", +}; + +/** Replace the predefined and numeric character references in `value`. */ +export function decodeXmlEntities(value: string): string { + return value.replace( + /&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, + (match, entity: string) => { + if (entity.startsWith("#x") || entity.startsWith("#X")) { + return String.fromCodePoint(Number.parseInt(entity.slice(2), 16)); + } + if (entity.startsWith("#")) { + return String.fromCodePoint(Number.parseInt(entity.slice(1), 10)); + } + return NAMED_ENTITIES[entity] ?? match; + }, + ); +} + +/** Index just past `terminator` from `from`, or throw when it never comes. */ +function skipPast(xml: string, from: number, terminator: string): number { + const end = xml.indexOf(terminator, from); + if (end === -1) { + throw new Error(`Malformed XML: missing "${terminator}".`); + } + return end + terminator.length; +} + +/** + * Parse `xml` and return its root element. + * + * @throws {Error} When the document has no root element, or a tag is + * malformed or left unclosed + */ +export function parseXml(xml: string): XmlElement { + const root: XmlElement = { name: "", attributes: {}, children: [] }; + const stack: XmlElement[] = [root]; + let index = 0; + + while (index < xml.length) { + const tagStart = xml.indexOf("<", index); + if (tagStart === -1) { + break; + } + + if (xml.startsWith(""); + continue; + } + if (xml.startsWith(""); + continue; + } + if (xml.startsWith(""); + continue; + } + if (xml.startsWith(""); + continue; + } + + const parent = stack.at(-1); + if (!parent) { + throw new Error("Malformed XML: unbalanced tags."); + } + + if (xml.startsWith(".`); + } + stack.pop(); + index = skipPast(xml, NAME_PATTERN.lastIndex, ">"); + continue; + } + + NAME_PATTERN.lastIndex = tagStart + 1; + const name = NAME_PATTERN.exec(xml)?.[0]; + if (!name) { + throw new Error("Malformed XML: tag without a name."); + } + const element: XmlElement = { name, attributes: {}, children: [] }; + let cursor = NAME_PATTERN.lastIndex; + + for (;;) { + ATTRIBUTE_PATTERN.lastIndex = cursor; + const attribute = ATTRIBUTE_PATTERN.exec(xml); + if (!attribute) { + break; + } + const [, attributeName = "", doubleQuoted, singleQuoted] = attribute; + element.attributes[attributeName] = decodeXmlEntities( + doubleQuoted ?? singleQuoted ?? "", + ); + cursor = ATTRIBUTE_PATTERN.lastIndex; + } + + const tagEnd = /\s*(\/?)>/y; + tagEnd.lastIndex = cursor; + const end = tagEnd.exec(xml); + if (!end) { + throw new Error(`Malformed XML: invalid <${name}> tag.`); + } + parent.children.push(element); + if (!end[1]) { + stack.push(element); + } + index = tagEnd.lastIndex; + } + + if (stack.length > 1) { + throw new Error(`Malformed XML: <${stack.at(-1)?.name}> is not closed.`); + } + const [documentElement] = root.children; + if (!documentElement || root.children.length > 1) { + throw new Error("Malformed XML: expected exactly one root element."); + } + return documentElement; +} + +/** The direct children of `element` named `name`. */ +export function childElements( + element: XmlElement | undefined, + name: string, +): XmlElement[] { + return element?.children.filter((child) => child.name === name) ?? []; +} diff --git a/packages/cli/test/commands/wizard.test.ts b/packages/cli/test/commands/wizard.test.ts index 3705740bb..4a44c6815 100644 --- a/packages/cli/test/commands/wizard.test.ts +++ b/packages/cli/test/commands/wizard.test.ts @@ -25,6 +25,7 @@ import { import type { SentryContext } from "../../src/context.js"; import { buildCommand } from "../../src/lib/command.js"; import { ValidationError, WizardExitError } from "../../src/lib/errors.js"; +import { hasWizardRunner, INTEGRATION_IDS } from "../../src/lib/wizard/run.js"; import type { Writer } from "../../src/types/index.js"; import { loadCommand, useTestConfigDir } from "../helpers.js"; @@ -242,11 +243,16 @@ describe("sentry wizard", () => { }, ); - test("reports an integration this version can't set up yet", async () => { - await expect(runWizardCommand({}, "remix")).rejects.toThrow( - "The remix wizard is not available in this version yet.", - ); - }); + const unported = INTEGRATION_IDS.find((id) => !hasWizardRunner(id)); + + test.runIf(unported)( + "reports an integration this version can't set up yet", + async () => { + await expect(runWizardCommand({}, unported ?? "")).rejects.toThrow( + `The ${unported} wizard is not available in this version yet.`, + ); + }, + ); test("exits with the wizard's code when it stops", async () => { runNextjsWizard.mockRejectedValue(new WizardExitError(0)); diff --git a/packages/cli/test/lib/wizard/android/android-wizard.test.ts b/packages/cli/test/lib/wizard/android/android-wizard.test.ts new file mode 100644 index 000000000..cf3f2f3dc --- /dev/null +++ b/packages/cli/test/lib/wizard/android/android-wizard.test.ts @@ -0,0 +1,197 @@ +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { runAndroidWizard } from "../../../../src/lib/wizard/android/android-wizard.js"; +import { reportCliError } from "../../../../src/lib/error-reporting.js"; +import { WizardExitError } from "../../../../src/lib/errors.js"; +import { execute } from "../../../../src/lib/wizard/utils/bash.js"; +import { + addSentryCliConfig, + getOrAskForProjectData, +} from "../../../../src/lib/wizard/utils/clack/index.js"; +import type { WizardProjectData } from "../../../../src/lib/wizard/utils/project-data.js"; +import type { WizardOptions } from "../../../../src/lib/wizard/utils/types.js"; + +vi.mock("../../../../src/lib/error-reporting.js", () => ({ + reportCliError: vi.fn(), +})); +vi.mock("../../../../src/lib/wizard/utils/bash.js", () => ({ + execute: vi.fn(), +})); +vi.mock("../../../../src/lib/wizard/utils/release-registry.js", () => ({ + fetchSdkVersion: vi.fn().mockResolvedValue("5.0.0"), +})); +vi.mock("../../../../src/lib/wizard/utils/clack/index.js", async () => ({ + ...(await vi.importActual( + "../../../../src/lib/wizard/utils/clack/index.js", + )), + confirmContinueIfNoOrDirtyGitRepo: vi.fn(), + addSentryCliConfig: vi.fn(), + getOrAskForProjectData: vi.fn(), +})); +vi.mock("../../../../src/lib/wizard/utils/clack/mcp-config.js", () => ({ + offerProjectScopedMcpConfig: vi.fn(), +})); +vi.mock("@clack/prompts", async () => ({ + ...(await vi.importActual("@clack/prompts")), + confirm: vi.fn().mockResolvedValue(false), +})); + +const OPTIONS: WizardOptions = { telemetryEnabled: false }; + +function projectData( + selfHosted: boolean, + sentryUrl: string, +): WizardProjectData { + return { + spotlight: false, + selfHosted, + sentryUrl, + authToken: "sntrys_token", + selectedProject: { + id: "1", + slug: "my-app", + organization: { id: "1", slug: "my-org", name: "My Org" }, + keys: [{ dsn: { public: "https://key@o1.ingest.sentry.io/1" } }], + }, + }; +} + +const MAIN_ACTIVITY_MANIFEST = ` + + + + + + + + +`; + +describe("runAndroidWizard", () => { + const originalCwd = process.cwd(); + let projectDir: string; + + beforeEach(() => { + vi.spyOn(process.stdout, "write").mockImplementation(() => true); + vi.mocked(execute).mockResolvedValue(""); + vi.mocked(getOrAskForProjectData).mockResolvedValue( + projectData(false, "https://sentry.io/"), + ); + projectDir = mkdtempSync(path.join(tmpdir(), "android-wizard-test-")); + process.chdir(projectDir); + }); + + afterEach(() => { + process.chdir(originalCwd); + rmSync(projectDir, { recursive: true }); + vi.mocked(reportCliError).mockClear(); + vi.restoreAllMocks(); + }); + + function writeApp(manifest: string): void { + mkdirSync(path.join(projectDir, "app", "src", "main"), { + recursive: true, + }); + writeFileSync( + path.join(projectDir, "app", "build.gradle"), + `plugins {\n id 'com.android.application'\n}\n\nandroid {\n namespace 'com.example'\n}\n`, + ); + writeFileSync( + path.join(projectDir, "app", "src", "main", "AndroidManifest.xml"), + manifest, + ); + } + + async function expectNonZeroExit(message: string): Promise { + const error = await runAndroidWizard(OPTIONS).catch( + (thrown: unknown) => thrown, + ); + expect(error).toBeInstanceOf(WizardExitError); + expect((error as WizardExitError).exitCode).not.toBe(0); + expect(reportCliError).not.toHaveBeenCalled(); + const output = vi + .mocked(process.stdout.write) + .mock.calls.map(([chunk]) => String(chunk)) + .join(""); + expect(output).toContain(message); + } + + it("exits non-zero without a Gradle project", async () => { + await expectNonZeroExit("No Gradle project found."); + }); + + it("exits non-zero when the Gradle sync fails", async () => { + writeApp(MAIN_ACTIVITY_MANIFEST); + vi.mocked(execute).mockRejectedValue(new Error("build failed")); + + await expectNonZeroExit("The Gradle sync failed"); + }); + + it("exits non-zero without a main activity", async () => { + writeApp( + ``, + ); + + await expectNonZeroExit( + "Could not find the Activity with intent action MAIN", + ); + }); + + describe("sentry.properties", () => { + beforeEach(async () => { + const actual = await vi.importActual< + typeof import("../../../../src/lib/wizard/utils/clack/index.js") + >("../../../../src/lib/wizard/utils/clack/index.js"); + vi.mocked(addSentryCliConfig).mockImplementation( + actual.addSentryCliConfig, + ); + writeApp(MAIN_ACTIVITY_MANIFEST); + const activityDir = path.join( + projectDir, + "app", + "src", + "main", + "java", + "com", + "example", + ); + mkdirSync(activityDir, { recursive: true }); + writeFileSync( + path.join(activityDir, "MainActivity.kt"), + `package com.example\n\nclass MainActivity : Activity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n }\n}\n`, + ); + }); + + function readProperties(): string { + return readFileSync(path.join(projectDir, "sentry.properties"), "utf8"); + } + + it("writes defaults.url for a self-hosted project", async () => { + vi.mocked(getOrAskForProjectData).mockResolvedValue( + projectData(true, "https://sentry.example.com/"), + ); + + await runAndroidWizard(OPTIONS); + + expect(readProperties()).toContain("auth.token=sntrys_token"); + expect(readProperties()).toContain( + "defaults.url=https://sentry.example.com/", + ); + }); + + it("writes no defaults.url for sentry.io", async () => { + await runAndroidWizard(OPTIONS); + + expect(readProperties()).toContain("auth.token=sntrys_token"); + expect(readProperties()).not.toContain("defaults.url"); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/android/code-tools.test.ts b/packages/cli/test/lib/wizard/android/code-tools.test.ts new file mode 100644 index 000000000..1313b5830 --- /dev/null +++ b/packages/cli/test/lib/wizard/android/code-tools.test.ts @@ -0,0 +1,111 @@ +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; +import { + findActivitySourceFile, + getLastImportLineLocation, + patchMainActivity, +} from "../../../../src/lib/wizard/android/code-tools.js"; + +describe("code-tools", () => { + describe("getLastImportLineLocation", () => { + it("returns proper line index", () => { + const code = `import a.b.c;\n` + `//\n` + `class X {}`; + expect(getLastImportLineLocation(code)).toBe( + code.indexOf("//"), + ); + }); + + it("returns the line after the package declaration when there are no imports", () => { + const code = + `package com.example\n` + `//\n` + `class X {}`; + expect(getLastImportLineLocation(code)).toBe( + code.indexOf("//"), + ); + }); + + it("returns proper line index when static import is used", () => { + const code = + `import static a.b.c;\n` + `//\n` + `class X {}`; + expect(getLastImportLineLocation(code)).toBe( + code.indexOf("//"), + ); + }); + + it("returns proper line index when wildcard import is used", () => { + const code = `import a.b.*\n` + `//\n` + `class X {}`; + expect(getLastImportLineLocation(code)).toBe( + code.indexOf("//"), + ); + }); + + it("returns proper line index when alias import is used", () => { + const code = + `import static a.b.c as d\n` + `//\n` + `class X {}`; + expect(getLastImportLineLocation(code)).toBe( + code.indexOf("//"), + ); + }); + + it("returns proper line index when multiple imports are present", () => { + const code = + `import static a.b.c as d\n` + + `import a.b.*\n` + + `import static a.b.c;\n` + + `import a.b.c;\n` + + `//\n` + + `class X {}`; + expect(getLastImportLineLocation(code)).toBe( + code.indexOf("//"), + ); + }); + }); + + describe("findActivitySourceFile", () => { + it.each([ + ["a relative name", ".MainActivity"], + ["a name without a dot", "MainActivity"], + ["a fully qualified name", "com.example.MainActivity"], + ])("finds the activity from %s", async (_label, activityName) => { + const appDir = mkdtempSync(path.join(tmpdir(), "android-activity-test-")); + try { + const dir = path.join(appDir, "src", "main", "java", "com", "example"); + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(dir, "MainActivity.kt"), ""); + + await expect( + findActivitySourceFile(appDir, "com.example", activityName), + ).resolves.toBe(path.join(dir, "MainActivity.kt")); + } finally { + rmSync(appDir, { recursive: true }); + } + }); + }); + + describe("patchMainActivity", () => { + it("adds the Sentry import when only other io.sentry classes are imported", () => { + const dir = mkdtempSync(path.join(tmpdir(), "android-patch-test-")); + try { + const file = path.join(dir, "MainActivity.kt"); + writeFileSync( + file, + "package com.example\n\nimport io.sentry.SentryOptions\n\nclass MainActivity : Activity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n }\n}\n", + ); + + expect(patchMainActivity(file)).toBe(true); + expect(readFileSync(file, "utf8")).toMatch( + /^import io\.sentry\.Sentry$/m, + ); + } finally { + rmSync(dir, { recursive: true }); + } + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/android/gradle.test.ts b/packages/cli/test/lib/wizard/android/gradle.test.ts new file mode 100644 index 000000000..bcdeec3d9 --- /dev/null +++ b/packages/cli/test/lib/wizard/android/gradle.test.ts @@ -0,0 +1,174 @@ +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + addGradlePlugin, + getNamespace, +} from "../../../../src/lib/wizard/android/gradle.js"; +import { + pluginKts, + pluginsBlock, + sourceContext, + sourceContextKts, +} from "../../../../src/lib/wizard/android/templates.js"; +import { execute } from "../../../../src/lib/wizard/utils/bash.js"; + +vi.mock("../../../../src/lib/error-reporting.js", () => ({ + reportCliError: vi.fn(), +})); +vi.mock("../../../../src/lib/wizard/utils/bash.js", () => ({ + execute: vi.fn(), +})); +vi.mock("../../../../src/lib/wizard/utils/release-registry.js", () => ({ + fetchSdkVersion: vi.fn().mockResolvedValue("5.0.0"), +})); + +describe("gradle", () => { + let tmpDir: string; + + beforeEach(() => { + vi.spyOn(process.stdout, "write").mockImplementation(() => true); + vi.mocked(execute).mockResolvedValue(""); + tmpDir = mkdtempSync(path.join(tmpdir(), "android-gradle-test-")); + }); + + afterEach(() => { + rmSync(tmpDir, { recursive: true }); + vi.restoreAllMocks(); + }); + + function writeGradle(name: string, content: string): string { + const file = path.join(tmpDir, name); + writeFileSync(file, content); + return file; + } + + describe("getNamespace", () => { + it.each([ + ["Groovy", `android {\n namespace 'com.example.groovy'\n}`], + ["Kotlin", `android {\n namespace = "com.example.groovy"\n}`], + ])("reads the namespace of a %s script", (_label, content) => { + const file = writeGradle("build.gradle", content); + + expect(getNamespace(file)).toBe("com.example.groovy"); + }); + + it("returns undefined without a namespace", () => { + const file = writeGradle("build.gradle", "android {}"); + + expect(getNamespace(file)).toBeUndefined(); + }); + }); + + describe("addGradlePlugin", () => { + it("adds the plugin to an existing plugins block and a sentry block", async () => { + const original = `plugins { + id("com.android.application") +} + +android { + namespace = "com.example" +} +`; + const file = writeGradle("build.gradle.kts", original); + + await expect(addGradlePlugin(file, "my-org", "my-app")).resolves.toBe( + true, + ); + + const insertAt = original.indexOf("}"); + expect(readFileSync(file, "utf8")).toBe( + original.slice(0, insertAt) + + pluginKts("5.0.0") + + original.slice(insertAt) + + sourceContextKts("my-org", "my-app"), + ); + expect(execute).toHaveBeenCalledWith("./gradlew"); + }); + + it("verifies with gradlew.bat on Windows", async () => { + vi.spyOn(process, "platform", "get").mockReturnValue("win32"); + const file = writeGradle( + "build.gradle.kts", + `plugins {\n id("com.android.application")\n}\n`, + ); + + await addGradlePlugin(file, "my-org", "my-app"); + + expect(execute).toHaveBeenCalledWith("gradlew.bat"); + }); + + it("adds a plugins block after the imports when there is none", async () => { + const original = `import groovy.json.JsonSlurper + +apply plugin: 'com.android.application' +`; + const file = writeGradle("build.gradle", original); + + await addGradlePlugin(file, "my-org", "my-app"); + + const insertAt = original.indexOf("\n") + 1; + expect(readFileSync(file, "utf8")).toBe( + original.slice(0, insertAt) + + pluginsBlock("5.0.0") + + original.slice(insertAt) + + sourceContext("my-org", "my-app"), + ); + }); + + it.each([ + "import static org.gradle.api.JavaVersion.VERSION_17", + "import java.util.*", + "import com.foo.Bar as Baz", + ])( + "adds the plugins block after the whole `%s` line", + async (importLine) => { + const original = `${importLine}\n\napply plugin: 'com.android.application'\n`; + const file = writeGradle("build.gradle", original); + + await addGradlePlugin(file, "my-org", "my-app"); + + const insertAt = original.indexOf("\n") + 1; + expect(readFileSync(file, "utf8")).toBe( + original.slice(0, insertAt) + + pluginsBlock("5.0.0") + + original.slice(insertAt) + + sourceContext("my-org", "my-app"), + ); + }, + ); + + it("keeps an existing sentry block when the plugin is already there", async () => { + const original = `plugins { + id 'io.sentry.android.gradle' version '4.0.0' +} + +sentry { + includeSourceContext = false +} +`; + const file = writeGradle("build.gradle", original); + + await expect(addGradlePlugin(file, "my-org", "my-app")).resolves.toBe( + true, + ); + + expect(readFileSync(file, "utf8")).toBe(original); + expect(execute).not.toHaveBeenCalled(); + }); + + it("fails when ./gradlew fails, keeping the edit", async () => { + vi.mocked(execute).mockRejectedValue(new Error("build failed")); + const file = writeGradle( + "build.gradle", + `plugins {\n id 'com.android.application'\n}\n`, + ); + + await expect(addGradlePlugin(file, "my-org", "my-app")).resolves.toBe( + false, + ); + expect(readFileSync(file, "utf8")).toContain("io.sentry.android.gradle"); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/android/manifest.test.ts b/packages/cli/test/lib/wizard/android/manifest.test.ts new file mode 100644 index 000000000..a977dd92e --- /dev/null +++ b/packages/cli/test/lib/wizard/android/manifest.test.ts @@ -0,0 +1,179 @@ +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + addManifestSnippet, + getMainActivity, +} from "../../../../src/lib/wizard/android/manifest.js"; +import { manifest } from "../../../../src/lib/wizard/android/templates.js"; + +vi.mock("../../../../src/lib/error-reporting.js", () => ({ + reportCliError: vi.fn(), +})); + +describe("AndroidManifest.xml", () => { + let tmpDir: string; + let manifestFile: string; + + beforeEach(() => { + vi.spyOn(process.stdout, "write").mockImplementation(() => true); + tmpDir = mkdtempSync(path.join(tmpdir(), "android-manifest-test-")); + manifestFile = path.join(tmpDir, "AndroidManifest.xml"); + }); + + afterEach(() => { + rmSync(tmpDir, { recursive: true }); + vi.restoreAllMocks(); + }); + + describe("getMainActivity", () => { + it("finds the activity with the MAIN action and the manifest package", () => { + writeFileSync( + manifestFile, + ` + + + + + + + + + + + + + + + + + + + + +`, + ); + + expect(getMainActivity(manifestFile)).toEqual({ + packageName: "com.example.sample", + activityName: "ui.MainActivity", + }); + }); + + it("returns no package name when the manifest has none", () => { + writeFileSync( + manifestFile, + ` + + + + + + + +`, + ); + + expect(getMainActivity(manifestFile)).toEqual({ + packageName: undefined, + activityName: ".MainActivity", + }); + }); + + it("returns nothing for a single activity without intent filters", () => { + writeFileSync( + manifestFile, + ``, + ); + + expect(getMainActivity(manifestFile)).toEqual({}); + }); + + it("ignores activity aliases", () => { + writeFileSync( + manifestFile, + ` + + + + + + + +`, + ); + + expect(getMainActivity(manifestFile)).toEqual({}); + }); + + it("returns nothing for a manifest it can't parse", () => { + writeFileSync(manifestFile, ``); + + expect(getMainActivity(manifestFile)).toEqual({}); + }); + + it("returns nothing when the manifest is missing", () => { + expect(getMainActivity(manifestFile)).toEqual({}); + }); + }); + + describe("addManifestSnippet", () => { + const original = ` + + + + +`; + + it("adds the Sentry options before and keeps the rest as-is", () => { + writeFileSync(manifestFile, original); + + expect(addManifestSnippet(manifestFile, "https://key@dsn", false)).toBe( + true, + ); + + const insertAt = original.indexOf(""); + expect(readFileSync(manifestFile, "utf8")).toBe( + original.slice(0, insertAt) + + manifest("https://key@dsn", false) + + original.slice(insertAt), + ); + }); + + it("enables logs when asked to", () => { + writeFileSync(manifestFile, original); + + addManifestSnippet(manifestFile, "https://key@dsn", true); + + expect(readFileSync(manifestFile, "utf8")).toContain( + '', + ); + }); + + it("leaves a manifest that already configures Sentry alone", () => { + const configured = original.replace( + "", + '', + ); + writeFileSync(manifestFile, configured); + + expect(addManifestSnippet(manifestFile, "https://key@dsn", false)).toBe( + true, + ); + expect(readFileSync(manifestFile, "utf8")).toBe(configured); + }); + + it("fails without an element", () => { + writeFileSync(manifestFile, ""); + + expect(addManifestSnippet(manifestFile, "https://key@dsn", false)).toBe( + false, + ); + expect(readFileSync(manifestFile, "utf8")).toBe(""); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/apple/snapshots/xml-scan.test.ts b/packages/cli/test/lib/wizard/apple/snapshots/xml-scan.test.ts index e44b5290f..777d2f865 100644 --- a/packages/cli/test/lib/wizard/apple/snapshots/xml-scan.test.ts +++ b/packages/cli/test/lib/wizard/apple/snapshots/xml-scan.test.ts @@ -1,6 +1,5 @@ import { describe, expect, it } from "vitest"; import { - decodeXmlEntities, getAttributeValues, getElementContent, getElementTexts, @@ -47,19 +46,6 @@ const plist = ` `; describe("xml-scan", () => { - describe("decodeXmlEntities", () => { - it("decodes named and numeric references", () => { - expect(decodeXmlEntities("a & b <c> "'")).toBe( - "a & b \"'", - ); - expect(decodeXmlEntities("AB")).toBe("AB"); - }); - - it("leaves unknown entities as they are", () => { - expect(decodeXmlEntities(" ")).toBe(" "); - }); - }); - describe("getElementContent", () => { it("returns the markup inside the first matching element", () => { const testAction = getElementContent(scheme, "TestAction"); diff --git a/packages/cli/test/lib/wizard/flutter/code-tools.test.ts b/packages/cli/test/lib/wizard/flutter/code-tools.test.ts new file mode 100644 index 000000000..e0bdb0c0a --- /dev/null +++ b/packages/cli/test/lib/wizard/flutter/code-tools.test.ts @@ -0,0 +1,336 @@ +import { describe, expect, it } from "vitest"; +import { + patchMainContent, + getDependenciesLocation, + getDevDependenciesLocation, + getLastImportLineLocation, +} from "../../../../src/lib/wizard/flutter/code-tools.js"; +import { initSnippet } from "../../../../src/lib/wizard/flutter/templates.js"; + +describe("code-tools", () => { + const pubspec = `name: flutter_example +description: An example flutter app. +version: 1.0.0 +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +environment: + sdk: '>=2.17.0 <4.0.0' + flutter: '>=3.0.0' + +dependencies: + flutter: + sdk: flutter + +dev_dependencies: + flutter_lints: ^2.0.0 +`; + + const simpleRunApp = `import 'package:flutter/widgets.dart'; + +void main() { + runApp(const MyApp()); +} +`; + + const asyncRunApp = `import 'package:flutter/widgets.dart'; + +void main() { + runApp(const MyApp()); +} +`; + + const selectedFeaturesMap = { + tracing: true, + replay: true, + }; + + const simpleRunAppPatched = `import 'package:flutter/widgets.dart'; +import 'package:sentry_flutter/sentry_flutter.dart'; + +Future main() async { + ${initSnippet("dsn", selectedFeaturesMap, "const MyApp()")} +} +`; + + const paramRunApp = `import 'package:flutter/widgets.dart'; + +Future main() async { + await someFunction(); + runApp(MyApp(param: SomeParam())); + await anotherFunction(); +} +`; + + const paramRunAppPatched = `import 'package:flutter/widgets.dart'; +import 'package:sentry_flutter/sentry_flutter.dart'; + +Future main() async { + await someFunction(); + ${initSnippet("dsn", selectedFeaturesMap, "MyApp(param: SomeParam())")} + await anotherFunction(); +} +`; + + const multilineRunApp = `import 'package:flutter/widgets.dart'; + +void main() { + runApp( + MyApp( + param: Param(), + multi: Another(1), + line: await bites(the: "dust"), + ), + ); + anotherFunction(); +} +`; + + const multilineRunAppPatched = `import 'package:flutter/widgets.dart'; +import 'package:sentry_flutter/sentry_flutter.dart'; + +Future main() async { + ${initSnippet( + "dsn", + selectedFeaturesMap, + ` + MyApp( + param: Param(), + multi: Another(1), + line: await bites(the: "dust"), + ), + `, + )} + anotherFunction(); +} +`; + + describe("patchMainContent", () => { + function patched(main: string, runAppArgs: string): string { + return `import 'package:flutter/widgets.dart'; +import 'package:sentry_flutter/sentry_flutter.dart'; + +${main} { + ${initSnippet("dsn", selectedFeaturesMap, runAppArgs)} +} +`; + } + + it("wraps the whole runApp call when its arguments contain a statement", () => { + const args = + "MaterialApp(home: Builder(builder: (c) { return Text('x'); }))"; + expect( + patchMainContent( + "dsn", + `import 'package:flutter/widgets.dart';\n\nvoid main() {\n runApp(${args});\n}\n`, + selectedFeaturesMap, + ), + ).toBe(patched("Future main() async", args)); + }); + + it("skips parentheses in strings and comments inside runApp", () => { + const args = "MyApp(title: 'a);b') /* ) */"; + expect( + patchMainContent( + "dsn", + `import 'package:flutter/widgets.dart';\n\nvoid main() {\n runApp(${args});\n}\n`, + selectedFeaturesMap, + ), + ).toBe(patched("Future main() async", args)); + }); + + it("leaves a commented-out runApp call alone", () => { + const source = (call: string) => + `import 'package:flutter/widgets.dart';\n\nvoid main() {\n // runApp(const OldApp());\n ${call}\n}\n`; + expect( + patchMainContent( + "dsn", + source("runApp(const MyApp());"), + selectedFeaturesMap, + ), + ).toBe( + `import 'package:flutter/widgets.dart';\nimport 'package:sentry_flutter/sentry_flutter.dart';\n\nFuture main() async {\n // runApp(const OldApp());\n ${initSnippet("dsn", selectedFeaturesMap, "const MyApp()")}\n}\n`, + ); + }); + + it("leaves main text inside strings and comments alone", () => { + const source = `import 'package:flutter/widgets.dart';\n\n// void main() {\nvoid main() {\n print('void main() {');\n runApp(const MyApp());\n}\n`; + expect(patchMainContent("dsn", source, selectedFeaturesMap)).toBe( + `import 'package:flutter/widgets.dart';\nimport 'package:sentry_flutter/sentry_flutter.dart';\n\n// void main() {\nFuture main() async {\n print('void main() {');\n ${initSnippet("dsn", selectedFeaturesMap, "const MyApp()")}\n}\n`, + ); + }); + + it("keeps an existing Sentry import and adds no second one", () => { + const source = `import 'package:flutter/widgets.dart';\nimport 'package:sentry_flutter/sentry_flutter.dart';\n\nvoid main() {\n runApp(const MyApp());\n}\n`; + expect(patchMainContent("dsn", source, selectedFeaturesMap)).toBe( + `import 'package:flutter/widgets.dart';\nimport 'package:sentry_flutter/sentry_flutter.dart';\n\nFuture main() async {\n ${initSnippet("dsn", selectedFeaturesMap, "const MyApp()")}\n}\n`, + ); + }); + + it("leaves a commented-out arrow main alone", () => { + const source = `import 'package:flutter/widgets.dart';\n\n// void main() => runApp(const OldApp());\nvoid main() {\n runApp(const MyApp());\n}\n`; + expect(patchMainContent("dsn", source, selectedFeaturesMap)).toBe( + `import 'package:flutter/widgets.dart';\nimport 'package:sentry_flutter/sentry_flutter.dart';\n\n// void main() => runApp(const OldApp());\nFuture main() async {\n ${initSnippet("dsn", selectedFeaturesMap, "const MyApp()")}\n}\n`, + ); + }); + + it("turns an expression-bodied main into an async block", () => { + expect( + patchMainContent( + "dsn", + `import 'package:flutter/widgets.dart';\n\nvoid main() => runApp(const MyApp());\n`, + selectedFeaturesMap, + ), + ).toBe(patched("Future main() async", "const MyApp()")); + }); + + it("makes a main with parameters async", () => { + expect( + patchMainContent( + "dsn", + `import 'package:flutter/widgets.dart';\n\nvoid main(List args) {\n runApp(const MyApp());\n}\n`, + selectedFeaturesMap, + ), + ).toBe( + patched("Future main(List args) async", "const MyApp()"), + ); + }); + + it("adds no init without a runApp statement", () => { + expect( + patchMainContent( + "dsn", + `void main() {\n bootstrap();\n}\n`, + selectedFeaturesMap, + ), + ).not.toContain("SentryFlutter.init("); + }); + + it("wraps simple runApp", () => { + expect(patchMainContent("dsn", simpleRunApp, selectedFeaturesMap)).toBe( + simpleRunAppPatched, + ); + }); + + it("wraps async runApp", () => { + expect(patchMainContent("dsn", asyncRunApp, selectedFeaturesMap)).toBe( + simpleRunAppPatched, + ); + }); + + it("wraps runApp with parameterized app", () => { + expect(patchMainContent("dsn", paramRunApp, selectedFeaturesMap)).toBe( + paramRunAppPatched, + ); + }); + + it("wraps multiline runApp", () => { + expect( + patchMainContent("dsn", multilineRunApp, selectedFeaturesMap), + ).toBe(multilineRunAppPatched); + }); + }); + + describe("pubspec", () => { + it("returns proper line index for dependencies", () => { + expect(getDependenciesLocation(pubspec)).toBe( + pubspec.indexOf(" flutter:\n"), + ); + }); + + it("returns proper line index for dev-dependencies", () => { + expect(getDevDependenciesLocation(pubspec)).toBe( + pubspec.indexOf(" flutter_lints: ^2.0.0\n"), + ); + }); + + it("finds a header with a trailing comment", () => { + const withComment = "dev_dependencies: # tools\n lints: ^2.0.0\n"; + expect(getDevDependenciesLocation(withComment)).toBe( + withComment.indexOf(" lints"), + ); + }); + + it("returns -1 without the header", () => { + expect(getDevDependenciesLocation("dependencies:\n http: any\n")).toBe( + -1, + ); + }); + }); + + describe("getLastImportLineLocation", () => { + it("returns proper line index", () => { + const code = + `import 'foo:bar';\n` + `//\n` + `class X {}`; + expect(getLastImportLineLocation(code)).toBe( + code.indexOf("//"), + ); + }); + + it("returns proper line index when alias import is used", () => { + const code = + `import 'package:my_library/utils.dart' as utils;\n` + + `//\n` + + `class X {}`; + expect(getLastImportLineLocation(code)).toBe( + code.indexOf("//"), + ); + }); + + it("returns proper line index when specific parts import is used", () => { + const code = + `import 'dart:math' show pi, sin;\n` + + `//\n` + + `class X {}`; + expect(getLastImportLineLocation(code)).toBe( + code.indexOf("//"), + ); + }); + + it("returns proper line index when hide import is used", () => { + const code = + `import 'dart:math' hide Random;\n` + + `//\n` + + `class X {}`; + expect(getLastImportLineLocation(code)).toBe( + code.indexOf("//"), + ); + }); + + it("returns proper line index when deferred import is used", () => { + const code = + `import 'package:my_library/large_library.dart' deferred as largeLibrary;\n` + + `//\n` + + `class X {}`; + expect(getLastImportLineLocation(code)).toBe( + code.indexOf("//"), + ); + }); + + it("returns proper line index when multiple imports (with newlines) are present", () => { + const code = + `import 'foo:bar';\n` + + `import 'package:my_library/utils.dart' as utils;\n` + + `import 'dart:math' show pi, sin;\n` + + `import 'dart:math' hide Random;\n` + + `\n` + + `import 'package:my_library/large_library.dart' deferred as largeLibrary;\n` + + `//\n` + + `class X {}`; + expect(getLastImportLineLocation(code)).toBe( + code.indexOf("//"), + ); + }); + + it("ignores imports inside comments", () => { + const code = + `import 'package:flutter/widgets.dart';\n` + + `//\n` + + `/* import 'package:foo/foo.dart'; */\n` + + `// import 'package:bar/bar.dart';\n` + + `class X {}`; + expect(getLastImportLineLocation(code)).toBe( + code.indexOf("//"), + ); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/flutter/flutter-wizard.test.ts b/packages/cli/test/lib/wizard/flutter/flutter-wizard.test.ts new file mode 100644 index 000000000..3073ca3f6 --- /dev/null +++ b/packages/cli/test/lib/wizard/flutter/flutter-wizard.test.ts @@ -0,0 +1,162 @@ +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { runFlutterWizard } from "../../../../src/lib/wizard/flutter/flutter-wizard.js"; +import { reportCliError } from "../../../../src/lib/error-reporting.js"; +import { WizardExitError } from "../../../../src/lib/errors.js"; +import { + featureSelectionPrompt, + showCopyPasteInstructions, +} from "../../../../src/lib/wizard/utils/clack/index.js"; +import { clack } from "../../../../src/lib/wizard/utils/clack/prompts.js"; +import type { WizardOptions } from "../../../../src/lib/wizard/utils/types.js"; + +vi.mock("../../../../src/lib/error-reporting.js", () => ({ + reportCliError: vi.fn(), +})); +vi.mock("../../../../src/lib/wizard/utils/release-registry.js", () => ({ + fetchSdkVersion: vi.fn().mockResolvedValue("9.0.0"), +})); +vi.mock("../../../../src/lib/wizard/utils/clack/mcp-config.js", () => ({ + offerProjectScopedMcpConfig: vi.fn(), +})); +vi.mock("../../../../src/lib/wizard/utils/clack/index.js", async () => ({ + ...(await vi.importActual( + "../../../../src/lib/wizard/utils/clack/index.js", + )), + confirmContinueIfNoOrDirtyGitRepo: vi.fn(), + showCopyPasteInstructions: vi.fn(), + featureSelectionPrompt: vi + .fn() + .mockResolvedValue({ tracing: true, replay: false }), + getOrAskForProjectData: vi.fn().mockResolvedValue({ + spotlight: false, + selfHosted: false, + sentryUrl: "https://sentry.io/", + authToken: "sntrys_token", + selectedProject: { + id: "1", + slug: "my-app", + organization: { id: "1", slug: "my-org", name: "My Org" }, + keys: [{ dsn: { public: "https://key@o1.ingest.sentry.io/1" } }], + }, + }), +})); + +const OPTIONS: WizardOptions = { telemetryEnabled: false }; + +const PUBSPEC = `name: flutter_example + +dependencies: + flutter: + sdk: flutter + +dev_dependencies: + flutter_lints: ^2.0.0 +`; + +describe("runFlutterWizard", () => { + const originalCwd = process.cwd(); + let projectDir: string; + + beforeEach(() => { + vi.spyOn(process.stdout, "write").mockImplementation(() => true); + projectDir = mkdtempSync(path.join(tmpdir(), "flutter-wizard-test-")); + process.chdir(projectDir); + }); + + afterEach(() => { + process.chdir(originalCwd); + rmSync(projectDir, { recursive: true }); + vi.mocked(reportCliError).mockClear(); + vi.mocked(showCopyPasteInstructions).mockClear(); + vi.restoreAllMocks(); + }); + + function copyPasteFiles(): string[] { + return vi + .mocked(showCopyPasteInstructions) + .mock.calls.map(([opts]) => ("filename" in opts ? opts.filename : "")); + } + + it("exits non-zero without a pubspec.yaml", async () => { + const error = await runFlutterWizard(OPTIONS).catch( + (thrown: unknown) => thrown, + ); + + expect(error).toBeInstanceOf(WizardExitError); + expect((error as WizardExitError).exitCode).not.toBe(0); + expect(reportCliError).not.toHaveBeenCalled(); + }); + + it("shows the main.dart snippet when there is no lib/ directory", async () => { + writeFileSync(path.join(projectDir, "pubspec.yaml"), PUBSPEC); + + await runFlutterWizard(OPTIONS); + + expect(copyPasteFiles()).toEqual(["main.dart"]); + expect(reportCliError).not.toHaveBeenCalled(); + }); + + it.each([ + "import 'package:sentry_flutter/sentry_flutter.dart';\n\n", + "// import 'package:sentry_flutter/sentry_flutter.dart';\n\n", + ])( + "adds SentryFlutter.init when main.dart only imports Sentry (%#)", + async (imports) => { + writeFileSync(path.join(projectDir, "pubspec.yaml"), PUBSPEC); + mkdirSync(path.join(projectDir, "lib")); + const mainFile = path.join(projectDir, "lib", "main.dart"); + writeFileSync( + mainFile, + `${imports}void main() {\n runApp(const MyApp());\n}\n`, + ); + + await runFlutterWizard(OPTIONS); + + expect(readFileSync(mainFile, "utf8")).toContain("SentryFlutter.init("); + expect(copyPasteFiles()).toEqual([]); + }, + ); + + it("exits when the feature prompt is cancelled", async () => { + writeFileSync(path.join(projectDir, "pubspec.yaml"), PUBSPEC); + mkdirSync(path.join(projectDir, "lib")); + writeFileSync( + path.join(projectDir, "lib", "main.dart"), + "void main() {\n runApp(const MyApp());\n}\n", + ); + vi.mocked(featureSelectionPrompt).mockRejectedValueOnce( + new WizardExitError(0), + ); + + await expect(runFlutterWizard(OPTIONS)).rejects.toBeInstanceOf( + WizardExitError, + ); + expect(copyPasteFiles()).toEqual([]); + expect(reportCliError).not.toHaveBeenCalled(); + }); + + it("shows the main.dart snippet and leaves main.dart alone without runApp", async () => { + const outro = vi.spyOn(clack, "outro"); + writeFileSync(path.join(projectDir, "pubspec.yaml"), PUBSPEC); + mkdirSync(path.join(projectDir, "lib")); + const mainFile = path.join(projectDir, "lib", "main.dart"); + const main = "void main() {\n bootstrap();\n}\n"; + writeFileSync(mainFile, main); + + await runFlutterWizard(OPTIONS); + + expect(copyPasteFiles()).toEqual(["main.dart"]); + expect(readFileSync(mainFile, "utf8")).toBe(main); + expect(reportCliError).not.toHaveBeenCalled(); + expect(outro.mock.calls[0]?.[0]).not.toContain("test error"); + }); +}); diff --git a/packages/cli/test/lib/wizard/flutter/pubspec.test.ts b/packages/cli/test/lib/wizard/flutter/pubspec.test.ts new file mode 100644 index 000000000..d859f5487 --- /dev/null +++ b/packages/cli/test/lib/wizard/flutter/pubspec.test.ts @@ -0,0 +1,185 @@ +import { + existsSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + addProperties, + patchPubspec, +} from "../../../../src/lib/wizard/flutter/code-tools.js"; +import { pubspecOptions } from "../../../../src/lib/wizard/flutter/templates.js"; +import { reportCliError } from "../../../../src/lib/error-reporting.js"; + +vi.mock("../../../../src/lib/error-reporting.js", () => ({ + reportCliError: vi.fn(), +})); + +describe("pubspec.yaml and sentry.properties", () => { + let tmpDir: string; + let pubspecFile: string; + + beforeEach(() => { + vi.spyOn(process.stdout, "write").mockImplementation(() => true); + tmpDir = mkdtempSync(path.join(tmpdir(), "flutter-pubspec-test-")); + pubspecFile = path.join(tmpDir, "pubspec.yaml"); + }); + + afterEach(() => { + rmSync(tmpDir, { recursive: true }); + vi.restoreAllMocks(); + }); + + describe("patchPubspec", () => { + it("adds the packages and plugin options and keeps the user's formatting", () => { + writeFileSync( + pubspecFile, + `name: flutter_example # the app +version: 1.0.0 + +dependencies: + flutter: + sdk: flutter + # keep this comment + http: "^1.0.0" + +dev_dependencies: + flutter_lints: ^2.0.0 + +flutter: + uses-material-design: true +`, + ); + + expect( + patchPubspec(pubspecFile, "^9.0.0", "^3.0.0", "my-app", "my-org"), + ).toBe(true); + + expect(readFileSync(pubspecFile, "utf8")) + .toBe(`name: flutter_example # the app +version: 1.0.0 + +dependencies: + sentry_flutter: ^9.0.0 + flutter: + sdk: flutter + # keep this comment + http: "^1.0.0" + +dev_dependencies: + sentry_dart_plugin: ^3.0.0 + flutter_lints: ^2.0.0 + +flutter: + uses-material-design: true + +sentry: + upload_debug_symbols: true + upload_source_maps: true + project: my-app + org: my-org +`); + }); + + it("changes nothing that is already there", () => { + const original = `dependencies: + sentry_flutter: ^8.0.0 + +dev_dependencies: + sentry_dart_plugin: ^2.0.0 + +sentry: + project: other +`; + writeFileSync(pubspecFile, original); + + expect(patchPubspec(pubspecFile, "any", "any", "my-app", "my-org")).toBe( + true, + ); + expect(readFileSync(pubspecFile, "utf8")).toBe(original); + }); + + it("adds a dev_dependencies section when there is none", () => { + writeFileSync( + pubspecFile, + "name: flutter_example\n\ndependencies:\n flutter:\n sdk: flutter\n", + ); + + expect( + patchPubspec(pubspecFile, "^9.0.0", "^3.0.0", "my-app", "my-org"), + ).toBe(true); + + expect(readFileSync(pubspecFile, "utf8")).toBe( + "name: flutter_example\n\ndependencies:\n sentry_flutter: ^9.0.0\n flutter:\n sdk: flutter\n\ndev_dependencies:\n sentry_dart_plugin: ^3.0.0\n\n" + + pubspecOptions("my-app", "my-org"), + ); + }); + + it("adds the packages when they are only in comments", () => { + writeFileSync( + pubspecFile, + "name: flutter_example\n\ndependencies:\n # sentry_flutter: ^8.0.0\n\ndev_dependencies:\n # sentry_dart_plugin: ^2.0.0\n", + ); + + expect( + patchPubspec(pubspecFile, "^9.0.0", "^3.0.0", "my-app", "my-org"), + ).toBe(true); + + const patched = readFileSync(pubspecFile, "utf8"); + expect(patched).toMatch(/^ {2}sentry_flutter: \^9\.0\.0$/m); + expect(patched).toMatch(/^ {2}sentry_dart_plugin: \^3\.0\.0$/m); + }); + + it("adds the plugin options when a dependency is named sentry", () => { + writeFileSync( + pubspecFile, + "name: flutter_example\n\ndependencies:\n sentry: ^9.0.0\n\ndev_dependencies:\n flutter_lints: ^2.0.0\n", + ); + + expect( + patchPubspec(pubspecFile, "^9.0.0", "^3.0.0", "my-app", "my-org"), + ).toBe(true); + + expect(readFileSync(pubspecFile, "utf8")).toContain( + pubspecOptions("my-app", "my-org"), + ); + }); + + it("fails without a pubspec.yaml", () => { + expect(patchPubspec(null, "any", "any", "my-app", "my-org")).toBe(false); + expect(reportCliError).toHaveBeenCalled(); + }); + }); + + describe("addProperties", () => { + it("writes the auth token and adds sentry.properties to .gitignore", () => { + writeFileSync(path.join(tmpDir, ".gitignore"), "build/"); + + expect(addProperties(pubspecFile, "sntrys_token")).toBe(true); + + expect(readFileSync(path.join(tmpDir, "sentry.properties"), "utf8")).toBe( + "auth_token=sntrys_token", + ); + expect(readFileSync(path.join(tmpDir, ".gitignore"), "utf8")).toBe( + "build/\nsentry.properties\n", + ); + }); + + it("creates .gitignore when there is none", () => { + addProperties(pubspecFile, "sntrys_token"); + + expect(readFileSync(path.join(tmpDir, ".gitignore"), "utf8")).toBe( + "sentry.properties\n", + ); + }); + + it("fails without a pubspec.yaml", () => { + expect(addProperties(null, "sntrys_token")).toBe(false); + expect(existsSync(path.join(tmpDir, "sentry.properties"))).toBe(false); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/flutter/templates.test.ts b/packages/cli/test/lib/wizard/flutter/templates.test.ts new file mode 100644 index 000000000..37c97a286 --- /dev/null +++ b/packages/cli/test/lib/wizard/flutter/templates.test.ts @@ -0,0 +1,121 @@ +import { describe, expect, it, vi } from "vitest"; +import { + pubspecOptions, + sentryProperties, + initSnippet, + initSnippetColored, +} from "../../../../src/lib/wizard/flutter/templates.js"; + +vi.mock("../../../../src/lib/wizard/utils/clack/mcp-config.js", () => ({ + offerProjectScopedMcpConfig: vi.fn().mockResolvedValue(undefined), +})); + +describe("Flutter code templates", () => { + describe("pubspec", () => { + it("generates pubspec with project and org", () => { + const template = pubspecOptions("fixture-project", "fixture-org"); + expect(template).toMatchInlineSnapshot(` + "sentry: + upload_debug_symbols: true + upload_source_maps: true + project: fixture-project + org: fixture-org + " + `); + }); + }); + describe("sentry.properties", () => { + it("generates sentry.properties with token", () => { + const template = sentryProperties("fixture-token"); + expect(template).toMatchInlineSnapshot(`"auth_token=fixture-token"`); + }); + }); + describe("init", () => { + it("generates Sentry config with tracing and replay enabled", () => { + const template = initSnippet( + "my-dsn", + { + tracing: true, + replay: true, + }, + "const MyApp()", + ); + expect(template).toMatchInlineSnapshot(` + "await SentryFlutter.init( + (options) { + options.dsn = 'my-dsn'; + // Adds request headers and IP for users, for more info visit: + // https://docs.sentry.io/platforms/dart/guides/flutter/data-management/data-collected/ + options.sendDefaultPii = true; + // Set tracesSampleRate to 1.0 to capture 100% of transactions for tracing. + // We recommend adjusting this value in production. + options.tracesSampleRate = 1.0; + // Configure Session Replay + options.replay.sessionSampleRate = 0.1; + options.replay.onErrorSampleRate = 1.0; + }, + appRunner: () => runApp(SentryWidget(child: const MyApp())), + ); + // TODO: Remove this line after sending the first sample event to sentry. + await Sentry.captureException(StateError('This is a sample exception.'));" + `); + }); + + it("generates Sentry config with replay disabled", () => { + const template = initSnippet( + "my-dsn", + { + tracing: true, + replay: false, + }, + "const MyApp()", + ); + expect(template).toMatchInlineSnapshot(` + "await SentryFlutter.init( + (options) { + options.dsn = 'my-dsn'; + // Adds request headers and IP for users, for more info visit: + // https://docs.sentry.io/platforms/dart/guides/flutter/data-management/data-collected/ + options.sendDefaultPii = true; + // Set tracesSampleRate to 1.0 to capture 100% of transactions for tracing. + // We recommend adjusting this value in production. + options.tracesSampleRate = 1.0; + }, + appRunner: () => runApp(SentryWidget(child: const MyApp())), + ); + // TODO: Remove this line after sending the first sample event to sentry. + await Sentry.captureException(StateError('This is a sample exception.'));" + `); + }); + + it("generates Sentry config with tracing and replay disabled", () => { + const template = initSnippet( + "my-dsn", + { + tracing: false, + replay: false, + }, + "const MyApp()", + ); + expect(template).toMatchInlineSnapshot(` + "await SentryFlutter.init( + (options) { + options.dsn = 'my-dsn'; + // Adds request headers and IP for users, for more info visit: + // https://docs.sentry.io/platforms/dart/guides/flutter/data-management/data-collected/ + options.sendDefaultPii = true; + }, + appRunner: () => runApp(SentryWidget(child: const MyApp())), + ); + // TODO: Remove this line after sending the first sample event to sentry. + await Sentry.captureException(StateError('This is a sample exception.'));" + `); + }); + }); + + it("ends the copy-paste init statement with a semicolon", () => { + expect(initSnippetColored("dsn")).toContain( + "appRunner: () => runApp(SentryWidget(child: YourApp())),\n );\n}", + ); + }); +}); diff --git a/packages/cli/test/lib/wizard/utils/line-endings.test.ts b/packages/cli/test/lib/wizard/utils/line-endings.test.ts new file mode 100644 index 000000000..aedda0576 --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/line-endings.test.ts @@ -0,0 +1,110 @@ +import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fixLineEndings } from "../../../../src/lib/wizard/utils/line-endings.js"; +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as git from "../../../../src/lib/wizard/utils/git.js"; + +describe("fixLineEndings", () => { + let tmpDir: string; + + beforeEach(() => { + tmpDir = mkdtempSync(path.join(tmpdir(), "line-endings-test-")); + }); + + afterEach(() => { + rmSync(tmpDir, { recursive: true }); + vi.restoreAllMocks(); + }); + + it("normalizes mixed line endings to CRLF when file has CRLF", () => { + const filePath = path.join(tmpDir, "mixed.dart"); + writeFileSync(filePath, "line1\r\nline2\nline3\r\n", "utf8"); + + vi.spyOn(git, "getUncommittedOrUntrackedFilePaths").mockReturnValue([ + filePath, + ]); + + fixLineEndings(); + + const result = readFileSync(filePath, "utf8"); + expect(result).toBe("line1\r\nline2\r\nline3\r\n"); + }); + + it("skips files that are pure LF", () => { + const filePath = path.join(tmpDir, "lf.dart"); + const original = "line1\nline2\n"; + writeFileSync(filePath, original, "utf8"); + + vi.spyOn(git, "getUncommittedOrUntrackedFilePaths").mockReturnValue([ + filePath, + ]); + + fixLineEndings(); + + const result = readFileSync(filePath, "utf8"); + expect(result).toBe(original); + }); + + it("leaves consistent CRLF files unchanged", () => { + const filePath = path.join(tmpDir, "crlf.dart"); + const original = "line1\r\nline2\r\n"; + writeFileSync(filePath, original, "utf8"); + + vi.spyOn(git, "getUncommittedOrUntrackedFilePaths").mockReturnValue([ + filePath, + ]); + + fixLineEndings(); + + const result = readFileSync(filePath, "utf8"); + expect(result).toBe(original); + }); + + it("skips non-text files", () => { + const filePath = path.join(tmpDir, "image.png"); + const original = "line1\r\nline2\nline3\r\n"; + writeFileSync(filePath, original, "utf8"); + + vi.spyOn(git, "getUncommittedOrUntrackedFilePaths").mockReturnValue([ + filePath, + ]); + + fixLineEndings(); + + const result = readFileSync(filePath, "utf8"); + expect(result).toBe(original); + }); + + it("skips directories", () => { + const dirPath = path.join(tmpDir, "subdir"); + mkdirSync(dirPath); + + vi.spyOn(git, "getUncommittedOrUntrackedFilePaths").mockReturnValue([ + dirPath, + ]); + + expect(() => fixLineEndings()).not.toThrow(); + }); + + it("skips nonexistent files", () => { + vi.spyOn(git, "getUncommittedOrUntrackedFilePaths").mockReturnValue([ + "nonexistent.txt", + ]); + + expect(() => fixLineEndings()).not.toThrow(); + }); + + it("does nothing when there are no modified files", () => { + vi.spyOn(git, "getUncommittedOrUntrackedFilePaths").mockReturnValue([]); + + expect(() => fixLineEndings()).not.toThrow(); + }); +}); diff --git a/packages/cli/test/lib/wizard/utils/release-registry.test.ts b/packages/cli/test/lib/wizard/utils/release-registry.test.ts new file mode 100644 index 000000000..c076ee7e6 --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/release-registry.test.ts @@ -0,0 +1,51 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { fetchSdkVersion } from "../../../../src/lib/wizard/utils/release-registry.js"; + +describe("fetchSdkVersion", () => { + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it("returns the version the registry lists for the SDK", async () => { + const fetchMock = vi.fn().mockResolvedValue( + Response.json({ + "sentry.dart.flutter": { version: "9.1.0" }, + "sentry.dart.plugin": { version: "3.0.0" }, + }), + ); + vi.stubGlobal("fetch", fetchMock); + + await expect(fetchSdkVersion("sentry.dart.flutter")).resolves.toBe("9.1.0"); + expect(fetchMock).toHaveBeenCalledWith( + "https://release-registry.services.sentry.io/sdks", + ); + }); + + it("returns undefined for an SDK the registry doesn't list", async () => { + vi.stubGlobal("fetch", vi.fn().mockResolvedValue(Response.json({}))); + + await expect(fetchSdkVersion("sentry.unknown")).resolves.toBeUndefined(); + }); + + it("returns undefined for an error response", async () => { + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue(new Response("oops", { status: 503 })), + ); + + await expect( + fetchSdkVersion("sentry.dart.flutter"), + ).resolves.toBeUndefined(); + }); + + it("returns undefined when the registry can't be reached", async () => { + vi.stubGlobal( + "fetch", + vi.fn().mockRejectedValue(new TypeError("fetch failed")), + ); + + await expect( + fetchSdkVersion("sentry.dart.flutter"), + ).resolves.toBeUndefined(); + }); +}); diff --git a/packages/cli/test/lib/wizard/utils/xml.test.ts b/packages/cli/test/lib/wizard/utils/xml.test.ts new file mode 100644 index 000000000..198a5c07b --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/xml.test.ts @@ -0,0 +1,113 @@ +import { describe, expect, it } from "vitest"; +import { + childElements, + decodeXmlEntities, + parseXml, +} from "../../../../src/lib/wizard/utils/xml.js"; + +describe("parseXml", () => { + it("parses nested elements and their attributes", () => { + const root = parseXml( + ` + + + + +`, + ); + + expect(root).toEqual({ + name: "manifest", + attributes: { + "xmlns:android": "http://schemas.android.com/apk/res/android", + package: "com.example", + }, + children: [ + { + name: "application", + attributes: { "android:label": "@string/app_name" }, + children: [ + { + name: "activity", + attributes: { + "android:name": ".MainActivity", + "android:exported": "true", + }, + children: [], + }, + ], + }, + ], + }); + }); + + it("skips comments, CDATA, doctypes, and text, even when they look like tags", () => { + const root = parseXml(` + + + some text + ]]> + + + +`); + + expect(root.name).toBe("manifest"); + expect(root.children.map((child) => child.name)).toEqual(["application"]); + expect(root.children[0]?.children).toEqual([]); + }); + + it("decodes character references in attribute values", () => { + const root = parseXml( + ``, + ); + + expect(root.attributes["value"]).toBe(`x & y "q" 's' AB`); + }); + + it("allows `>` inside attribute values and multi-line tags", () => { + const root = parseXml(``); + + expect(root.attributes).toEqual({ first: "1 > 0", second: "2" }); + }); + + it.each([ + ["an unclosed element", ""], + ["a closing tag without an opening tag", ""], + ["an element that is never closed", ""], + ["two root elements", ""], + ["no root element", ""], + ["an unterminated comment", "