Transloco Keys Manager (TKM)

repository·master·Indexed 42 days ago

https://github.com/jsverse/transloco-keys-manager

A utility for the Transloco translation library that automates the extraction, management, and auditing of translation keys. It provides a CLI and programmatic API to find missing or extra keys, support scoped translations, and integrate with Webpack. Version 8.1.1 supports ESM and is available under the @jsverse scope.

Tokens
6.5K
Snippets
15
Records
25
Agent score
52%

What's inside Transloco Keys Manager

  1. Overview of Transloco Keys Manager features

    master

    Transloco Keys Manager is a tool designed to automate the repetitive tasks associated with managing translation files. Its primary capabilities include:

    • Extract Translate Keys: Automatically finds and extracts translation keys from your source code.
    • Scopes Support: Handles translation keys organized by scopes.
    • Webpack Plugin: Integrates directly into your Webpack build process.
    • Find Missing and Extra Keys: Identifies keys that exist in your code but are missing from translation files, or keys in translation files that are no longer used in your code.
  2. Understand translation shape normalization in V9

    master

    In V9, the extract command normalizes the existing translation files on disk to match your configured output shape before merging them with extracted keys.

    Previously, if your unflat setting was falsy (the default), the tool would merge flat extracted keys into nested JSON files, resulting in duplicated keys (e.g., both used.key and used: { key: ... } appearing in the same file).

    What to expect upon upgrading: If your translation files do not currently match your unflat setting, the first extract run after upgrading to V9 will rewrite those files into a single, consistent shape. This will appear as a large one-time diff in your version control.

  3. How dynamic template keys inherit 'read' values (V2 behavior)

    master

    In version 2, comments in templates used for key extraction inherit the read input value from the *transloco directive. This allows for nested key extraction based on the context provided by the directive.

    Example:

    <!-- t(this.is.cool) -->
    <ng-container *transloco="let m; read: 'messages'">
        ...
        <!-- t(success, error) -->
        <ng-container *transloco="let g; read: 'general'">
            ...
            <!-- t(ok, cancel) -->
        </ng-container>
    </ng-container>

    Resulting extracted keys:

    {
      "this.is.cool": "",
      "messages.success": "",
      "messages.error": "",
      "general.ok": "",
      "general.cancel": ""
    }
  4. How `scopePathMap` affects extra key reporting in V9

    master

    In V9, the behavior of find --emit-error-on-extra-keys has changed regarding how it handles scopes defined in scopePathMap that no longer exist in your source code.

    Behavior Change

    Previously, if a scope was mapped in scopePathMap but no code declared that scope, the extractor would silently skip the associated translation files.

    In V9, if a scope is explicitly mapped in scopePathMap but no code declares it, the tool treats that scope as having zero keys. Consequently, the extractor will read the translation files for that scope and report every key within them as an extra key.

    Impact

    If you have stale mappings in your scopePathMap for features or scopes that have been deleted from your codebase, running find --emit-error-on-extra-keys will now result in an error (exit code 2) instead of exiting successfully (exit code 0).

  5. Behavior of `*.comment` keys with `--remove-extra-keys` in V9

    master

    In V9, the extract --remove-extra-keys command has been updated to respect the same rules as the find command regarding comment keys.

    Keys ending with the .comment suffix (e.g., used.key.comment) are treated as translator notes and are not considered extra keys. Consequently, they will no longer be deleted when running extract --remove-extra-keys.

    Note: This change ensures that find remains the single source of truth for what constitutes an 'extra key' in your project.

  6. CLI flag validation and error handling in V9

    master

    V9 introduces stricter validation for command-line flags. The CLI now distinguishes between flags supported by a specific command and those that are not.

    Behavior by Source

    • Explicit CLI Flags: If you pass a flag that the specific command (e.g., extract) does not support, the CLI will throw a hard error and exit with a non-zero exit code.
    • Configuration Files: Flags defined in your transloco.config.js or .ts file that are only relevant to other commands (e.g., setting emitErrorOnExtraKeys in a config used for both find and extract) will remain silent and will not cause errors. This ensures that shared configurations do not break automated workflows.

    Common breaking scenarios

    • Using a shared CI template that passes the same set of flags to both extract and find.
    • Combining commands in an npm script like: tkm extract -e && tkm find -e (where -e is unsupported by extract).
  7. Migrate to Transloco Keys Manager V4 (ESM and Package Scope)

    master

    When upgrading to version 4, note the following breaking changes:

    1. ESM Only: The library has moved to ESM (ECMAScript Modules) only to support newer versions of the Angular compiler.
    2. Package Scope Change: The publishing scope has changed from @ngneat/transloco-keys-manager to @jsverse/transloco-keys-manager.

    Action Required: If you are using marker functions, you must update your import paths to use the new @jsverse/ scope.

  8. Migrate to the new V9 `keysManager` configuration shape

    master

    In Transloco Keys Manager V9, the keysManager configuration object in TranslocoGlobalConfig has been restructured from a flat object into command-specific sections. This change ensures that configuration keys are only applied to the commands they are intended for (extract or find) and provides better TypeScript type safety.

    Breaking Change

    Every existing transloco.config.js that places command-specific keys at the top level of keysManager must be updated. Keys like output, replace, removeExtraKeys, addMissingKeys, or emitErrorOnExtraKeys must now be moved into their respective extract or find blocks.

    New Configuration Structure

    SectionPurposeSupported Keys
    SharedRead by both extract and findinput, langs, fileFormat, marker, defaultValue, sort, unflat, translationsPath
    extractSpecific to the extract commandoutput, replace, removeExtraKeys
    findSpecific to the find commandaddMissingKeys, emitErrorOnExtraKeys

    Example Migration

    Before (V8):

    keysManager: {
      input: 'src/assets/i18n',
      output: 'src/assets/i18n/en.json',
      addMissingKeys: true
    }

    After (V9):

    keysManager: {
      input: 'src/assets/i18n',
      extract: {
        output: 'src/assets/i18n/en.json'
      },
      find: {
        addMissingKeys: true
      }
    }
    keysManager: {
      // read by both commands
      input?: string | string[];
      langs?: string[];
      fileFormat?: 'json' | 'pot';
      marker?: string;
      defaultValue?: string;
      sort?: boolean;
      unflat?: boolean;
      translationsPath?: string;
    
      extract?: { output?: string; replace?: boolean; removeExtraKeys?: boolean };
      find?: { addMissingKeys?: boolean; emitErrorOnExtraKeys?: boolean };
    }
  9. Migrate to the @jsverse scope

    master

    The transloco-keys-manager package and related Transloco packages have moved to the @jsverse NPM scope. To ensure you receive the latest features and updates, you must update your project dependencies to use the new scoped packages (e.g., @jsverse/transloco-keys-manager).

    Note: This repository is archived. For new issues, discussions, or pull requests, please use the jsverse/transloco monorepo.

  10. Migrate to Transloco Keys Manager V5 path configurations

    master

    In version 5, the sourceRoot prefix is only applied to the default configuration. For all other configurations, you must provide the full path relative to the project root for rootTranslationsPath, keysManager.input, and keysManager.output.

    Example Migration:

    Before (v4 and below):

    import {TranslocoGlobalConfig} from "@jsverse/transloco-utils";
    
    const config: TranslocoGlobalConfig = {
       rootTranslationsPath: 'assets/i18n/',
       langs: ['it', 'en'],
       keysManager: {
           input: ['app'],
           output: 'assets/i18n/'
       },
    }
    
    export default config;

    After (v5+):

    import {TranslocoGlobalConfig} from "@jsverse/transloco-utils";
    
    const config: TranslocoGlobalConfig = {
       // Prefix paths with the source root (e.g., 'src/')
       rootTranslationsPath: 'src/assets/i18n/',
       langs: ['it', 'en'],
       keysManager: {
           input: [
               'src/app', 
               'projects/ui-lib/src/lib' // Scanning non-buildable libs is now supported
           ],
           output: 'src/assets/i18n/'
       },
    }
    
    export default config;
    import {TranslocoGlobalConfig} from "@jsverse/transloco-utils";
    
    const config: TranslocoGlobalConfig = {
       rootTranslationsPath: 'src/assets/i18n/',
       langs: ['it', 'en'],
       keysManager: {
           input: [
               'src/app', 
               'projects/ui-lib/src/lib'
           ],
           output: 'src/assets/i18n/'
       },
    }
    
    export default config;
  11. How the templateExtractor works

    master

    The templateExtractor is the core logic used for HTML files. It follows these steps:

    1. Content Loading: It reads the file content from the provided file path or uses config.content if provided.
    2. Early Exit: If the content does not include the term transloco, it returns the current scopeToKeys immediately.
    3. Template Parsing: It uses @angular/compiler's parseTemplate to create a parsed representation of the HTML.
    4. Multi-stage Extraction: It executes a sequence of specialized extractors on the parsed template:
      • pipeExtractor: Finds keys used within pipes.
      • templateCommentsExtractor: Finds keys defined within HTML comments.
      • directiveExtractor: Finds keys used in standard directives.
      • structuralDirectiveExtractor: Finds keys used in structural directives (e.g., *ngIf).
    5. Result: It returns the updated scopeToKeys containing all discovered keys.
  12. How TypeScript key extraction works

    master

    The TypeScript extractor (TSExtractor) follows a multi-stage process to ensure all keys are captured:

    1. Import Detection: It checks for imports from @jsverse/transloco or @ngneat/transloco and @jsverse/transloco-keys-manager. This determines which specialized extractors to run.
    2. Specialized Extraction: If Transloco imports are found, it runs:
      • serviceExtractor: For keys used in Transloco services.
      • pureFunctionExtractor: For keys used in pure functions.
      • signalExtractor: For keys used in Signals.
      • markerExtractor: For keys identified via specific markers (if the keys-manager package is imported).
    3. AST Parsing: If Transloco-related content is detected, it performs an AST parse using tsquery to accurately locate function calls and variable usages.
    4. Comment & Template Scanning:
      • It scans file comments using addCommentSectionKeys to find keys manually defined in comments.
      • It uses inlineTemplateExtractor to find keys within inline templates found in the AST.