### Basic Setup Example Source: https://generaltranslation.com/en-US/docs/node/reference/functions/initialize-gt Standard initialization example for a server entry file. ```ts // Basic setup import { initializeGT } from 'gt-node'; initializeGT({ defaultLocale: 'en', locales: ['en', 'es', 'fr', 'ja'], }); ``` -------------------------------- ### Run setup wizard examples Source: https://generaltranslation.com/en-US/docs/cli/reference/commands/init Demonstrates the primary command and its shorthand equivalent. ```bash # Run the full setup wizard npx gt init # Running gt with no command does the same thing npx gt ``` -------------------------------- ### Initialize Project Setup Source: https://generaltranslation.com/en-US/docs/platform/core/reference/gt-class-methods/translation/setup-project Example demonstrating how to call setupProject with file references and handle the resulting status. ```typescript import { GT } from 'generaltranslation'; const gt = new GT({ projectId: 'your-project-id', apiKey: 'your-api-key', }); // File references from a previous upload const fileRefs = [ { fileId: 'file-123', versionId: 'version-456', branchId: 'branch-789', fileName: 'app.json', fileFormat: 'JSON', }, { fileId: 'file-789', versionId: 'version-012', branchId: 'branch-789', fileName: 'content.md', fileFormat: 'MD', }, ]; const setupResult = await gt.setupProject(fileRefs); if (setupResult.status === 'queued') { console.log(`Setup initiated with job ID: ${setupResult.setupJobId}`); // Monitor job status (checkJobStatus returns a flat array) const jobStatus = await gt.checkJobStatus([setupResult.setupJobId]); console.log(`Job status: ${jobStatus[0].status}`); } else { console.log('Project is already set up — no setup job needed'); } ``` -------------------------------- ### Initialize the CLI Source: https://generaltranslation.com/en-US/docs/cli/guides/configuring Run the setup wizard to detect the framework, install dependencies, and create the configuration file. ```bash npx gt init ``` -------------------------------- ### Run gt setup Source: https://generaltranslation.com/en-US/docs/cli/reference/commands/setup Executes the setup command to upload and register source files. ```bash npx gt setup ``` -------------------------------- ### Polling job status example Source: https://generaltranslation.com/en-US/docs/platform/core/reference/gt-class-methods/translation/check-job-status A complete example showing how to initiate a project setup and poll the resulting job status. ```typescript import { GT } from 'generaltranslation'; const gt = new GT({ projectId: 'your-project-id', apiKey: 'your-api-key', }); const fileRefs = [ { fileId: 'file-123', versionId: 'version-456', branchId: 'branch-789', fileName: 'app.json', fileFormat: 'JSON', }, { fileId: 'file-789', versionId: 'version-012', branchId: 'branch-789', fileName: 'content.md', fileFormat: 'MD', }, ]; const setupResult = await gt.setupProject(fileRefs); async function pollJobStatus(jobIds: string[]) { const status = await gt.checkJobStatus(jobIds); status.forEach((job) => { console.log(`Job ${job.jobId}:`); console.log(` Status: ${job.status}`); if (job.error) { console.log(` Error: ${job.error.message}`); } }); return status; } if (setupResult.status === 'queued') { const jobStatus = await pollJobStatus([setupResult.setupJobId]); } ``` -------------------------------- ### Start Development Server Source: https://generaltranslation.com/en-US/docs/react/nextjs-quickstart Commands to start the development server using various package managers. ```bash npm run dev ``` ```bash yarn dev ``` ```bash bun dev ``` ```bash pnpm dev ``` -------------------------------- ### Example usage Source: https://generaltranslation.com/en-US/docs/python/reference/functions/get-locales A standard implementation example using the Flask integration. ```python from gt_flask import get_locales locales = get_locales() # e.g. ["en", "es", "fr"] ``` -------------------------------- ### Install Integration Packages Source: https://generaltranslation.com/en-US/docs/python/quickstart Install the required package for your specific web framework. ```bash pip install gt-flask ``` ```bash pip install gt-fastapi ``` -------------------------------- ### Install gt-tanstack-start dependencies Source: https://generaltranslation.com/en-US/docs/react/tanstack-start-quickstart Install the required packages and the CLI tool using your preferred package manager. ```bash npm install gt-tanstack-start gt-react && npm install gt --save-dev ``` ```bash yarn add gt-tanstack-start gt-react && yarn add --dev gt ``` ```bash bun add gt-tanstack-start gt-react && bun add --dev gt ``` ```bash pnpm add gt-tanstack-start gt-react && pnpm add --save-dev gt ``` -------------------------------- ### Install gt-i18n library Source: https://generaltranslation.com/en-US/docs/python/quickstart Install the core library using pip. ```bash pip install gt-i18n ``` -------------------------------- ### Initialize Project Setup Source: https://generaltranslation.com/en-US/docs/platform/core/reference/gt-class-methods/translation/setup-project Demonstrates how to call setupProject with file references and optional configuration. ```typescript const gt = new GT({ projectId: 'your-project-id', apiKey: 'your-api-key' }); const setupResult = await gt.setupProject(fileRefs, { timeoutMs: 30000 }); if (setupResult.status === 'queued') { console.log(`Setup job created: ${setupResult.setupJobId}`); } else { console.log('Project is already set up'); } ``` -------------------------------- ### Install the compiler Source: https://generaltranslation.com/en-US/docs/cli/guides/using-auto-jsx Install the @generaltranslation/compiler package using your preferred package manager. ```bash npm install @generaltranslation/compiler ``` ```bash yarn add @generaltranslation/compiler ``` ```bash bun add @generaltranslation/compiler ``` ```bash pnpm add @generaltranslation/compiler ``` -------------------------------- ### Full Middleware Configuration Example Source: https://generaltranslation.com/en-US/docs/react/nextjs/reference/functions/create-next-middleware A complete example demonstrating the use of prefixDefaultLocale and pathConfig within the middleware export. ```typescript import { createNextMiddleware } from 'gt-next/middleware'; export default createNextMiddleware({ prefixDefaultLocale: true, pathConfig: { '/about': { fr: '/a-propos', }, }, }); export const config = { matcher: ['/((?!api|static|.*\..*|_next).*)'], }; ``` -------------------------------- ### Install generaltranslation package Source: https://generaltranslation.com/en-US/docs/platform/core/quickstart Install the library using your preferred package manager. ```bash npm install generaltranslation ``` ```bash yarn add generaltranslation ``` ```bash bun add generaltranslation ``` ```bash pnpm add generaltranslation ``` -------------------------------- ### Run Application Source: https://generaltranslation.com/en-US/docs/python/quickstart Commands to start the web server for Flask or FastAPI. ```bash flask --app app run ``` ```bash pip install "uvicorn[standard]" uvicorn main:app ``` -------------------------------- ### Initialize GT with Flask Source: https://generaltranslation.com/en-US/docs/python/reference/functions/initialize-gt Performs a minimal setup by reading from gt.config.json. ```python # Minimal setup, reading gt.config.json from flask import Flask from gt_flask import initialize_gt app = Flask(__name__) initialize_gt(app) ``` -------------------------------- ### Advanced list formatting examples Source: https://generaltranslation.com/en-US/docs/platform/core/reference/gt-class-methods/formatting/format-list Examples showing how to use different list types and locale overrides. ```typescript import { GT } from 'generaltranslation'; const gt = new GT({ targetLocale: 'en' }); // Conjunction (default) — "and" list console.log(gt.formatList(['A', 'B', 'C'])); // Output: "A, B, and C" // Disjunction — "or" list console.log(gt.formatList(['A', 'B', 'C'], { type: 'disjunction' })); // Output: "A, B, or C" // Spanish disjunction console.log(gt.formatList(['red', 'green', 'blue'], { locales: ['es'], type: 'disjunction', })); // Output: "red, green o blue" ``` -------------------------------- ### Run and verify the server Source: https://generaltranslation.com/en-US/docs/node/quickstart Start the server and verify the integration by sending a request to the endpoint. ```bash node server.js ``` ```bash curl http://localhost:3000/api/greeting ``` ```json {"message":"Hello, Alice!"} ``` -------------------------------- ### Install gt-next and gt CLI Source: https://generaltranslation.com/en-US/docs/react/nextjs-quickstart Install the required translation library and CLI tool using your preferred package manager. ```bash npm i gt-next npm i -D gt ``` ```bash yarn add gt-next yarn add --dev gt ``` ```bash bun add gt-next bun add --dev gt ``` ```bash pnpm add gt-next pnpm add --save-dev gt ``` -------------------------------- ### Authentication command examples Source: https://generaltranslation.com/en-US/docs/cli/reference/commands/auth Demonstrates interactive and non-interactive usage for generating API keys. ```bash # Prompt for the key type, then write credentials to .env.local npx gt auth # Generate a production key without the prompt npx gt auth --key-type production ``` -------------------------------- ### Install General Translation packages Source: https://generaltranslation.com/en-US/docs/react/react-quickstart Install the core library and the CLI tool using your preferred package manager. ```bash npm i gt-react npm i -D gt ``` ```bash yarn add gt-react yarn add --dev gt ``` ```bash bun add gt-react bun add --dev gt ``` ```bash pnpm add gt-react pnpm add --save-dev gt ``` -------------------------------- ### gt setup Source: https://generaltranslation.com/en-US/docs/cli/reference/commands/setup Uploads source files and registers a project for translation. ```APIDOC ## CLI Command: gt setup ### Description Uploads your source files and registers the project with the General Translation platform. This command performs the file collection and upload steps without enqueuing translations or downloading results. ### Usage `npx gt setup [options]` ### Parameters - **--api-key** (string) - Optional - Production API key. Defaults to GT_API_KEY environment variable. - **--project-id** (string) - Optional - Project ID. Defaults to GT_PROJECT_ID environment variable. - **-c, --config** (string) - Optional - Path to the config file. Defaults to gt.config.json. - **--dry-run** (boolean) - Optional - Collect files and report them without uploading. ### Example ```bash # Upload and register source files with the platform npx gt setup # Report the files that would be uploaded without uploading them npx gt setup --dry-run ``` ``` -------------------------------- ### Install the gt CLI Source: https://generaltranslation.com/en-US/docs/cli/quickstart Install the CLI as a development dependency using your preferred package manager. ```bash npm install gt --save-dev ``` ```bash yarn add --dev gt ``` ```bash bun add --dev gt ``` ```bash pnpm add --save-dev gt ``` -------------------------------- ### Run gt setup with flags Source: https://generaltranslation.com/en-US/docs/cli/reference/commands/setup Demonstrates standard usage and a dry-run execution to preview file collection. ```bash # Upload and register source files with the platform npx gt setup # Report the files that would be uploaded without uploading them npx gt setup --dry-run ``` -------------------------------- ### gt.setupProject(fileRefs) Source: https://generaltranslation.com/en-US/docs/platform/core/reference/gt-class-methods/translation/setup-project Initializes the project setup using a list of file references. Returns a promise that resolves to a SetupProjectResult object. ```APIDOC ## gt.setupProject(fileRefs) ### Description Initializes the project setup by providing an array of file references. This method returns a union type indicating if a background job was queued or if the project setup is already complete. ### Parameters - **fileRefs** (Array) - Required - An array of file reference objects containing fileId, versionId, branchId, fileName, and fileFormat. ### Returns - **Promise** - A promise that resolves to an object with a status of 'queued' (with a setupJobId) or 'completed'. ### Example ```typescript const setupResult = await gt.setupProject(fileRefs); if (setupResult.status === 'queued') { console.log(`Setup initiated with job ID: ${setupResult.setupJobId}`); } else { console.log('Project is already set up'); } ``` ``` -------------------------------- ### setupProject(files, options) Source: https://generaltranslation.com/en-US/docs/platform/core/reference/gt-class-methods/translation/setup-project Initializes the setup process for a translation project using file references obtained from uploadSourceFiles. ```APIDOC ## setupProject ### Description Initializes the setup process for a translation Project using previously uploaded files. It creates an asynchronous setup job that analyzes the files and prepares them for translation workflows. ### Signature `setupProject(files: FileReference[], options?: SetupProjectOptions): Promise` ### Parameters - **files** (FileReference[]) - Required - An array of file references obtained from the uploadSourceFiles method. - **options** (SetupProjectOptions) - Optional - Configuration options for the setup process, such as timeoutMs. ### Returns - **Promise** - A promise that resolves to an object containing the status of the setup (e.g., 'queued') and a setupJobId if applicable. ``` -------------------------------- ### Full translation workflow example Source: https://generaltranslation.com/en-US/docs/platform/core/reference/gt-class-methods/translation/download-file A complete workflow example showing file upload, job enqueuing, waiting for completion, and finally downloading the translated content. ```typescript // (1) Create a GT instance const targetLocales = ['es', 'fr', 'de']; const gt = new GT({ projectId: 'your-project-id', apiKey: 'your-api-key', }); // (2) Upload the file const fileUpload = { content: fileContents, fileName: filePath, fileFormat: 'JSON', locale: 'en', }; const files = [{ source: fileUpload }]; const { uploadedFiles } = await gt.uploadSourceFiles(files, { sourceLocale: 'en' }); // (3) Enqueue the file translation job const enqueueResult = await gt.enqueueFiles(uploadedFiles, { sourceLocale: 'en', targetLocales: targetLocales, }); // (4) Wait for all translations to be completed const { fileId, versionId, branchId } = uploadedFiles[0]; const result = await gt.awaitJobs(enqueueResult); if (!result.complete) { console.error('Some jobs did not finish in time'); } // (5) Download a single file const spanishContent = await gt.downloadFile({ fileId, branchId, locale: 'es', }); console.log('Spanish translation:', spanishContent); ``` -------------------------------- ### npx gt init Source: https://generaltranslation.com/en-US/docs/cli/reference/commands/init Initializes the General Translation setup wizard to configure a project. ```APIDOC ## CLI Command: npx gt init ### Description Runs the General Translation setup wizard to detect the project framework, configure settings, and generate necessary credentials. ### Usage `npx gt init [options]` ### Parameters #### Options - **--src** (string[]) - Optional - Glob patterns for the app's source code. Defaults to `src`, `app`, `pages`, `components`. - **-c, --config** (string) - Optional - Path to the configuration file. Defaults to `gt.config.json`. ``` -------------------------------- ### Manual configuration file setup Source: https://generaltranslation.com/en-US/docs/cli/guides/configuring Create the configuration file manually with a schema reference for editor validation. ```json { "$schema": "https://assets.gtx.dev/config-schema.json", "defaultLocale": "en", "locales": ["fr", "es"] } ``` -------------------------------- ### Configure and generate templates Source: https://generaltranslation.com/en-US/docs/cli/reference/commands/generate Initial setup and generation of translation templates for a project. ```bash npx gt configure npx gt generate ``` -------------------------------- ### Full translation workflow example Source: https://generaltranslation.com/en-US/docs/cli/reference/commands/download Demonstrates the sequence of commands from uploading source files to downloading the final translations. ```bash # Stage 1: upload source files npx gt upload # Stage 2: enqueue translations npx gt enqueue # Stage 3: download the completed translations (this command) npx gt download ``` -------------------------------- ### Full Project Information Retrieval Example Source: https://generaltranslation.com/en-US/docs/platform/core/reference/gt-class-methods/translation/get-project-data A complete example demonstrating error handling and data retrieval for a specific project. ```typescript import { GT } from 'generaltranslation'; const gt = new GT({ projectId: 'your-project-id', apiKey: 'your-api-key', }); async function getProjectInfo(projectId: string) { try { const project = await gt.getProjectData(projectId); console.log('=== Project Information ==='); console.log(`ID: ${project.id}`); console.log(`Name: ${project.name}`); console.log(`Organization: ${project.orgId}`); console.log(`Default Locale: ${project.defaultLocale}`); console.log(`Target Locales: ${project.currentLocales.join(', ')}`); return project; } catch (error) { console.error(`Failed to retrieve project ${projectId}:`, error); throw error; } } const projectInfo = await getProjectInfo('my-project-123'); ``` -------------------------------- ### Install gt-sanity plugin Source: https://generaltranslation.com/en-US/docs/integrations/sanity/quickstart Commands to install the plugin using various package managers. ```bash npm install gt-sanity ``` ```bash yarn add gt-sanity ``` ```bash bun add gt-sanity ``` ```bash pnpm add gt-sanity ``` -------------------------------- ### Initialize GT instance Source: https://generaltranslation.com/en-US/docs/platform/core/reference/types/gt-constructor-params Examples showing manual configuration versus environment variable usage. ```typescript // Basic setup const gt = new GT({ apiKey: 'your-api-key', sourceLocale: 'en', targetLocale: 'es', locales: ['en', 'es', 'fr'] }); ``` ```typescript // With environment variables const gt = new GT({ sourceLocale: 'en', targetLocale: 'es' }); // Uses GT_API_KEY and GT_PROJECT_ID from the environment ``` -------------------------------- ### Basic usage example Source: https://generaltranslation.com/en-US/docs/python/reference/functions/get-version-id Demonstrates calling the function to retrieve the version ID string or None. ```python from gt_i18n import get_version_id get_version_id() # e.g., "v_abc123" or None ``` -------------------------------- ### Usage Example Source: https://generaltranslation.com/en-US/docs/python/reference/functions/set-i18n-manager Register a manager and perform a translation using the configured locale. ```python from gt_i18n import I18nManager, set_i18n_manager, t manager = I18nManager(default_locale="en", locales=["es"]) set_i18n_manager(manager) manager.set_locale("es") t("Hello, world!") ``` -------------------------------- ### Install gt-node dependencies Source: https://generaltranslation.com/en-US/docs/node/quickstart Install the required runtime and development dependencies using your preferred package manager. ```bash npm install gt-node express && npm install gt --save-dev ``` ```bash yarn add gt-node express && yarn add --dev gt ``` ```bash bun add gt-node express && bun add --dev gt ``` ```bash pnpm add gt-node express && pnpm add --save-dev gt ``` -------------------------------- ### Advanced usage and validation examples Source: https://generaltranslation.com/en-US/docs/platform/core/reference/utility-functions/locales/standardize-locale Examples showing how to handle non-canonicalizable inputs and integrate with validation logic. ```typescript import { standardizeLocale } from 'generaltranslation'; // Normalizes casing on hyphenated tags console.log(standardizeLocale('EN-gb')); // 'en-GB' console.log(standardizeLocale('fr-ca')); // 'fr-CA' console.log(standardizeLocale('en-us')); // 'en-US' // Already standardized locales pass through console.log(standardizeLocale('es-ES')); // 'es-ES' // Non-canonicalizable input is returned unchanged console.log(standardizeLocale('en_us')); // 'en_us' (underscore is not valid BCP-47) console.log(standardizeLocale('not a locale')); // 'not a locale' ``` ```typescript import { standardizeLocale, isValidLocale } from 'generaltranslation'; // Normalizing user input function processUserInput(input: string) { const standardized = standardizeLocale(input.trim()); const isValid = isValidLocale(standardized); return { original: input, standardized, isValid, }; } // Test various inputs const inputs = ['EN-gb', 'FR-ca', 'invalid', 'zh-CN']; inputs.forEach((input) => { console.log(processUserInput(input)); }); ``` -------------------------------- ### Install gt-react-native dependencies Source: https://generaltranslation.com/en-US/docs/react/react-native-quickstart Install the required package and CLI tool using your preferred package manager. ```bash npm install gt-react-native && npm install gt --save-dev ``` ```bash yarn add gt-react-native && yarn add --dev gt ``` ```bash bun add gt-react-native && bun add --dev gt ``` ```bash pnpm add gt-react-native && pnpm add --save-dev gt ``` -------------------------------- ### Install FormatJS polyfills via package manager Source: https://generaltranslation.com/en-US/docs/react/react-native/plugin Install the required FormatJS polyfill packages using your preferred package manager. ```bash npm install @formatjs/intl-getcanonicallocales @formatjs/intl-locale @formatjs/intl-displaynames @formatjs/intl-listformat @formatjs/intl-pluralrules @formatjs/intl-numberformat @formatjs/intl-relativetimeformat @formatjs/intl-datetimeformat ``` ```bash yarn add @formatjs/intl-getcanonicallocales @formatjs/intl-locale @formatjs/intl-displaynames @formatjs/intl-listformat @formatjs/intl-pluralrules @formatjs/intl-numberformat @formatjs/intl-relativetimeformat @formatjs/intl-datetimeformat ``` ```bash bun add @formatjs/intl-getcanonicallocales @formatjs/intl-locale @formatjs/intl-displaynames @formatjs/intl-listformat @formatjs/intl-pluralrules @formatjs/intl-numberformat @formatjs/intl-relativetimeformat @formatjs/intl-datetimeformat ``` ```bash pnpm add @formatjs/intl-getcanonicallocales @formatjs/intl-locale @formatjs/intl-displaynames @formatjs/intl-listformat @formatjs/intl-pluralrules @formatjs/intl-numberformat @formatjs/intl-relativetimeformat @formatjs/intl-datetimeformat ``` -------------------------------- ### Example usage of t_fallback Source: https://generaltranslation.com/en-US/docs/python/reference/functions/t-fallback Demonstrates the interpolation of a welcome message. ```python from gt_i18n import t_fallback t_fallback("Welcome, {name}!", name="Alice") # → "Welcome, Alice!" ``` -------------------------------- ### Create JsxElement examples Source: https://generaltranslation.com/en-US/docs/platform/core/reference/types/jsx-children Demonstrates creating JsxChildren using div and link elements. ```typescript // Div element const divElement: JsxChildren = { t: 'div', c: ['Content here'] }; // Link with title const linkElement: JsxChildren = { t: 'a', d: { ti: 'Visit homepage' }, c: ['Click here'] }; ``` -------------------------------- ### Create a dictionary-based StorageAdapter Source: https://generaltranslation.com/en-US/docs/python/reference/classes/storage-adapter Example implementation of a StorageAdapter using a dictionary for state management, passed to the I18nManager. ```python from gt_i18n import StorageAdapter, I18nManager class DictStorageAdapter(StorageAdapter): def __init__(self) -> None: self._data: dict[str, str] = {} def get_item(self, key: str) -> str | None: return self._data.get(key) def set_item(self, key: str, value: str) -> None: self._data[key] = value manager = I18nManager(default_locale="en", store_adapter=DictStorageAdapter()) ``` -------------------------------- ### Create configuration file Source: https://generaltranslation.com/en-US/docs/cli/guides/configuring Generate the gt.config.json file without installing dependencies or modifying framework settings. ```bash npx gt configure ``` -------------------------------- ### Create JsxChildren examples Source: https://generaltranslation.com/en-US/docs/platform/core/reference/types/jsx-children Demonstrates creating JsxChildren using simple text and text with variables. ```typescript import { JsxChildren, Variable } from 'generaltranslation/types'; // Simple text const text: JsxChildren = "Welcome!"; // Text with variables const greeting: JsxChildren = [ "Hello, ", { k: 'userName' } as Variable, "!" ]; ``` -------------------------------- ### Use EnqueueFilesOptions in Translation Source: https://generaltranslation.com/en-US/docs/platform/core/reference/types/enqueue-files-options Example of configuring options and passing them to the enqueueFiles method. ```typescript import { GT, EnqueueFilesOptions } from 'generaltranslation'; const options: EnqueueFilesOptions = { targetLocales: ['es', 'fr', 'de'], sourceLocale: 'en', modelProvider: 'premium', }; const result = await gt.enqueueFiles(files, options); ``` -------------------------------- ### Register gtMiddleware in TanStack Start Source: https://generaltranslation.com/en-US/docs/react/tanstack-start/reference/functions/gt-middleware Import gtMiddleware from gt-tanstack-start and include it in the requestMiddleware array within the createStart configuration. ```ts import { createCsrfMiddleware, createStart } from '@tanstack/react-start'; import { gtMiddleware } from 'gt-tanstack-start'; const csrfMiddleware = createCsrfMiddleware({ filter: ({ handlerType }) => handlerType === 'serverFn', }); export const startInstance = createStart(() => ({ requestMiddleware: [csrfMiddleware, gtMiddleware], })); ``` -------------------------------- ### Initialize Variable Objects Source: https://generaltranslation.com/en-US/docs/platform/core/reference/types/variable Examples of creating Variable objects for different data types. ```typescript import { Variable } from 'generaltranslation/types'; // Text variable const nameVariable: Variable = { k: 'userName' }; // Number variable const countVariable: Variable = { k: 'itemCount', v: 'n' }; // Currency variable const priceVariable: Variable = { k: 'price', v: 'c' }; ``` -------------------------------- ### Initialize GTProvider in TanStack Start Source: https://generaltranslation.com/en-US/docs/react/reference/components/gt-provider Pass the active locale and translation snapshot after registering the middleware. ```tsx import { GTProvider } from 'gt-tanstack-start'; ``` -------------------------------- ### Configure Render Settings in next.config.ts Source: https://generaltranslation.com/en-US/docs/react/nextjs/config Example of configuring the render method and timeout for runtime translations. ```ts export default withGTConfig(nextConfig, { renderSettings: { method: 'skeleton', timeout: 10000, }, }); ``` -------------------------------- ### Install the General Translation ESLint plugin Source: https://generaltranslation.com/en-US/docs/react/guides/linting-your-code Add the linter as a development dependency using your preferred package manager. ```bash npm install --save-dev @generaltranslation/react-core-linter ``` ```bash yarn add --dev @generaltranslation/react-core-linter ``` ```bash bun add --dev @generaltranslation/react-core-linter ``` ```bash pnpm add --save-dev @generaltranslation/react-core-linter ``` -------------------------------- ### Using getTranslations in a Server Function Source: https://generaltranslation.com/en-US/docs/react/tanstack-start/reference/functions/get-translations Example of using getTranslations within a TanStack Start server function. ```ts import { createServerFn } from '@tanstack/react-start'; import { getTranslations } from 'gt-tanstack-start'; export const loadHeading = createServerFn({ method: 'GET' }).handler( async () => { const t = await getTranslations('account'); return t('heading'); } ); ``` -------------------------------- ### Advanced list formatting examples Source: https://generaltranslation.com/en-US/docs/platform/core/reference/utility-functions/formatting/format-list Demonstrates conjunction and disjunction formatting across different locales. ```typescript import { formatList } from 'generaltranslation'; // Conjunction (default) console.log(formatList(['A', 'B', 'C'], { locales: 'en' })); // Output: "A, B, and C" // Disjunction console.log(formatList(['A', 'B', 'C'], { locales: 'en', type: 'disjunction' })); // Output: "A, B, or C" // Spanish disjunction console.log(formatList(['red', 'green', 'blue'], { locales: 'es', type: 'disjunction', })); // Output: "red, green o blue" ``` -------------------------------- ### Generate templates with flags Source: https://generaltranslation.com/en-US/docs/cli/reference/commands/generate Examples of generating templates using specific locale settings and error handling configurations. ```bash # Generate templates for the configured locales npx gt generate # Generate from a custom source locale, ignoring scan errors npx gt generate --default-locale en-US --ignore-errors ``` -------------------------------- ### Using getGT in a Server Function Source: https://generaltranslation.com/en-US/docs/react/tanstack-start/reference/functions/get-gt Example of using getGT within a TanStack Start server function. ```ts import { createServerFn } from '@tanstack/react-start'; import { getGT } from 'gt-tanstack-start'; export const loadTitle = createServerFn({ method: 'GET' }).handler(async () => { const gt = await getGT(); return gt('Account settings'); }); ``` -------------------------------- ### Example Source JSON File Source: https://generaltranslation.com/en-US/docs/platform/core/guides/translating-files A sample JSON file structure used as the source for translation. ```json { "hello": "Hello", "world": "World" } ``` -------------------------------- ### Using getEnableI18n in a Server Function Source: https://generaltranslation.com/en-US/docs/react/tanstack-start/reference/functions/get-enable-i18n Example of accessing the i18n state within a TanStack Start server function. ```ts import { createServerFn } from '@tanstack/react-start'; import { getEnableI18n } from 'gt-tanstack-start'; export const loadI18nState = createServerFn({ method: 'GET' }).handler(() => { return { enableI18n: getEnableI18n() }; }); ``` -------------------------------- ### Create JsxElement instances Source: https://generaltranslation.com/en-US/docs/platform/core/reference/types/jsx-element Examples of defining simple elements and elements with attributes using JsxElement. ```typescript import { JsxElement, Variable } from 'generaltranslation/types'; // Simple element const heading: JsxElement = { t: 'h1', c: ['Welcome'] }; // With attributes const button: JsxElement = { t: 'button', d: { ti: 'Submit form' }, c: ['Submit'] }; ``` -------------------------------- ### Advanced examples of extract_variables Source: https://generaltranslation.com/en-US/docs/python/reference/functions/extract-variables Shows how the function handles reserved keys and preserves user keys starting with a single underscore. ```python from gt_i18n import extract_variables extract_variables({"_context": "x", "_id": "y", "_max_chars": 10}) # → {} extract_variables({"_name": "Alice", "_context": "greeting"}) # → {"_name": "Alice"} ``` -------------------------------- ### setupProject(files, options) Source: https://generaltranslation.com/en-US/docs/platform/core/reference/gt-class-methods/translation/setup-project Initializes the translation project setup process. This method is typically required before enqueueing translation jobs for new projects. ```APIDOC ## setupProject(files, options) ### Description Analyzes file content and structure to optimize translation workflows. This operation runs asynchronously. ### Parameters - **files** (FileReference[]) - Required - File references from previously uploaded source files. - **options** (SetupProjectOptions) - Optional - Settings for the setup job. ### FileReference Type - **fileId** (string) - **versionId** (string) - **branchId** (string) - **fileName** (string) - **fileFormat** (FileFormat) - **transformFormat** (FileFormat) - Optional - **dataFormat** (DataFormat) - Optional ### SetupProjectOptions Fields - **force** (boolean) - Optional - Force re-setup by invalidating existing cached translations. - **locales** (string[]) - Optional - Target locales for the Project. - **timeoutMs** (number) - Optional - Timeout in milliseconds for the API request. ``` -------------------------------- ### Example usage of decodeVars Source: https://generaltranslation.com/en-US/docs/node/reference/functions/decode-vars A simple example showing the interpolation of an encoded string. ```ts import { decodeVars, declareVar } from 'gt-node'; const encoded = 'Hi ' + declareVar('Brian') + ', my name is {name}'; console.log(decodeVars(encoded)); // 'Hi Brian, my name is {name}' ``` -------------------------------- ### Custom Translation Loader Example Source: https://generaltranslation.com/en-US/docs/node/reference/functions/initialize-gt Initialization using a custom asynchronous loader to fetch translations from an external API. ```ts // With a custom translation loader import { initializeGT } from 'gt-node'; initializeGT({ defaultLocale: 'en', locales: ['en', 'es'], loadTranslations: async (locale) => { const res = await fetch(`https://my-api.com/translations/${locale}`); return res.json(); }, }); ``` -------------------------------- ### GET /v2/project/setup/should-generate Source: https://generaltranslation.com/en-US/docs/platform/openapi/reference/context/check-freshness Check whether the Project needs translation context generated. This deprecated endpoint is retained for backward compatibility. ```APIDOC ## GET /v2/project/setup/should-generate ### Description Check whether the Project needs translation context generated. This deprecated endpoint is retained for backward compatibility and is no longer called by current clients. ### Method GET ### Endpoint https://api.gtx.dev/v2/project/setup/should-generate ### Parameters #### Header Parameters - **gt-api-version** (string) - Optional - API version. Defaults to the earliest supported version. Latest is 2026-03-06.v1. - **gt-project-id** (string) - Optional - Target project ID. Required when authenticating with an organization API key. ### Response #### Success Response (200) - **shouldSetupProject** (boolean) - Whether context generation is recommended. #### Error Response (401) - **error** (string) - Missing or invalid API key. #### Error Response (403) - **error** (string) - The API key lacks the required permission, or the action is not allowed on the current plan. ``` -------------------------------- ### POST /v2/project/setup/generate Source: https://generaltranslation.com/en-US/docs/platform/openapi/reference/context/generate-context Generates glossaries and translation instructions for the specified project files. ```APIDOC ## POST https://api.gtx.dev/v2/project/setup/generate ### Description Generate glossaries and translation instructions for the project. ### Method POST ### Endpoint https://api.gtx.dev/v2/project/setup/generate ### Parameters #### Headers - **gt-api-version** (string) - Optional - API version. Defaults to the earliest supported version. Latest is 2026-03-06.v1. - **gt-project-id** (string) - Optional - Target project ID. Required when authenticating with an organization API key. #### Request Body - **files** (object[]) - Required - List of files to process. - **branchId** (string) - Optional - **fileId** (string) - Required - **versionId** (string) - Required - **locales** (string[]) - Optional - Target locales for glossary generation. - **force** (boolean) - Optional - Default: false. ### Response #### Success Response (200) - **setupJobId** (string) - The ID of the generated setup job. - **status** (string) - The status of the job (queued or completed). #### Error Responses - **400**: The request was invalid. - **401**: Missing or invalid API key. - **403**: The API key lacks the required permission, or the action is not allowed on the current plan. ``` -------------------------------- ### CI/CD pipeline workflow example Source: https://generaltranslation.com/en-US/docs/cli/reference/commands/enqueue Demonstrates the sequence of commands for splitting translation tasks into separate upload, enqueue, and download stages. ```bash # Stage 1: upload source files npx gt upload # Stage 2: enqueue the uploaded files for translation npx gt enqueue # Stage 3: download the results once they are ready npx gt download ``` -------------------------------- ### setupProject Method Signature Source: https://generaltranslation.com/en-US/docs/platform/core/reference/gt-class-methods/translation/setup-project Defines the input parameters and return type for the setupProject method. ```typescript setupProject( files: FileReference[], options?: SetupProjectOptions ): Promise ``` -------------------------------- ### Implement translations loading in a root route Source: https://generaltranslation.com/en-US/docs/react/reference/functions/get-translations-snapshot Example of initializing the GT provider and loading translations within a root route handler. ```tsx import { GTProvider, initializeGT, getTranslationsSnapshot, parseLocale, } from 'gt-react'; import gtConfig from '../../gt.config.json'; const loadTranslations = (locale: string) => import(`../_gt/${locale}.json`).then((m) => m.default); initializeGT({ ...gtConfig, loadTranslations }); export async function loadRoot(request: Request) { const locale = parseLocale(request); return { locale, translations: await getTranslationsSnapshot(locale), // [!code highlight] }; } export function Root({ locale, translations, children }) { return ( {children} ); } ``` -------------------------------- ### User locale negotiation example Source: https://generaltranslation.com/en-US/docs/platform/core/reference/gt-class-methods/locales/determine-locale Example of using determineLocale to resolve a user's preferred locales against a set of approved locales. ```typescript // User locale negotiation const gt = new GT({ sourceLocale: 'en-US', locales: ['en-US', 'en-GB', 'es-ES', 'fr-FR'], }); // Simulate a browser Accept-Language header const userPreferences = ['fr-CA', 'en-GB', 'en']; const bestMatch = gt.determineLocale(userPreferences); console.log(bestMatch); // 'fr-FR' based on preference order ``` -------------------------------- ### Translate a plain string Source: https://generaltranslation.com/en-US/docs/platform/core/reference/types/translate-many-entry Example of passing a simple string as a TranslateManyEntry. ```typescript 'Hello, world!' ``` -------------------------------- ### Basic Plural Example Source: https://generaltranslation.com/en-US/docs/react/reference/components/plural A standard implementation of the Plural component for count-based text. ```tsx import { Plural } from 'gt-react'; export default function ItemCount({ count }) { return ( You have one item.} other={<>You have some items.} /> ); } ``` -------------------------------- ### initialize_gt(app, **kwargs) Source: https://generaltranslation.com/en-US/docs/python/reference/functions/initialize-gt Initializes the General Translation SDK for a web framework application. ```APIDOC ## initialize_gt(app, **kwargs) ### Description Configures the General Translation SDK for a Flask or FastAPI application. This function must be called once at startup to build the translation manager and register locale detection. ### Signature `initialize_gt(app, *, default_locale=None, locales=None, custom_mapping=None, project_id=None, cache_url=None, version_id=None, get_locale=None, load_translations=None, eager_loading=True, config_path=None, load_config=None) -> I18nManager` ### Parameters - **app** (Flask/FastAPI object) - Required - The web application instance. - **default_locale** (str) - Optional - The default locale to use. - **locales** (list[str]) - Optional - A list of supported locales. - **custom_mapping** (CustomMapping) - Optional - Custom mapping configuration. - **project_id** (str) - Optional - The project identifier for CDN delivery. - **cache_url** (str) - Optional - The URL for the translation cache. - **version_id** (str) - Optional - The specific version identifier. - **get_locale** (Callable) - Optional - A function to detect the current locale. - **load_translations** (Callable) - Optional - A function to load translation dictionaries. - **eager_loading** (bool) - Optional - Whether to load translations eagerly (default: True). - **config_path** (str) - Optional - Path to the configuration file. - **load_config** (Callable) - Optional - A function to load the configuration. ### Returns - **I18nManager** - The configured translation manager instance. ``` -------------------------------- ### Configure environment variables for TanStack Start Source: https://generaltranslation.com/en-US/docs/react/guides/configuring Define the project ID and development API key using Vite-prefixed environment variables. ```bash VITE_GT_PROJECT_ID="..." VITE_GT_DEV_API_KEY="gtx-dev-..." ``` -------------------------------- ### Integrate compiler with Vite Source: https://generaltranslation.com/en-US/docs/react/guides/developing-spa-translations Import the compiler plugin and configuration into the Vite setup. ```typescript import react from '@vitejs/plugin-react'; import { vite as gtCompiler } from '@generaltranslation/compiler'; // [!code highlight] import { defineConfig } from 'vite'; import gtConfig from './gt.config.json'; // [!code highlight] export default defineConfig({ plugins: [react(), gtCompiler({ ...gtConfig })], // [!code highlight] }); ``` -------------------------------- ### new GT(params?: GTConstructorParams) Source: https://generaltranslation.com/en-US/docs/platform/core/reference/gt-class/constructor Initializes a new GT instance. Credentials and settings provided here serve as defaults for all subsequent method calls. ```APIDOC ## new GT(params?: GTConstructorParams) ### Description Creates a new GT instance, which serves as the entry point for all translation, formatting, and locale functionality. It is recommended to instantiate this once and reuse it throughout the application. ### Signature `new GT(params?: GTConstructorParams): GT` ### Parameters - **params** (GTConstructorParams) - Optional - Configuration object containing: - **apiKey** (string) - Optional - API key for authentication. Falls back to `GT_API_KEY` environment variable. - **devApiKey** (string) - Optional - Development API key. Falls back to `GT_DEV_API_KEY` environment variable. - **projectId** (string) - Optional - Project identifier. Falls back to `GT_PROJECT_ID` environment variable. - **sourceLocale** (string) - Optional - Default source locale code. - **targetLocale** (string) - Optional - Default target locale code. ### Usage Example ```typescript import { GT } from 'generaltranslation'; const gt = new GT({ apiKey: 'your-api-key', projectId: 'your-project-id', sourceLocale: 'en', targetLocale: 'es', }); ``` ``` -------------------------------- ### Configure API credentials Source: https://generaltranslation.com/en-US/docs/platform/core/quickstart Set your project ID and API key as environment variables. ```bash GT_PROJECT_ID=your-project-id GT_API_KEY=your-api-key ``` -------------------------------- ### Translate a simple string Source: https://generaltranslation.com/en-US/docs/react/reference/hooks/use-gt Example of using the translation function within a functional component. ```tsx import { useGT } from 'gt-react'; export default function TranslateGreeting() { const gt = useGT(); return

{gt('Hello, Alice!')}

; } // "Hello, Alice!" is translated to the user's locale. ``` -------------------------------- ### Customizing Terminators and Separators Source: https://generaltranslation.com/en-US/docs/platform/core/reference/utility-functions/formatting/format-cutoff Examples of overriding default terminators and adding custom separators. ```typescript // Custom terminators // Custom terminator console.log(formatCutoff('Long text here', { locales: 'en-US', maxChars: 10, terminator: '...', })); // Output: "Long te..." // Custom terminator with separator console.log(formatCutoff('Another example', { locales: 'en-US', maxChars: 12, terminator: '[more]', separator: ' ', })); // Output: "Anoth [more]" // No terminator console.log(formatCutoff('Clean cut', { locales: 'en-US', maxChars: 5, style: 'none', })); // Output: "Clean" ``` -------------------------------- ### Validate locales with explicit variables Source: https://generaltranslation.com/en-US/docs/platform/core/reference/gt-class-methods/locales/is-valid-locale Example showing the validation result stored in variables. ```typescript const gt = new GT({ sourceLocale: 'en', targetLocale: 'es' }); const isValid = gt.isValidLocale('en-US'); console.log(isValid); // true const isInvalid = gt.isValidLocale('invalid-locale'); console.log(isInvalid); // false ``` -------------------------------- ### Define Pre-process and Post-process Commands Source: https://generaltranslation.com/en-US/docs/platform/locadex/guides/configuring-automations Examples of commands to run before or after Locadex processes files, such as building the project or running type checks. ```bash npm run build ``` ```bash npm run typecheck ``` -------------------------------- ### Set environment credentials Source: https://generaltranslation.com/en-US/docs/node/guides/configuring Configure the SDK by exporting project and API key credentials as environment variables. ```bash export GT_PROJECT_ID="your-project-id" export GT_DEV_API_KEY="gtx-dev-..." export GT_API_KEY="gtx-api-..." ``` -------------------------------- ### Using getLocales in an Express handler Source: https://generaltranslation.com/en-US/docs/node/reference/functions/get-locales Example of returning supported locales from an API endpoint. ```js // Basic usage import { getLocales } from 'gt-node'; app.get('/api/locales', (req, res) => { res.json({ supportedLocales: getLocales() }); }); ``` -------------------------------- ### Basic usage in a handler Source: https://generaltranslation.com/en-US/docs/node/reference/functions/get-default-locale Example of using getDefaultLocale within an Express-style route handler. ```js // Basic usage import { getDefaultLocale } from 'gt-node'; app.get('/api/info', (req, res) => { res.json({ defaultLocale: getDefaultLocale() }); }); ``` -------------------------------- ### Run configuration command Source: https://generaltranslation.com/en-US/docs/cli/reference/commands/configure Executes the interactive configuration wizard to create or update the gt.config.json file. ```bash npx gt configure ``` ```bash # Write gt.config.json interactively npx gt configure ``` -------------------------------- ### Upload a font file Source: https://generaltranslation.com/en-US/docs/platform/core/reference/gt-class-methods/translation/upload-fonts Example demonstrating how to read a local font file, encode it as base64, and upload it using the GT client. ```typescript import { readFile } from 'node:fs/promises'; import { GT } from 'generaltranslation'; const gt = new GT({ apiKey: process.env.GT_API_KEY, projectId: process.env.GT_PROJECT_ID, }); const content = (await readFile('./public/fonts/BrandSans.ttf')).toString( 'base64' ); const result = await gt.uploadFonts([ { assetType: 'FONT', content, fileName: 'BrandSans.ttf', }, ]); console.log(result.assets[0].assetKey); ``` -------------------------------- ### Manual JSX wrapping Source: https://generaltranslation.com/en-US/docs/cli/guides/using-auto-jsx Example of wrapping translatable text manually using the component. ```jsx import { T } from 'gt-react'; function Welcome() { return (

Welcome to our app

); } ``` -------------------------------- ### Initialize the GT class Source: https://generaltranslation.com/en-US/docs/platform/core/quickstart Create a GT instance with your credentials. You can optionally specify default source and target locales. ```typescript import { GT } from 'generaltranslation'; const gt = new GT({ projectId: 'your-project-id', apiKey: 'your-api-key', }); ``` ```typescript const gt = new GT({ projectId: 'your-project-id', apiKey: 'your-api-key', sourceLocale: 'en', targetLocale: 'es', }); ``` -------------------------------- ### Example of variable marker replacement Source: https://generaltranslation.com/en-US/docs/python/reference/functions/decode-vars Shows the replacement of a count variable marker within a string. ```python from gt_i18n import declare_var, decode_vars marked = f"You have {declare_var('5', name='count')} messages" decode_vars(marked) # "You have 5 messages" ``` -------------------------------- ### Run gt download Source: https://generaltranslation.com/en-US/docs/cli/reference/commands/download Executes the download command to fetch completed translations. ```bash npx gt download ``` -------------------------------- ### Implement custom translation loaders Source: https://generaltranslation.com/en-US/docs/python/reference/classes/translations-loader Examples of synchronous and asynchronous loader implementations that can be passed to the I18nManager. ```python import json from pathlib import Path from gt_i18n import I18nManager, TranslationsLoader # A synchronous loader reading one JSON file per locale def load_translations(locale: str) -> dict[str, str]: path = Path("translations") / f"{locale}.json" return json.loads(path.read_text()) if path.exists() else {} loader: TranslationsLoader = load_translations manager = I18nManager(default_locale="en", locales=["es"], load_translations=loader) ``` ```python # An async loader is also valid async def load_translations(locale: str) -> dict[str, str]: return await fetch_from_somewhere(locale) ``` -------------------------------- ### Initialize Application Source: https://generaltranslation.com/en-US/docs/python/quickstart Register the translation integration with your Flask or FastAPI application instance. ```python from flask import Flask from gt_flask import initialize_gt, t, get_locale app = Flask(__name__) initialize_gt(app) @app.route("/") def index(): return {"message": t("Hello, world!"), "locale": get_locale()} ``` ```python from fastapi import FastAPI from gt_fastapi import initialize_gt, t, get_locale app = FastAPI() initialize_gt(app) @app.get("/") def index(): return {"message": t("Hello, world!"), "locale": get_locale()} ``` -------------------------------- ### Use Variables in JSX Source: https://generaltranslation.com/en-US/docs/platform/core/reference/types/variable Example of embedding Variable objects within JSX content arrays. ```typescript // In JSX content const welcomeContent = [ 'Welcome back, ', { k: 'userName' } as Variable, '! You have ', { k: 'messageCount', v: 'n' } as Variable, ' messages.' ]; ``` -------------------------------- ### Basic usage Source: https://generaltranslation.com/en-US/docs/react/nextjs/reference/components/tx Import the component from gt-next/server and wrap dynamic content with a context string. ```tsx import { Tx } from 'gt-next/server'; Welcome back; ``` -------------------------------- ### Define SetupProjectResult Type Source: https://generaltranslation.com/en-US/docs/platform/core/reference/gt-class-methods/translation/setup-project The return type for setupProject, representing either a queued job or a completed project state. ```typescript type SetupProjectResult = | { setupJobId: string; status: 'queued' } | { status: 'completed' }; ``` -------------------------------- ### Configure GTProvider in TanStack Start Source: https://generaltranslation.com/en-US/docs/react/guides/configuring Pass the active locale and translations directly to the provider component. ```tsx import { GTProvider, getTranslationsSnapshot } from 'gt-tanstack-start'; const translations = await getTranslationsSnapshot(locale); ; ```