### Install Yarn Regular Dependency Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/dependencies.md Example of how to install a regular dependency using yarn. ```bash yarn add react-native ``` -------------------------------- ### Install npm Regular Dependency Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/dependencies.md Example of how to install a regular dependency using npm. ```bash npm install react-native ``` -------------------------------- ### Setup in Current Directory Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/setup-command.md Example of running SetupCommand from the project's root directory. It automatically uses the current working directory for the project path. ```bash cd /path/to/rn/project npx datadog-react-native-wizard ``` -------------------------------- ### Step Implementation Example Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/types.md An example of how to implement the `Step` type for installing project dependencies. It shows the usage of `stepFunction` and `errorHandler` with a generic `AppState`. ```typescript const step: Step = { name: 'Install Dependencies', stepFunction: async (store) => { const state = store.get(); await installer.install(state.projectPath); }, errorHandler: async (error) => ({ terminating: false, error, details: ['Failed to install dependencies'] }) }; ``` -------------------------------- ### Install Yarn Dev Dependency Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/dependencies.md Example of how to install a development dependency using yarn. ```bash yarn add [--dev] {dependency} ``` ```bash yarn add --dev @datadog/datadog-ci ``` -------------------------------- ### Install npm Dev Dependency Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/dependencies.md Example of how to install a development dependency using npm. ```bash npm install [--save-dev] {dependency} ``` ```bash npm install --save-dev @datadog/datadog-ci ``` -------------------------------- ### Basic Programmatic Setup Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/setup-command.md Demonstrates basic programmatic usage of SetupCommand. Sets the project path and executes the setup process, relying on interactive prompts for other configurations. ```typescript import { SetupCommand } from 'datadog-react-native-wizard'; const command = new SetupCommand(); command.absoluteProjectPath = '/Users/me/MyApp'; await command.execute(); ``` -------------------------------- ### Install Dependency with Output Streaming Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/dependencies.md Installs a dependency by building and executing an install command, then streaming the output. Throws an error if the installation process fails. ```typescript public async installDependency(output: Output): Promise ``` -------------------------------- ### SetupCommandStateType Example Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/types.md An example of how to initialize the `SetupCommandStateType` with specific values. Note that `bypassPrompts` is required. ```typescript const state: SetupCommandStateType = { androidMinificationEnabled: true, apiKey: 'ddrm_***', bypassPrompts: true, datadogSite: 'US1', intakeUrl: undefined }; ``` -------------------------------- ### Non-Interactive CLI Setup Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/setup-command.md Shows how to use SetupCommand via the CLI with arguments for non-interactive setup. Includes API key, Datadog site, bypass prompts, and Android minification options. ```bash npx datadog-react-native-wizard /Users/me/MyApp \ --api-key YOUR_API_KEY \ --datadog-site US1 \ --bypass-prompts \ --android-minification ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/CONTRIBUTING.md Run this command in the root directory to install all necessary dependencies for the project packages. ```bash yarn install ``` -------------------------------- ### Programmatic Setup with Custom Intake URL Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/setup-command.md Illustrates advanced programmatic usage of SetupCommand. Configures project path, API key, Datadog site, custom intake URL, and bypasses prompts for a non-interactive setup. ```typescript const command = new SetupCommand(); command.absoluteProjectPath = '/Users/me/MyApp'; command.apiKey = 'your-api-key'; command.datadogSite = 'EU1'; command.intakeUrl = 'https://custom.intake.datadoghq.eu'; command.bypassPrompts = true; await command.execute(); ``` -------------------------------- ### Example Usage of PackageManager Type Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/types.md Shows how to get the package manager for a given path and conditionally execute logic based on the result. ```typescript const pm: PackageManager = getPackageManager('/Users/me/MyApp'); if (pm === 'npm') { // Use npm-specific installation logic } ``` -------------------------------- ### Example Usage of addDependencies Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/dependencies.md Demonstrates how to import and use the `addDependencies` function. It includes basic error handling for installation failures. ```typescript import { addDependencies } from './add-dependencies'; const output = { stdout: process.stdout, stderr: process.stderr }; try { await addDependencies('/Users/me/MyApp', output); console.log('Dependencies installed successfully'); } catch (error) { console.error('Failed to add dependencies:', error.message); } ``` -------------------------------- ### Execute Setup Command Programmatically Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/README.md Instantiate and execute the `SetupCommand` programmatically, setting project path, API key, and site. Supports bypassing prompts. ```typescript import { SetupCommand } from './setup'; const command = new SetupCommand(); command.absoluteProjectPath = '/Users/me/MyApp'; command.apiKey = 'your-api-key'; command.datadogSite = 'EU1'; command.bypassPrompts = true; await command.execute(); ``` -------------------------------- ### Example Usage of DependencyVersion Type Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/types.md Illustrates initializing a DependencyVersion object and provides examples of how version strings are parsed into this format. ```typescript const version: DependencyVersion = { major: 0, minor: 72, patch: '3' }; // Version string "0.72.3" → { major: 0, minor: 72, patch: "3" } // Version string "1.2.0-rc1" → { major: 1, minor: 2, patch: "0-rc1" } ``` -------------------------------- ### SetupCommandInitialStateType Example and Validation Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/types.md Demonstrates initializing the `SetupCommandInitialStateType` with raw CLI arguments and then validating it using `validateInitialState` to convert it to `SetupCommandStateType`. ```typescript const initialState: SetupCommandInitialStateType = { datadogSite: 'EU1', // String, not yet validated apiKey: 'ddrm_***', bypassPrompts: true }; // After validation: const validState: SetupCommandStateType = validateInitialState(initialState); // Now datadogSite is type-checked as DatadogSite ``` -------------------------------- ### SetupCommand Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/setup-command.md CLI command that orchestrates all setup steps to configure automatic sourcemap, dSYM, and Proguard mapping uploads. Executed via `npx datadog-react-native-wizard`. ```APIDOC ## Class: SetupCommand CLI command that extends `Command` from the Clipanion CLI framework. Executed via `npx datadog-react-native-wizard`. ### Constructor and Options ```typescript class SetupCommand extends Command { absoluteProjectPath: string; // Option.String({ required: false }) androidMinificationEnabled: boolean; // Option.Boolean("--android-minification") apiKey: string; // Option.String("--api-key", { required: false }) bypassPrompts: boolean; // Option.Boolean("--bypass-prompts") intakeUrl: string; // Option.String("--intake-url", { required: false }) datadogSite: string; // Option.String("--datadog-site", { required: false }) } ``` | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | absoluteProjectPath | string | No | `process.cwd()` | Absolute path to the React Native project root. If not provided, uses current working directory | | androidMinificationEnabled | boolean | No | false | Enable Android minification/obfuscation and Proguard mapping upload | | apiKey | string | No | undefined | Datadog API key for uploading artifacts. Can be provided via CLI or interactive prompt | | bypassPrompts | boolean | No | false | Skip all interactive prompts. When enabled, must provide apiKey | | intakeUrl | string | No | undefined | Custom intake URL for Datadog (optional). Used when organization has a proxy or custom endpoint | | datadogSite | string | No | "US1" | Datadog site selection (US1, EU1, US3, US5, GOV). Must be a valid DatadogSite value | ### Method: execute ```typescript async execute(): Promise ``` Main command execution method. Orchestrates all setup steps in sequence: 1. **Get sourcemaps upload variables** — Collects Datadog API key and site configuration, creates `datadog-ci.json` 2. **Add required dependencies** — Installs `@datadog/datadog-ci` (v2.5.0 or later) 3. **Automate sourcemaps upload on iOS builds** — Modifies Xcode build phases to upload sourcemaps 4. **Automate sourcemaps upload on Android builds** — Injects Gradle task into Android build 5. **Automate dSYMs upload on iOS builds** — Adds dSYM upload build phase to Xcode 6. **Automate Proguard mapping upload on Android builds** — Injects Gradle plugin for mapping files **Returns:** void (exit code set via `process.exitCode`) **Throws:** - `ReactNativeProjectError` — if project is not a valid React Native project - `DatadogSiteValueNotValid` — if invalid datadogSite provided - `ApiKeyNotProvided` — if bypassPrompts enabled but no apiKey provided - `DatadogCiConfigFileAlreadyExists` — if datadog-ci.json already exists - Various platform-specific errors during iOS/Android configuration ### Usage Examples Basic usage (interactive prompts): ```typescript import { SetupCommand } from 'datadog-react-native-wizard'; const command = new SetupCommand(); command.absoluteProjectPath = '/Users/me/MyApp'; await command.execute(); ``` With CLI arguments (non-interactive): ```bash npx datadog-react-native-wizard /Users/me/MyApp \ --api-key YOUR_API_KEY \ --datadog-site US1 \ --bypass-prompts \ --android-minification ``` Current directory (uses `process.cwd()`): ```bash cd /path/to/rn/project npx datadog-react-native-wizard ``` Programmatic usage with custom intake URL: ```typescript const command = new SetupCommand(); command.absoluteProjectPath = '/Users/me/MyApp'; command.apiKey = 'your-api-key'; command.datadogSite = 'EU1'; command.intakeUrl = 'https://custom.intake.datadoghq.eu'; command.bypassPrompts = true; await command.execute(); ``` ``` -------------------------------- ### npmDependencyInstaller Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/dependencies.md Handles dependency installation using npm. It defines the command format for installing npm packages, including options for development dependencies. ```APIDOC ## Class: npmDependencyInstaller Implementation of DependencyInstaller for npm. ```typescript class npmDependencyInstaller extends DependencyInstaller { protected buildInstallCommand(): string } ``` **Install Command Format:** ``` npm install [--save-dev] {dependency} ``` **Example:** - Dev dependency: `npm install --save-dev @datadog/datadog-ci` - Regular dependency: `npm install react-native` ``` -------------------------------- ### StepsCommand Usage Example Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/steps-command.md Demonstrates how to instantiate and run a StepsCommand for initializing an application, including state definition, validation, and step configuration. ```typescript import { StepsCommand } from 'src/utils/StepsCommand/StepsCommand'; type AppState = { apiKey: string; site: string }; type AppInitialState = { apiKey?: string; site?: string }; const stepsCommand = new StepsCommand({ name: 'Initialize Application', output: { stdout: process.stdout, stderr: process.stderr }, initialState: { apiKey: undefined, site: undefined }, storeValidator: (initial) => { if (!initial.apiKey) throw new Error('API key required'); return { apiKey: initial.apiKey, site: initial.site || 'US1' }; }, storeValidatorErrorHandler: (error) => { return `Validation failed: ${(error as Error).message}`; }, steps: [ { name: 'Configure API', stepFunction: async (store) => { console.log(`Using API key: ${store.get().apiKey}`); }, errorHandler: async (error) => ({ terminating: true, error, details: ['API configuration failed'] }) }, { name: 'Test Connection', stepFunction: async (store) => { // store.set() updates the state for next steps store.set(s => ({ ...s, site: 'EU1' })); }, errorHandler: async (error) => ({ terminating: false, error }) } ] }); const exitCode = await stepsCommand.run(); process.exit(exitCode); ``` -------------------------------- ### Example Usage of Output Type Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/types.md Demonstrates how to initialize an Output type with process.stdout and process.stderr and use it with a command. ```typescript const output: Output = { stdout: process.stdout, stderr: process.stderr }; await stepsCommand.run(output); ``` -------------------------------- ### Abstract Dependency Installer Class Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/dependencies.md Base class for defining package manager-specific dependency installation logic. Subclasses must implement the buildInstallCommand method. ```typescript abstract class DependencyInstaller { protected dependency: string; protected options: { dev?: boolean; absoluteProjectPath: string }; protected abstract buildInstallCommand(): string; public async installDependency(output: Output): Promise } ``` ```typescript constructor( dependency: string, options: { dev?: boolean; absoluteProjectPath: string } ) ``` -------------------------------- ### Configuration File Example Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/README.md Use this JSON structure in your datadog-ci.json file to configure the wizard. Ensure you replace 'your-api-key' and 'datadoghq.eu' with your actual credentials and desired Datadog site. ```json { "apiKey": "your-api-key", "datadogSite": "datadoghq.eu" } ``` -------------------------------- ### startStep Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/printer.md Prints a message indicating that a step is starting its execution, prefixed with a gear emoji. ```APIDOC ## Method: startStep ```typescript public startStep(name: string): void ``` Prints a message when a step starts executing. **Output Format:** ``` ⚙️ Running task: {name}. ``` **Example:** ```typescript printer.startStep('add required dependencies'); // Output: ⚙️ Running task: add required dependencies. ``` ``` -------------------------------- ### yarnDependencyInstaller Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/dependencies.md Handles dependency installation using yarn. It defines the command format for installing yarn packages, including options for development dependencies. ```APIDOC ## Class: yarnDependencyInstaller Implementation of DependencyInstaller for yarn. ```typescript class yarnDependencyInstaller extends DependencyInstaller { protected buildInstallCommand(): string } ``` **Install Command Format:** ``` yarn add [--dev] {dependency} ``` **Example:** - Dev dependency: `yarn add --dev @datadog/datadog-ci` - Regular dependency: `yarn add react-native` ``` -------------------------------- ### Run Datadog React Native Wizard Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/README.md Execute the wizard at the root of your React Native application to initiate the setup process. ```bash npx datadog-react-native-wizard ``` -------------------------------- ### Yarn Dependency Installer Class Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/dependencies.md Defines the structure for a yarn dependency installer. Use this when managing yarn packages. ```typescript class yarnDependencyInstaller extends DependencyInstaller { protected buildInstallCommand(): string } ``` -------------------------------- ### npm Dependency Installer Class Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/dependencies.md Defines the structure for an npm dependency installer. Use this when managing npm packages. ```typescript class npmDependencyInstaller extends DependencyInstaller { protected buildInstallCommand(): string } ``` -------------------------------- ### Example Usage of getPackageManager Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/configuration.md Demonstrates how to import and use the getPackageManager function to detect and log the project's package manager. ```typescript import { getPackageManager } from './get-package-manager'; const pm = getPackageManager('/Users/me/MyApp'); console.log(`Using package manager: ${pm}`); ``` -------------------------------- ### Start Step Execution Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/printer.md Prints a message with a gear icon when a step begins executing. This helps in visualizing the progress of tasks within a command. ```typescript printer.startStep('add required dependencies'); ``` -------------------------------- ### DatadogSite Usage Example Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/types.md Demonstrates how to import and use the DatadogSite type and related constants in your project. Ensures that the provided site is included in the list of valid sites. ```typescript import { DatadogSite, datadogSites, DEFAULT_DATADOG_SITE } from './interface'; const site: DatadogSite = 'EU1'; console.log(datadogSites.includes(site)); // true ``` -------------------------------- ### Example Usage of printEndMessage Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/printer.md An example demonstrating how to use the printEndMessage method with sample step results, including a successful step and an erroring step. This shows how to pass results and the terminating error. ```typescript const results: StepResult[] = [ { status: 'success', name: 'Step 1' }, { status: 'error', status: 'error', terminating: true, name: 'Step 2', error: new Error('failed') } ]; printer.printEndMessage( results, 'Setup', results[1] as ErrorStepResult ); ``` -------------------------------- ### SetupCommand execute Method Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/setup-command.md The main execution method for SetupCommand. It orchestrates the sequential steps for configuring sourcemap, dSYM, and Proguard mapping uploads, including dependency installation and build phase modifications. ```typescript async execute(): Promise ``` -------------------------------- ### Example Usage of changeXCodeBuildPhase Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/ios-build-phase.md Demonstrates how to use the `changeXCodeBuildPhase` function to update the Xcode build phase. Includes error handling for potential issues during the process. ```typescript import { changeXCodeBuildPhase } from './change-xcode-build-phase'; try { await changeXCodeBuildPhase('/Users/me/MyApp'); console.log('Xcode build phase updated successfully'); } catch (error) { console.error('Failed to modify Xcode build phase:', error.message); } ``` -------------------------------- ### DependencyInstaller Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/dependencies.md Abstract base class for installing dependencies using package managers. ```APIDOC ## Abstract Class: DependencyInstaller ### Description Base class for package manager-specific dependency installation. Provides a common interface for installing packages, handling options like dev dependencies, and managing output streams. ### Constructor ```typescript constructor(dependency: string, options: { dev?: boolean; absoluteProjectPath: string }) ``` #### Parameters - **dependency** (string) - Required - Package name to install - **options.dev** (boolean) - Optional - If true, installs as a dev dependency - **options.absoluteProjectPath** (string) - Required - Project root path for execution context ### Method: installDependency #### Description Executes the install command and streams output to provided streams. #### Signature ```typescript public async installDependency(output: Output): Promise ``` #### Parameters - **output** (Output) - Object with stdout/stderr WriteStreams #### Throws - Error with message pattern `error {signal} while installing` if process exits with non-zero status. #### Behavior 1. Builds install command (implementation in subclass) 2. Executes command in project directory 3. Streams stdout/stderr to provided output 4. Waits for process to complete 5. Throws if exit code is non-zero ``` -------------------------------- ### ConfigurationData Example Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/types.md Illustrates how to create an instance of ConfigurationData with specific values for API key and site. This type is used for collecting and persisting configuration for artifact uploads. ```typescript const config: ConfigurationData = { apiKey: 'ddrm_***', site: 'EU1', intakeUrl: undefined }; ``` -------------------------------- ### Handle GradlePluginNotInstalled Error Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/errors.md Example demonstrating how to catch and handle the GradlePluginNotInstalled error. This is useful for providing specific user guidance when the build.gradle file is not in the expected format. ```typescript import { GradlePluginNotInstalled } from './errors'; try { await injectPluginInBuildGradle(inputFile, outputFile); } catch (error) { if (error instanceof GradlePluginNotInstalled) { console.error('Unable to inject plugin: build.gradle missing plugins block'); } } ``` -------------------------------- ### Store get Method Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/steps-command.md Retrieves the current state from the Store. Use this to access the state within a step. ```typescript public get(): StateType ``` ```typescript const state = store.get(); console.log(state.apiKey); ``` -------------------------------- ### Compare Dependency Versions Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/README.md Compare installed dependency versions against required versions using utility functions. Helps determine compatibility. ```typescript import { isDependencyVersionOver, formatDependencyVersion } from './dependency-utils'; const installed = formatDependencyVersion('1.2.3'); const required = '1.0.0'; if (isDependencyVersionOver(installed, required)) { console.log('Version is compatible'); } ``` -------------------------------- ### Example Usage of formatDependencyVersion Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/version-utilities.md Demonstrates how to use the `formatDependencyVersion` function with different version strings and log the parsed components. It shows how to access major, minor, and patch from the returned object. ```typescript import { formatDependencyVersion } from './dependency-utils'; const parsed = formatDependencyVersion('0.72.3'); console.log(parsed.major); // 0 console.log(parsed.minor); // 72 console.log(parsed.patch); // '3' const rc = formatDependencyVersion('1.0.0-rc1'); console.log(rc.patch); // '0-rc1' ``` -------------------------------- ### RN69BuildPhaseEditor Usage Example Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/ios-build-phase.md Instantiates and uses RN69BuildPhaseEditor, specifying the minor React Native version for newer projects. ```typescript const editor = new RN69BuildPhaseEditor( { absoluteProjectPath: '/Users/me/MyApp', inputPbxprojFile: 'ios/MyApp.xcodeproj/project.pbxproj', outputPbxprojFile: 'ios/MyApp.xcodeproj/project.pbxproj' }, { minorRNVersion: 72 } ); await editor.editBuildPhase(); ``` -------------------------------- ### Setup Command Validator Configuration Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/errors.md This TypeScript snippet illustrates how the SetupCommand configures its storeValidator and storeValidatorErrorHandler to handle custom errors during the initial state validation process. ```typescript storeValidator: validateInitialState, // Throws custom errors storeValidatorErrorHandler: handleValidationError, // Converts to user message ``` -------------------------------- ### Capture Output for Logging Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/printer.md Example of capturing stdout and stderr streams to a buffer for logging or display in a UI. This is useful for non-interactive modes. ```typescript import { Writable } from 'stream'; const capturedStdout = new Writable({ write(chunk, encoding, callback) { logBuffer.push(chunk.toString()); callback(); } }); const output: Output = { stdout: capturedStdout as WriteStream, stderr: capturedStdout as WriteStream }; const stepsCommand = new StepsCommand({ ..., output }); await stepsCommand.run(); const allOutput = logBuffer.join(''); ``` -------------------------------- ### Run Datadog React Native Wizard in Non-Interactive Mode Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/configuration.md Use this command for non-interactive setup, providing all necessary configuration options directly. This mode requires the API key and bypasses all prompts. ```bash npx datadog-react-native-wizard /Users/me/MyApp \ --api-key YOUR_API_KEY \ --datadog-site EU1 \ --bypass-prompts \ --android-minification ``` -------------------------------- ### Print Command Name Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/printer.md Prints the command name at the beginning of execution, formatted with bold text. This is useful for indicating the start of a specific command. ```typescript printer.printCommandName('Setup the automated upload of javascript sourcemaps to Datadog'); ``` -------------------------------- ### Usage Example: isDependencyVersionOver Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/version-utilities.md Demonstrates how to use the `isDependencyVersionOver` function with different version scenarios, including prerelease versions. Ensure `formatDependencyVersion` is imported and used to parse version strings. ```typescript import { isDependencyVersionOver, formatDependencyVersion } from './dependency-utils'; const v1 = formatDependencyVersion('1.2.3'); const v2 = formatDependencyVersion('1.2.0-rc1'); isDependencyVersionOver(v1, '1.2.0'); // true (1.2.3 >= 1.2.0) isDependencyVersionOver(v1, '1.2.3'); // true (1.2.3 >= 1.2.3) isDependencyVersionOver(v1, '1.3.0'); // false (1.2.3 < 1.3.0) isDependencyVersionOver(v2, '1.2.0'); // true (1.2.0-rc1 >= 1.2.0) isDependencyVersionOver(v2, '1.2.0-rc2'); // false (1.2.0-rc1 < 1.2.0-rc2) ``` -------------------------------- ### Run Datadog React Native Wizard in Interactive Mode Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/configuration.md Use this command to start the wizard in interactive mode, which will prompt for configuration details. Provide the absolute path to your React Native project. ```bash npx datadog-react-native-wizard /Users/me/MyApp ``` -------------------------------- ### Handle DatadogCiConfigFileAlreadyExists Error Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/errors.md Example of how to catch and handle the DatadogCiConfigFileAlreadyExists error. This is useful when you need to inform the user to remove the existing configuration file before proceeding. ```typescript import { DatadogCiConfigFileAlreadyExists } from './errors'; try { await createConfigurationFiles(projectPath, store); } catch (error) { if (error instanceof DatadogCiConfigFileAlreadyExists) { console.error('datadog-ci.json already exists. Remove it to reconfigure.'); } } ``` -------------------------------- ### Get Dependency Installer Factory Function Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/dependencies.md Factory function to retrieve the correct dependency installer based on project configuration. It detects the package manager by checking for 'package-lock.json'. ```typescript function getDependencyInstaller( dependency: string, options: { dev?: boolean; absoluteProjectPath: string } ): DependencyInstaller ``` ```typescript import { getDependencyInstaller } from './get-dependency-installer'; const installer = getDependencyInstaller('@datadog/datadog-ci', { dev: true, absoluteProjectPath: '/Users/me/MyApp' }); await installer.installDependency({ stdout: process.stdout, stderr: process.stderr }); ``` -------------------------------- ### Get React Native Version Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/version-utilities.md Extracts the React Native version from a project's package.json. Use this to determine the specific React Native version installed in your project. ```typescript import { getRNVersion } from './dependency-utils'; const version = getRNVersion('/Users/me/MyApp'); console.log(`React Native: ${version.major}.${version.minor}.${version.patch}`); // Output: React Native: 0.72.3 ``` -------------------------------- ### Get Datadog SDK Version Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/version-utilities.md Extracts the @datadog/mobile-react-native SDK version from a project's package.json. Use this to check the installed Datadog SDK version and ensure it meets minimum requirements. ```typescript import { getDatadogVersion } from './dependency-utils'; const version = getDatadogVersion('/Users/me/MyApp'); if (version.major < 1) { throw new Error('Datadog SDK too old'); } ``` -------------------------------- ### Typical Printer Initialization Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/printer.md Demonstrates the typical usage for initializing the Printer class. It shows how to create an Output object using process.stdout and process.stderr, and then instantiate the Printer with this output. ```typescript const output: Output = { stdout: process.stdout, stderr: process.stderr }; const printer = new Printer(output); ``` -------------------------------- ### SetupCommand Class Definition Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/setup-command.md Defines the SetupCommand class, extending Clipanion's Command. It includes properties for project path, API key, Datadog site, and options for enabling minification and bypassing prompts. ```typescript class SetupCommand extends Command { absoluteProjectPath: string; // Option.String({ required: false }) androidMinificationEnabled: boolean; // Option.Boolean("--android-minification") apiKey: string; // Option.String("--api-key", { required: false }) bypassPrompts: boolean; // Option.Boolean("--bypass-prompts") intakeUrl: string; // Option.String("--intake-url", { required: false }) datadogSite: string; // Option.String("--datadog-site", { required: false }) } ``` -------------------------------- ### Example Step Error Handler Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/types.md Provides an example of a step error handler function that returns a StepError object, indicating termination and providing specific details. ```typescript const errorHandler = async (error: unknown): Promise => { return { terminating: true, error, details: [ 'React Native project not found', 'Make sure you are in the project root' ] }; }; ``` -------------------------------- ### SetupCommandInitialStateType Definition Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/setup-command.md Defines the initial state type for SetupCommand, derived from CLI arguments. Fields are optional, and datadogSite is initially a string before validation. ```typescript type SetupCommandInitialStateType = { androidMinificationEnabled?: boolean; apiKey?: string; bypassPrompts?: boolean; datadogSite?: string; intakeUrl?: string; }; ``` -------------------------------- ### checkDependencyStatus Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/dependencies.md Checks the installation status of a dependency against a minimum required version. It reads the project's `package.json` to determine if the dependency is installed and if its version meets the specified minimum. ```APIDOC ## Function: checkDependencyStatus ### Description Checks the installation status of a dependency against a minimum required version. It reads the project's `package.json` to determine if the dependency is installed and if its version meets the specified minimum. ### Signature ```typescript function checkDependencyStatus( dependencyName: string, minVersion: string, options: { absoluteProjectPath: string } ): 'NOT_INSTALLED' | 'OK' | 'OUTDATED' ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters * **dependencyName** (string) - Required - NPM package name (e.g., '@datadog/datadog-ci') * **minVersion** (string) - Required - Minimum required semantic version (e.g., '2.5.0') * **options.absoluteProjectPath** (string) - Required - Absolute path to project root containing package.json ### Returns Status string: - `'NOT_INSTALLED'` — dependency not in devDependencies - `'OK'` — installed version >= minVersion - `'OUTDATED'` — installed version < minVersion ### Example ```typescript import { checkDependencyStatus } from './check-dependency-status'; const status = checkDependencyStatus( '@datadog/datadog-ci', '2.5.0', { absoluteProjectPath: '/Users/me/MyApp' } ); switch (status) { case 'NOT_INSTALLED': console.log('Install the dependency'); break; case 'OUTDATED': console.log('Upgrade the dependency'); break; case 'OK': console.log('Dependency is up to date'); } ``` ``` -------------------------------- ### Check Dependency Installation Status Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/dependencies.md Verifies if a dependency is installed and meets the minimum version requirement. Reads the project's package.json to check devDependencies and compares semantic versions. ```typescript import { checkDependencyStatus } from './check-dependency-status'; const status = checkDependencyStatus( '@datadog/datadog-ci', '2.5.0', { absoluteProjectPath: '/Users/me/MyApp' } ); switch (status) { case 'NOT_INSTALLED': console.log('Install the dependency'); break; case 'OUTDATED': console.log('Upgrade the dependency'); break; case 'OK': console.log('Dependency is up to date'); } ``` -------------------------------- ### Catch ApiKeyNotProvided Error in Example Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/errors.md This TypeScript example shows how to use a try-catch block to handle the ApiKeyNotProvided error, specifically when validating initial state with bypassPrompts enabled and an undefined API key. ```typescript import { ApiKeyNotProvided } from './errors'; try { const state = validateInitialState({ bypassPrompts: true, apiKey: undefined }); } catch (error) { if (error instanceof ApiKeyNotProvided) { console.error('API key required when using --bypass-prompts'); } } ``` -------------------------------- ### Handle GradlePluginNotAutomated Error Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/errors.md Example of how to catch and handle a `GradlePluginNotAutomated` error during the `injectPluginInBuildGradle` process. ```typescript import { GradlePluginNotAutomated } from './errors'; try { await injectPluginInBuildGradle(inputFile, outputFile); } catch (error) { if (error instanceof GradlePluginNotAutomated) { console.error('Unable to find android block to configure automation'); } } ``` -------------------------------- ### Run Datadog React Native Wizard from Current Directory Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/configuration.md Configure the wizard for the current directory by navigating to your project first and then running the CLI with specified options. This is useful for quick configurations without needing to specify the full project path. ```bash cd /Users/me/MyApp npx datadog-react-native-wizard \ --api-key ddrm_*** \ --datadog-site US1 \ --bypass-prompts ``` -------------------------------- ### Detect React Native Version Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/README.md Retrieve the major, minor, and patch version of React Native installed in a project. ```typescript import { getRNVersion } from './dependency-utils'; const version = getRNVersion('/Users/me/MyApp'); console.log(`React Native: ${version.major}.${version.minor}.${version.patch}`); ``` -------------------------------- ### RN63BuildPhaseEditor Usage Example Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/ios-build-phase.md Instantiates and uses RN63BuildPhaseEditor to modify the build phase for older React Native projects. ```typescript const editor = new RN63BuildPhaseEditor({ absoluteProjectPath: '/Users/me/MyApp', inputPbxprojFile: 'ios/MyApp.xcodeproj/project.pbxproj', outputPbxprojFile: 'ios/MyApp.xcodeproj/project.pbxproj' }); await editor.editBuildPhase(); ``` -------------------------------- ### Check Datadog Dependency Status Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/README.md Programmatically check the installation status of a Datadog dependency within your React Native project. ```typescript import { checkDependencyStatus } from './check-dependency-status'; const status = checkDependencyStatus( '@datadog/datadog-ci', '2.5.0', { absoluteProjectPath: '/Users/me/MyApp' } ); // status: 'NOT_INSTALLED' | 'OK' | 'OUTDATED' ``` -------------------------------- ### StepsCommand Constructor Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/steps-command.md Initializes a new StepsCommand instance. It takes an object containing steps, command name, output streams, initial state, a state validator, and a validation error handler. ```APIDOC ## Constructor StepsCommand ### Description Initializes a new StepsCommand instance. It takes an object containing steps, command name, output streams, initial state, a state validator, and a validation error handler. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **steps** (Step[]) - Required - Array of step definitions to execute sequentially - **name** (string) - Required - Human-readable name of the command (printed at start and end) - **output** (Output) - Required - Object with stdout and stderr WriteStreams for output - **initialState** (InitialStateType) - Required - Raw initial state from user input or CLI arguments - **storeValidator** (function) - Required - Function that validates and transforms initialState into StateType. Throws on validation failure - **storeValidatorErrorHandler** (function) - Required - Function that converts validation errors into user-facing error messages ``` -------------------------------- ### Test Changes Locally with a Project Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/CONTRIBUTING.md Execute your command with the absolute path to your test project to verify changes in a real environment. ```bash yarn launch my-command /Users/me/MyTestProject ``` -------------------------------- ### createConfigurationFiles Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/configuration.md Creates the datadog-ci.json configuration file in the React Native project. It retrieves configuration data, updates the store, checks for existing files, generates content, and writes the file to the project root. ```APIDOC ## Function: createConfigurationFiles ### Description Creates the datadog-ci.json configuration file in the React Native project. It retrieves configuration data, updates the store, checks for existing files, generates content, and writes the file to the project root. ### Signature ```typescript async function createConfigurationFiles( absoluteProjectPath: string, store: Store<{ apiKey?: string; bypassPrompts: boolean; datadogSite?: DatadogSite; intakeUrl?: string; }> ): Promise ``` ### Parameters #### Path Parameters - **absoluteProjectPath** (string) - Required - Absolute path to React Native project root - **store** (Store) - Required - State store containing user input and configuration ### Returns - Promise - Resolves when configuration file is written ### Throws - **DatadogCiConfigFileAlreadyExists** - if datadog-ci.json already exists in project root ### Example ```typescript import { createConfigurationFiles } from './create-configuration-files'; import { Store } from '../../../utils/StepsCommand/Store'; const store = new Store({ apiKey: 'your-api-key', bypassPrompts: true, datadogSite: 'US1', intakeUrl: undefined }); try { await createConfigurationFiles('/Users/me/MyApp', store); console.log('Configuration file created'); } catch (error) { console.error('Failed to create configuration:', error.message); } ``` ``` -------------------------------- ### Create Custom Steps Command Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/README.md Define and run a custom wizard-like command with multiple steps, state management, and validation using `StepsCommand`. ```typescript import { StepsCommand } from './utils/StepsCommand/StepsCommand'; type State = { apiKey: string; site: string }; type InitialState = { apiKey?: string; site?: string }; const command = new StepsCommand({ name: 'My Setup', output: { stdout: process.stdout, stderr: process.stderr }, initialState: { apiKey: undefined, site: undefined }, storeValidator: (initial) => ({ apiKey: initial.apiKey || 'default', site: initial.site || 'US1' }), storeValidatorErrorHandler: (error) => `Validation failed: ${error}`, steps: [ { name: 'Step 1', stepFunction: async (store) => { const state = store.get(); // Do work }, errorHandler: async (error) => ({ terminating: true, error }) } ] }); await command.run(); ``` -------------------------------- ### StepsCommand.run() Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/steps-command.md Executes all defined steps sequentially. It handles initial state validation, step execution, error handling, and progress reporting, returning an exit code indicating success or failure. ```APIDOC ## Method: run ### Description Executes all steps sequentially and returns exit code. **Process:** 1. Validates initialState using storeValidator. If validation fails, prints error and returns 1 2. Creates a Store with validated state 3. Executes each step in order: - If a prior step failed with `terminating: true`, skips remaining steps - Passes Store to step function so it can read/update state - Calls errorHandler if step throws 4. Prints final summary of all step results ### Method `public run(): Promise` ### Parameters None ### Response #### Success Response (0) - Returns `0` if all steps succeeded #### Error Response (1) - Returns `1` if any step failed with `terminating: true` or if initial validation failed ``` -------------------------------- ### Handle DatadogSiteValueNotValid Error Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/errors.md Example of how to catch and handle a `DatadogSiteValueNotValid` error when validating initial state, displaying the invalid site and valid options. ```typescript import { DatadogSiteValueNotValid } from './errors'; try { const state = validateInitialState({ datadogSite: 'INVALID' }); } catch (error) { if (error instanceof DatadogSiteValueNotValid) { console.error(`Invalid site: ${error.site}`); console.error('Valid sites: US1, EU1, US3, US5, GOV'); } } ``` -------------------------------- ### Check Dependency Status Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/version-utilities.md Verifies if a specific dependency is installed and meets a minimum version requirement. This function internally uses version comparison utilities. ```typescript // Check if @datadog/datadog-ci is installed and recent enough const status = checkDependencyStatus( '@datadog/datadog-ci', '2.5.0', { absoluteProjectPath } ); // Uses isDependencyVersionOver internally to compare versions ``` -------------------------------- ### Datadog CI Configuration File Structure Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/configuration.md The wizard creates a datadog-ci.json file in the project root. This JSON object defines essential configuration parameters for Datadog integrations. ```json { "apiKey": "your-api-key-here", "datadogSite": "datadoghq.com" } ``` -------------------------------- ### addDependencies Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/dependencies.md Adds or upgrades the `@datadog/datadog-ci` dependency to the React Native project. It validates the project, checks for the required version, and installs it using npm or yarn. ```APIDOC ## Function: addDependencies ### Description Adds or upgrades the `@datadog/datadog-ci` dependency to the React Native project. It validates the project, checks for the required version, and installs it using npm or yarn. ### Signature ```typescript async function addDependencies(absoluteProjectPath: string, output: Output): Promise ``` ### Parameters #### Path Parameters - **absoluteProjectPath** (string) - Required - Absolute path to React Native project root - **output** (Output) - Required - Object with stdout and stderr WriteStreams for displaying installation progress ### Returns Promise that resolves when dependency installation completes. ### Throws - `ReactNativeProjectError` — if project does not have react-native in dependencies - Installation error from npm/yarn if installation fails ### Example ```typescript import { addDependencies } from './add-dependencies'; const output = { stdout: process.stdout, stderr: process.stderr }; try { await addDependencies('/Users/me/MyApp', output); console.log('Dependencies installed successfully'); } catch (error) { console.error('Failed to add dependencies:', error.message); } ``` ``` -------------------------------- ### SetupCommandStateType Definition Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/setup-command.md Defines the internal state type for SetupCommand execution. Includes optional fields for minification, API key, Datadog site, and intake URL, with bypassPrompts being mandatory. ```typescript type SetupCommandStateType = { androidMinificationEnabled?: boolean; apiKey?: string; bypassPrompts: boolean; datadogSite?: DatadogSite; intakeUrl?: string; }; ``` -------------------------------- ### Delivered Documentation Files Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/MANIFEST.md Lists the files included in the documentation package, along with their line counts and a brief description. This helps users navigate the documentation. ```text /workspace/home/output/ ├── README.md [380 lines] - Start here ├── INDEX.md [Quick index] ├── MANIFEST.md [This file] ├── types.md [388 lines] - All type definitions ├── errors.md [372 lines] - Error reference ├── configuration.md [288 lines] - CLI & config options └── api-reference/ ├── setup-command.md [130 lines] - Main CLI entry point ├── steps-command.md [251 lines] - Step orchestration ├── dependencies.md [281 lines] - Dependency management ├── ios-build-phase.md [289 lines] - iOS Xcode setup ├── android-gradle.md [299 lines] - Android Gradle setup ├── configuration.md [403 lines] - Config utilities ├── version-utilities.md [261 lines] - Version parsing └── printer.md [380 lines] - Output formatting **Total:** 13 files, 3,722+ lines of documentation ``` -------------------------------- ### StepsCommand Constructor Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/steps-command.md Initializes a new StepsCommand instance with configuration for steps, name, output, initial state, and validation. ```typescript constructor({ steps, name, output, initialState, storeValidator, storeValidatorErrorHandler }: { steps: Step[]; name: string; output: Output; initialState: InitialStateType; storeValidator: (initialState: InitialStateType) => StateType; storeValidatorErrorHandler: (error: unknown) => string; }) ``` -------------------------------- ### getBin Source: https://github.com/datadog/datadog-react-native-wizard/blob/main/_autodocs/api-reference/configuration.md Locates an executable command in the system PATH. This function is useful for finding the absolute path to commands like 'node' or 'npm'. ```APIDOC ## Function: getBin ### Description Locates an executable command in the system PATH. It searches for the command and returns its absolute path, ensuring that the correct executable is used. ### Signature ```typescript function getBin(command: string): Promise ``` ### Parameters #### Path Parameters - **command** (string) - Required - Command name to locate (e.g., 'node', 'npm'). ### Returns - Promise - A Promise resolving to the absolute path to the command. ### Throws - Error if the command is not found in the system's PATH. - Error if the `which -a` command execution fails. ### Behavior 1. Runs `which -a {command}` to find all instances in PATH. 2. Splits results by newlines. 3. Filters out temporary yarn paths. 4. Returns the first valid path found. 5. Throws an error if no valid path is found. ### Example ```typescript import { getBin } from './get-bin'; try { const nodePath = await getBin('node'); console.log(`Node is at: ${nodePath}`); } catch (error) { console.error('Node not found in PATH'); } ``` ```