### Install Dependencies and Run Functions Locally Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/functions/README.md Install project dependencies and start a local server to run the functions. Ensure you are using the correct Node.js version specified in `package.json`. ```bash nvm use 12 npm install npm run serve ``` -------------------------------- ### Example Runtime Configuration Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/configuration.md Provides a concrete example of a populated runtime.json file for both production and staging environments. ```json { "production": { "firebaseProjectId": "ga-dev-tools", "gapiClientId": "123456789-abcdefg.apps.googleusercontent.com", "bitlyClientId": "my-bitly-client-id", "bitlyClientSecret": "my-bitly-secret", "baseUri": "https://ga-dev-tools.web.app", "measurementId": "G-XXXXXXXXXX" }, "staging": { "firebaseProjectId": "ga-dev-tools-staging", "gapiClientId": "987654321-xyz.apps.googleusercontent.com", "bitlyClientId": "my-staging-bitly-id", "bitlyClientSecret": "my-staging-secret", "baseUri": "https://ga-dev-tools-staging.web.app", "measurementId": "G-YYYYYYYYYY" } } ``` -------------------------------- ### Example Usage of configForEnvironment() Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/COMPLETION_SUMMARY.txt Demonstrates how to use the configForEnvironment function, which is documented with example usage. ```typescript configForEnvironment() .then(config => { // Use the configuration }); ``` -------------------------------- ### Run check-config for First Time Setup Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/check-config.md Execute this command to initiate the setup process for the first time. It will prompt for all configuration values, create the runtime.json file, and generate necessary .env files. ```bash yarn run check-config # Prompts for all configuration values # Creates runtime.json # Generates .env files ``` -------------------------------- ### Example .env.production File Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/configuration.md This is an example of the .env.production file generated during the build process. It contains key-value pairs for various service credentials and identifiers. ```env GAPI_CLIENT_ID=123456789-abc.apps.googleusercontent.com BITLY_CLIENT_ID=my-bitly-id AUTH_ENDPOINT=https://us-central1-ga-dev-tools.cloudfunctions.net/bitly_auth GA_MEASUREMENT_ID=G-XXXXXXXXXX ``` -------------------------------- ### Install Dependencies in Lib Directory Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/README.md Navigate to the 'lib' directory and run this command to install its specific dependencies. This is a required step before running the main application. ```shell cd lib yarn cd .. ``` -------------------------------- ### Install Project Dependencies with Yarn Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/README.md Run this command to install all necessary project dependencies using Yarn. Ensure Yarn is installed before executing. ```shell yarn ``` -------------------------------- ### Install Dependencies and Deploy Functions Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/functions/README.md Install project dependencies and deploy the functions to production. Ensure you are using the correct Node.js version specified in `package.json`. ```bash nvm use 12 npm install npm run deploy ``` -------------------------------- ### Start Production App Locally Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/README.md Execute this command from the top-level directory to start a local production instance of the app. You will be prompted for configuration details, such as a Google client ID for authentication. ```shell yarn start:app:production ``` -------------------------------- ### Run Project Tests with Yarn Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/README.md After installing dependencies, use this command to run the project's test suite. Ensure all dependencies are installed first. ```shell yarn test ``` -------------------------------- ### Component Directory Structure Example Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/architecture.md Provides an example of the organizational pattern for React components, including top-level layout, feature-specific components, and utility components. ```text components/ ├── Layout/ # Top-level layout wrapper ├── [Tool Name]/ # Feature-specific components │ ├── index.tsx # Main component export │ ├── use[ToolName].ts # Custom hooks for feature │ ├── types.ts # Feature-specific types │ ├── params.ts # URL/form parameter handling │ └── [SubComponent]/ # Nested feature components └── [Utility]/ # Reusable UI utilities ├── CopyButton.tsx # Generic utilities ├── TextBox.tsx ├── Select.tsx └── ... ``` -------------------------------- ### Check Configuration Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/cli-scripts.md Validates and creates necessary configuration files and environment variables. Use this to ensure your project setup is complete. ```bash node lib/build/index.js check-config [--all] ``` -------------------------------- ### Usage Example for Runtime Configuration Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/configuration.md Load runtime configuration from a JSON file and access environment-specific settings. This demonstrates how to parse and use the configuration object. ```typescript const runtimeConfig = JSON.parse(fs.readFileSync("runtime.json", "utf8")) as RuntimeJson const prodConfig = configForEnvironment(Environment.Production, runtimeConfig) console.log(prodConfig.firebaseProjectId) ``` -------------------------------- ### Programmatic Usage of checkConfig Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/check-config.md Demonstrates how to programmatically use the checkConfig function within your project. This example shows how to get configuration for a specific environment and log the Firebase Project ID. ```typescript import { checkConfig } from "./check-config.js" import { configForEnvironment, Environment } from "./index.js" async function setupProject() { const config = await checkConfig({ cmd: Command.CheckConfig, all: false }) const prodConfig = configForEnvironment(Environment.Production, config) console.log(`Firebase Project: ${prodConfig.firebaseProjectId}`) } setupProject() ``` -------------------------------- ### Running a CLI Command with checkConfig Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/README.md Shows how to use the `checkConfig` function from the CLI to validate configuration. This example specifically sets `all: false` to only prompt for missing values. ```typescript import { checkConfig } from "./check-config.js" import { Command } from "./types.js" const config = await checkConfig({ cmd: Command.CheckConfig, all: false // Only prompt for missing values }) console.log(config.production.firebaseProjectId) ``` -------------------------------- ### Multi-Environment Configuration Example Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/check-config.md Define production and staging environments with distinct Firebase projects, OAuth credentials, and domains using a JSON configuration. This allows for separate deployments to each environment. ```json { "production": { "firebaseProjectId": "ga-dev-tools", "baseUri": "https://ga-dev-tools.web.app", ... }, "staging": { "firebaseProjectId": "ga-dev-tools-staging", "baseUri": "https://ga-dev-tools-staging.web.app", ... } } ``` -------------------------------- ### Gatsby Page Routing Example Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/architecture.md Demonstrates how file structure in `src/pages/` maps to URL routes in a Gatsby application. ```text `/ga4/query-explorer/index.tsx` → `/ga4/query-explorer/` `/campaign-url-builder/index.tsx` → `/campaign-url-builder/` ``` -------------------------------- ### Configuration Structure for Environments Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/README.md Example JSON structure for defining environment-specific configurations, including Firebase project ID, client IDs, and base URI. ```json { "production": { "firebaseProjectId": "ga-dev-tools", "gapiClientId": "xxx-yyy.apps.googleusercontent.com", "bitlyClientId": "xxx", "bitlyClientSecret": "yyy", "baseUri": "https://ga-dev-tools.web.app", "measurementId": "G-XXXXXXXXXX" }, "staging": { /* ... same structure ... */ } } ``` -------------------------------- ### Run checkConfig to get RuntimeJson Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/check-config.md Orchestrates the configuration validation and file generation process. Use this to get the complete runtime configuration object after prompting the user for necessary details. ```typescript import { checkConfig } from "./check-config.js" const config = await checkConfig({ cmd: Command.CheckConfig, all: false }) console.log(config.production.firebaseProjectId) ``` -------------------------------- ### Component Data Flow Example Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/architecture.md Details the data flow within a React component, showing how user input is processed through hooks and persisted to local storage. ```text User Input (TextBox, Select) ↓ useInputs() Hook (reads/writes StorageKey via usePersistent*) ↓ usePersistent* Hook (syncs to localStorage) ↓ useGenerateURL() Hook (computes output) ↓ Component Render (displays result) ``` -------------------------------- ### Development Build Pipeline Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/architecture.md The development build process starts with `yarn run develop`, which executes `lib/scripts/develop.ts`. This script validates configuration, generates a development environment file, and then initiates the Gatsby development server. ```bash yarn run develop ↓ lib/scripts/develop.ts ↓ 1. checkConfig() - Validate configuration 2. writeEnvFile() - Generate .env.development 3. gatsby develop --host=0.0.0.0 --port=5000 ↓ Gatsby dev server on http://localhost:5000 Hot module reloading enabled ``` -------------------------------- ### CORS Header Example Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/endpoints.md This header allows requests from any origin, which is essential for browser-based OAuth flows. ```text Access-Control-Allow-Origin: * ``` -------------------------------- ### Get Environment-Specific Configuration Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/cli-scripts.md Retrieves the appropriate configuration (staging or production) based on the specified environment. Ensure the `runtime.json` file exists and is correctly formatted. ```typescript import { configForEnvironment, Environment } from "./index.js" const runtimeConfig = JSON.parse(fs.readFileSync("runtime.json", "utf8")) const prodConfig = configForEnvironment(Environment.Production, runtimeConfig) console.log(prodConfig.firebaseProjectId) ``` -------------------------------- ### configForEnvironment Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/cli-scripts.md Retrieves environment-specific configuration from the runtime configuration object. This function is used to get the correct configuration for either staging or production environments. ```APIDOC ## configForEnvironment(environment: Environment, config: RuntimeJson) ### Description Retrieves environment-specific configuration from the runtime configuration object. This function is used to get the correct configuration for either staging or production environments. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **environment** (Environment) - Required - Either "production" or "staging" - **config** (RuntimeJson) - Required - The complete runtime configuration object ### Return Type `StagingConfig | ProductionConfig` - The configuration object for the specified environment ### Throws - Logs error and exits with code 1 if environment is not supported ### Example ```typescript import { configForEnvironment, Environment } from "./index.js" const runtimeConfig = JSON.parse(fs.readFileSync("runtime.json", "utf8")) const prodConfig = configForEnvironment(Environment.Production, runtimeConfig) console.log(prodConfig.firebaseProjectId) ``` ``` -------------------------------- ### GAVersion Enum Usage Example Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/constants.md Demonstrates how to use the GAVersion enum to conditionally render UI elements or perform navigation based on the selected Google Analytics version. ```typescript import { GAVersion } from "@/constants" if (gaVersion === GAVersion.GoogleAnalytics4) { // Show GA4-specific UI } else { // Show UA-specific UI } ``` -------------------------------- ### Configuration Flow from User Input to Files Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/architecture.md Shows the process of generating configuration files based on user input through interactive prompts. ```text User Input → Inquirer Prompts → ConfigAnswers → runtime.json + .env files ``` -------------------------------- ### Build and Validate Production Configuration Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/configuration.md Execute this command to build the application for production and validate the configuration. This process checks for the existence and validity of runtime.json, presence of all required values, environment-specific configuration, and successful .env file generation. ```bash yarn run build --environment=production ``` -------------------------------- ### Develop Project Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/cli-scripts.md Runs the local development server with hot-reloading for a specified environment. Use this for local development and testing. ```bash node lib/build/index.js develop --environment= ``` ```bash yarn run develop --environment=production ``` -------------------------------- ### Build Project Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/cli-scripts.md Builds the project for a specified environment after validation and type checking. This is typically used before deployment. ```bash node lib/build/index.js build --environment= ``` -------------------------------- ### Import and Use Constants Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/constants.md Demonstrates how to import and utilize constants for referencing documentation, checking GA versions, and managing persistent storage. ```typescript import { Url, GAVersion, StorageKey } from "@/constants" // Reference external documentation const docLink = Url.ga4DataAPI // Check current version if (gaVersion === GAVersion.GoogleAnalytics4) { // Use GA4-specific code } // Persist user state to localStorage const [dimensions, setDimensions] = usePersistentString( StorageKey.ga4RequestComposerBasicSelectedDimensions ) ``` -------------------------------- ### Check Configuration for Deployment Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/functions/README.md Run this command to ensure all required values are set for a correct deployment. It utilizes `functions.config()` to access environment configuration. ```bash yarn check-config --all ``` -------------------------------- ### CLI Args to Process Execution Data Flow Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/architecture.md Illustrates the data flow from command-line arguments to script execution, including Gatsby builds or Firebase deployments. ```text CLI Args → Parser → Command Handler → Script Logic → Process Execution ↓ Gatsby Build / Firebase Deploy ``` -------------------------------- ### Deploy Application Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/cli-scripts.md Builds and deploys the application to Firebase Hosting for the specified environment. This command is used for production or staging deployments. ```bash node lib/build/index.js deploy --environment= [--no-localhost] ``` -------------------------------- ### Update All Configuration Values Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/configuration.md Run this command to be prompted for all configuration values, overwriting existing settings. ```bash yarn run check-config --all ``` -------------------------------- ### Build Configuration Questions Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/check-config.md Generates a collection of inquirer questions based on existing configuration. Questions are asked if the --all flag is set or if a configuration value is undefined. ```typescript function configQuestions( filter: ConfigQuestionFilter ): QuestionCollection ``` -------------------------------- ### Manage GA Version with useGAVersion Hook Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/hooks.md Use this hook to get the current GA version (UA or GA4) based on the route and to switch between them. It automatically detects the version from the URL and provides feedback via toast messages. ```typescript import { useGAVersion } from "@/hooks" import { useLocation } from "@reach/router" import { GAVersion } from "@/constants" function VersionSwitcher() { const location = useLocation() const { gaVersion, setGAVersion } = useGAVersion(location.pathname) return ( ) } ``` -------------------------------- ### Deploying Application to Firebase Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/README.md Provides a sequence of bash commands for validating configuration, building the application for production, and deploying it to Firebase. The last command shows a consolidated deployment command. ```bash # Validate configuration yarn run check-config # Build for production yarn run build:app:production # Deploy to Firebase yarn run deploy:app:production # Or as one command yarn run deploy:app:production ``` -------------------------------- ### CLI Commands for GA Dev Tools Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/README.md Commonly used command-line interface commands for managing configuration, development server, building, deployment, and serving the application. ```bash yarn run check-config [--all] ``` ```bash yarn run develop --environment=production ``` ```bash yarn run build:app:production ``` ```bash yarn run deploy:app:production ``` ```bash yarn run serve:app:production [--skip_build] ``` ```bash yarn run deploy:functions:production ``` -------------------------------- ### Deploy to Specific Environment Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/check-config.md Deploy your application to a specific environment (production or staging) using dedicated commands. ```bash yarn run deploy:app:production ``` ```bash yarn run deploy:app:staging ``` -------------------------------- ### Update Configuration with --all flag Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/check-config.md Use this command to re-prompt for all configuration values and overwrite existing settings. This is useful for updating production configurations or when significant changes are needed. ```bash yarn run check-config --all # Prompts for all values again # Overwrites existing configuration ``` -------------------------------- ### CLI Commands Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/COMPLETION_SUMMARY.txt Documentation for available CLI commands, including their prompts and options. ```APIDOC ## CLI Commands ### check-config #### Description Documents the `check-config` CLI command, including all prompts and options. ### build #### Description Documents the `build` CLI command, detailing the process steps involved. ### develop #### Description Documents the `develop` CLI command, providing details on port and host configurations. ### serve #### Description Documents the `serve` CLI command, including an option to skip the build process. ### deploy #### Description Documents the `deploy` CLI command, including a `localhost` option. ### deploy-functions #### Description Documents the `deploy-functions` CLI command, detailing available environment options. ### configForEnvironment() #### Description Documents the `configForEnvironment()` function with an example of its usage. ``` -------------------------------- ### localStorage Key Conventions Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/architecture.md Outlines conventions for naming keys in localStorage to ensure organized and version-compatible storage of user preferences and complex objects. ```text - Nested paths: /ga4/request-composer/basic-report/{field} → nested feature structure - Version suffixes: selected-dimensions-2 → version tracking for backward compatibility - Boolean flags: Direct boolean values in localStorage - Complex objects: JSON-serialized via usePersistantObject ``` -------------------------------- ### Serve Built Content Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/cli-scripts.md Serves built content locally using the Firebase CLI emulator. Use this to test build artifacts before deployment. ```bash node lib/build/index.js serve --environment= [--skip_build] ``` -------------------------------- ### Import Configuration Types Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/configuration.md Import necessary configuration types from the local types definition file. Ensure the path is correct for your project structure. ```typescript import { CommonConfig, RuntimeJson, Environment } from "./types.js" ``` -------------------------------- ### Deployment Pipeline Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/architecture.md Deployment to production is handled by `yarn run deploy:app:production`, which invokes `lib/scripts/stage.ts`. This script first executes a full production build and then deploys the built site to Firebase Hosting using the command `firebase deploy --only hosting`. ```bash yarn run deploy:app:production ↓ lib/scripts/stage.ts (deploy) ↓ 1. build() - Full production build 2. firebase deploy --only hosting ↓ Built site deployed to Firebase Hosting ``` -------------------------------- ### Hooks Import Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/hooks.md Import various utility hooks from the '@/hooks' path. ```APIDOC ## Hooks Import ### Description Import various utility hooks from the '@/hooks' path. ### Import Path ```typescript import { usePersistentBoolean, usePersistentString, usePersistantObject, useSetToast, useGAVersion, useScrollTo, useAddToArray, useRemoveByIndex, useUpdateByIndex, useCopy, usePersistentBoolean, } from "@/hooks" ``` ``` -------------------------------- ### ensureNecessaryFiles Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/check-config.md Ensures the runtime.json file exists and writes the provided configuration to it. If the file is missing, it will be created. The configuration is stringified with a 2-space indent. ```APIDOC ## ensureNecessaryFiles ### Description Ensures `runtime.json` exists and writes configuration to it. ### Signature ```typescript async function ensureNecessaryFiles(runtimeJson: RuntimeJson): Promise ``` ### Behavior 1. Checks if `runtime.json` exists 2. Creates empty file if missing 3. Writes stringified RuntimeJson to file (formatted with 2-space indent) 4. Returns the RuntimeJson unchanged ``` -------------------------------- ### useCopy Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/hooks.md Creates a callback that copies text to the clipboard and optionally displays a toast message upon successful copy. ```APIDOC ## useCopy ### Description Creates a callback that copies text to clipboard and shows toast. ### Signature ```typescript function useCopy(toCopy: string, toast?: string): () => void ``` ### Parameters #### Parameters - **toCopy** (string) - Yes - Text to copy to clipboard - **toast** (string) - No - Toast message to display after copy ### Return Type Function that performs the copy operation when called. ### Example ```typescript import { useCopy } from "@/hooks" function CopyButton({ url }) { const handleCopy = useCopy(url, "URL copied to clipboard!") return } ``` ``` -------------------------------- ### Project Directory Structure Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/architecture.md Illustrates the organization of the ga-dev-tools project, detailing the purpose of each major directory and key files within them. This structure facilitates modularity and maintainability. ```tree ga-dev-tools/ ├── lib/ # Build and deployment scripts │ └── scripts/ │ ├── index.ts # CLI parser and command dispatcher │ ├── types.ts # Type definitions (Config, Args, Environment) │ ├── check-config.ts # Configuration validation and file generation │ ├── build.ts # Build orchestration │ ├── develop.ts # Development server startup │ ├── serve.ts # Firebase serve │ ├── stage.ts # Staging/deployment │ └── deploy-functions.ts # Cloud Functions deployment ├── functions/ # Firebase Cloud Functions │ └── src/ │ └── index.ts # Bitly OAuth endpoints ├── src/ # Main React application │ ├── constants.ts # Urls, GAVersion, StorageKey enums │ ├── hooks/ # React hooks │ │ ├── index.ts # Persistent state hooks │ │ ├── ga4/ # GA4-specific hooks │ │ └── ua/ # UA-specific hooks │ ├── components/ # React components │ │ ├── CampaignURLBuilder/ # Campaign URL builder component │ │ ├── ga4/ # GA4 tool components │ │ │ ├── QueryExplorer/ │ │ │ ├── EventBuilder/ │ │ │ ├── DimensionsMetricsExplorer/ │ │ │ └── StreamPicker/ │ │ └── [other components] │ ├── pages/ # Gatsby page definitions │ ├── types/ # TypeScript type definitions │ ├── styles/ # Global styles │ └── test-utils/ # Test utilities ├── gatsby-config.ts # Gatsby configuration ├── gatsby-browser.tsx # Gatsby browser APIs (Redux, theme) ├── gatsby-ssr.tsx # Gatsby SSR configuration ├── tsconfig.json # TypeScript configuration ├── package.json # Dependencies and scripts └── runtime.json # Configuration (generated, gitignored) ``` -------------------------------- ### Ensure Necessary Files Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/check-config.md Ensures the runtime.json file exists and writes the provided configuration to it. Creates the file if it's missing and formats the JSON with a 2-space indent. ```typescript async function ensureNecessaryFiles(runtimeJson: RuntimeJson): Promise ``` -------------------------------- ### configQuestions Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/check-config.md Generates an inquirer question collection based on missing configuration. Questions are asked if the `askAll` flag is true or if a configuration value is undefined. ```APIDOC ## configQuestions ### Description Generates inquirer question collection based on what configuration is missing. ### Signature ```typescript function configQuestions( filter: ConfigQuestionFilter ): QuestionCollection ``` ### Parameters #### Query Parameters - **filter** (ConfigQuestionFilter) - Required - Existing configuration to filter questions ### Filter Logic Questions are asked if: - `filter.askAll === true` (user specified --all flag), OR - The configuration value is `undefined` (first time setup) If configuration exists and `askAll` is false, prompt is skipped. ### Return Type Array of inquirer questions with validation and conditional rendering. ``` -------------------------------- ### writeEnvFile Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/check-config.md Generates `.env.production` and `.env.development` files from the provided configuration object. It handles the creation and overwriting of these files with environment variables. ```APIDOC ## writeEnvFile ### Description Generates `.env.production` and `.env.development` files from the provided configuration object. It handles the creation and overwriting of these files with environment variables. ### Signature ```typescript async function writeEnvFile( config: CommonConfig, endpointName?: string ): Promise ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **config** (CommonConfig) - Required - Configuration object to write to .env - **endpointName** (string) - Optional - Cloud Function endpoint name (defaults to "bitly_auth") ### Request Example ```typescript import { writeEnvFile } from "./check-config.js" import { configForEnvironment } from "./index.js" const config = await checkConfig({ all: false }) const prodConfig = configForEnvironment(Environment.Production, config) await writeEnvFile(prodConfig, "bitly_auth_production") ``` ### Response #### Success Response (200) - **void** - This function does not return a value. #### Response Example - None ``` -------------------------------- ### ServeArgs Interface Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/types.md Arguments for the serve command. Includes options to skip build and specify the target environment for the 'serve' CLI command. ```typescript interface ServeArgs { cmd: Command.Serve skipBuild: boolean environment: Environment } ``` -------------------------------- ### State Flow from User Action to Local Storage Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/architecture.md Details how user actions trigger state changes that are persisted using custom hooks and local storage. ```text User Action → Hook (usePersistentBoolean/String/Object) → localStorage → Next Session Recovered ``` -------------------------------- ### Handle Build Errors with execa Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/architecture.md This snippet demonstrates how to execute build scripts and capture their output. If the script fails (e.g., TypeScript errors), `execa` will throw an error, stopping the build process. ```typescript // In build.ts await execa("yarn", ["run", "check-types"], { stderr: "inherit", // Show errors to user stdout: "inherit" }) // If check-types fails, execa throws and build stops ``` -------------------------------- ### checkConfig Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/check-config.md Orchestrates the configuration validation and file generation process. It loads existing configuration, prompts the user for necessary details, validates the input, and generates runtime and environment files. ```APIDOC ## checkConfig ### Description Orchestrates the configuration validation and file generation process. It loads existing configuration, prompts the user for necessary details, validates the input, and generates runtime and environment files. ### Signature ```typescript async function checkConfig(args: CheckConfigArgs): Promise ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **args** (CheckConfigArgs) - Required - Command arguments with `all` flag ### Request Example ```typescript import { checkConfig } from "./check-config.js" const config = await checkConfig({ cmd: Command.CheckConfig, all: false }) console.log(config.production.firebaseProjectId) ``` ### Response #### Success Response (200) - **RuntimeJson** - The complete runtime configuration object #### Response Example ```json { "production": { "firebaseProjectId": "your-project-id" } } ``` ``` -------------------------------- ### Deploy Functions Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/cli-scripts.md Deploys Firebase Cloud Functions to the specified environment. Use this to update backend logic. ```bash node lib/build/index.js deploy-functions --environment= [--no-localhost] ``` -------------------------------- ### Campaign URL Builder Component Structure Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/architecture.md Illustrates the specific directory structure for a feature-specific component, such as the Campaign URL Builder. ```text CampaignURLBuilder/ ├── index.tsx # Main component ├── adNetworks.ts # Ad network configurations ├── Web/ # Web campaign builder │ ├── index.tsx │ ├── useInputs.ts # Form state management │ ├── useGenerateURL.ts # URL generation logic │ ├── GeneratedURL/ # Output display │ └── params.ts # Parameter validation └── Play/ # Google Play campaign builder ├── index.tsx └── useGenerateURL.ts ``` -------------------------------- ### React Hooks Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/COMPLETION_SUMMARY.txt Documentation for custom React Hooks, detailing their behavior and integration. ```APIDOC ## React Hooks ### usePersistentBoolean #### Description Provides full documentation for the `usePersistentBoolean` hook, including its behavior with `localStorage`. ### usePersistentString #### Description Provides full documentation for the `usePersistentString` hook, including its handling of `undefined` values. ### usePersistantObject #### Description Documents the `usePersistantObject` hook, including its generic type parameters. ### useGAVersion #### Description Documents the `useGAVersion` hook, covering navigation and redirection functionalities. ### useSetToast #### Description Explains the integration of the `useSetToast` hook with Redux. ### useScrollTo #### Description Documents the `useScrollTo` hook, detailing its behavior with URL hashes. ### useAddToArray #### Description Documents the `useAddToArray` hook, explaining its array manipulation capabilities. ### useRemoveByIndex #### Description Documents the `useRemoveByIndex` hook, focusing on its array filtering functionality. ### useUpdateByIndex #### Description Documents the `useUpdateByIndex` hook, detailing its array transformation capabilities. ### useCopy #### Description Documents the `useCopy` hook, explaining its integration with the clipboard and toast notifications. ``` -------------------------------- ### Importing React Hooks Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/hooks.md Import various hooks and utility functions from the '@/hooks' module. Ensure all necessary hooks are imported before use. ```typescript import { usePersistentBoolean, usePersistentString, usePersistantObject, useSetToast, useGAVersion, useScrollTo, useAddToArray, useRemoveByIndex, useUpdateByIndex, useCopy, usePersistentBoolean, } from "@/hooks" ``` -------------------------------- ### Tool Versioning with useGAVersion Hook Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/architecture.md Detect and handle different tool versions (e.g., GA4 vs. UA) based on URL path using the `useGAVersion` hook. This allows rendering appropriate UI components for each version. ```tsx function DimensionsExplorer() { const { gaVersion } = useGAVersion(pathname) if (gaVersion === GAVersion.GoogleAnalytics4) { return } else { return } } ``` -------------------------------- ### Update Missing Configuration Values Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/configuration.md Use this command to prompt only for configuration values that are currently missing. This is useful after selectively updating the runtime.json file. ```bash yarn run check-config ``` -------------------------------- ### Runtime Configuration Schema Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/configuration.md Defines the structure for runtime configuration, specifying required fields for both production and staging environments. ```typescript { "production": { "firebaseProjectId": string, "gapiClientId": string, "bitlyClientId": string, "bitlyClientSecret": string, "baseUri": string, "measurementId": string }, "staging": { "firebaseProjectId": string, "gapiClientId": string, "bitlyClientId": string, "bitlyClientSecret": string, "baseUri": string, "measurementId": string } } ``` -------------------------------- ### DeployArgs Interface Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/types.md Arguments for the deploy command. Allows specifying the environment and excluding localhost from OAuth allowed origins for the 'deploy' CLI command. ```typescript interface DeployArgs { cmd: Command.Deploy environment: Environment noLocalhost: boolean } ``` -------------------------------- ### Import Constants Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/constants.md Import necessary constants like URLs, GA versions, and storage keys from the constants module. ```typescript import { Url, GAVersion, StorageKey } from "@/constants" ``` -------------------------------- ### SKIP_QUESTION Constant Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/check-config.md Sentinel value used as default for optional configuration prompts. When user accepts this default, the configuration value is skipped and corresponding environment variables are omitted. Allows users to skip optional integrations (Google OAuth, Bitly). ```typescript const SKIP_QUESTION = "Leave blank to skip" ``` -------------------------------- ### Write Environment Files with writeEnvFile Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/check-config.md Generates .env.production and .env.development files from a configuration object. This function is useful for creating environment-specific variable files needed for deployment. ```typescript import { writeEnvFile } from "./check-config.js" import { configForEnvironment } from "./index.js" const config = await checkConfig({ all: false }) const prodConfig = configForEnvironment(Environment.Production, config) await writeEnvFile(prodConfig, "bitly_auth_production") ``` -------------------------------- ### Halt Process on Configuration Error Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/architecture.md Use this pattern to stop the process immediately when a critical configuration value is missing. Ensures that the application does not proceed with invalid settings. ```typescript // In check-config.ts if (!firebaseProjectId) { console.error("Firebase project ID required") process.exit(1) // Halt process } ``` -------------------------------- ### useGAVersion Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/hooks.md Retrieves and manages the current GA version (Universal Analytics vs GA4) based on the route. It automatically detects the version from the URL and provides a function to switch between versions, offering user feedback via toast notifications. ```APIDOC ## useGAVersion ### Description Retrieves and manages the current GA version (Universal Analytics vs GA4) based on route. Automatically detects version from URL path (/ga4/ = GA4, else = UA). Provides a function to switch versions, handling navigation and displaying toast messages for user feedback. If a version switch is invalid, the action is ignored. ### Signature ```typescript function useGAVersion( pathname: string ): { gaVersion: GAVersion setGAVersion: (version: GAVersion) => void } ``` ### Parameters #### Path Parameters - **pathname** (string) - Yes - Current pathname from useLocation().pathname ### Return Type Object with: - `gaVersion: GAVersion` - Current version (UniversalAnalytics or GoogleAnalytics4) - `setGAVersion: (version: GAVersion) => void` - Function to switch versions ### Example ```typescript import { useGAVersion } from "@/hooks" import { useLocation } from "@reach/router" import { GAVersion } from "@/constants" function VersionSwitcher() { const location = useLocation() const { gaVersion, setGAVersion } = useGAVersion(location.pathname) return ( ) } ``` ``` -------------------------------- ### DevelopArgs Interface Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/types.md Arguments for the develop command. Specify the environment for the 'develop' CLI command. ```typescript interface DevelopArgs { cmd: Command.Develop environment: Environment } ``` -------------------------------- ### Using Persistent State with usePersistentString Hook Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/README.md Demonstrates how to use the `usePersistentString` hook to manage state that is persisted in localStorage. It reads from localStorage on initial load and updates it on input change. ```typescript import { usePersistentString } from "@/hooks" import { StorageKey } from "@/constants" export function MyTool() { const [selectedProperty, setSelectedProperty] = usePersistentString( StorageKey.ga4RequestComposerBasicSelectedPropertyString ) return ( setSelectedProperty(e.target.value)} placeholder="Select property" /> ) } // On first load: reads from localStorage[StorageKey.ga4RequestComposerBasicSelectedPropertyString] // On input change: updates localStorage and component state // On page reload: restored from localStorage ``` -------------------------------- ### Switch Firebase Projects Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/api-reference/check-config.md To deploy to a different Firebase project, run 'yarn run check-config --all' and provide the new firebaseProjectId when prompted. Ensure you run the deploy command afterward. ```bash yarn run check-config --all # Provide new firebaseProjectId # Run deploy command ``` -------------------------------- ### DeployFunctionsArgs Interface Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/types.md Arguments for the deploy-functions command. Similar to DeployArgs, this defines parameters for deploying functions, including environment and localhost exclusion. ```typescript interface DeployFunctionsArgs { cmd: Command.DeployFunctions environment: Environment noLocalhost: boolean } ``` -------------------------------- ### Firebase Configuration for Hosting and Functions Source: https://github.com/googleanalytics/ga-dev-tools/blob/main/_autodocs/architecture.md This JSON configuration sets up Firebase Hosting to serve static files from the 'public' directory and route all requests to 'index.html' for single-page application functionality. It also specifies the source directory and Node.js runtime for Firebase Functions. ```json { "hosting": { "public": "public", "rewrites": [{ "source": "**", "destination": "/index.html" }] }, "functions": { "source": "functions", "runtime": "nodejs12" } } ```