Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 24 additions & 4 deletions packages/create-plugin/src/codemods/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,41 @@ This guide provides specific instructions for working with migrations and additi
## Agent Behavior

- Refer to current migrations and additions typescript files found in @./additions/scripts and @./migrations/scripts
- When creating a new migration add it to the exported migrations object in @./migrations/migrations.ts
- Always refer to @./context.ts to know what methods are available on the context class
- Always check for file existence using the @./context.ts class before attempting to do anything with it
- Never write files with any 3rd party npm library. Use the context for all file operations
- Always return the context for the next migration
- Always return the context for the next migration/addition
- Test thoroughly using the provided utils in @./test-utils.ts where necessary
- Never attempt to read or write files outside the current working directory

## Migrations

Migrations are automatically run during `create-plugin update` to keep plugins compatible with newer versions of the tooling. They are forced upon developers to ensure compatibility and are versioned based on the create-plugin version. Migrations primarily target configuration files or files that are scaffolded by create-plugin.

### Migration Behavior

- When creating a new migration add it to the exported migrations object in @./migrations/migrations.ts
- Each migration must be idempotent and must include a test case that uses the `.toBeIdempotent` custom matcher found in @../../vitest.setup.ts
- Keep migrations focused on one task
- Never attempt to read or write files outside the current working directory

## Naming Conventions
### Migration Naming Conventions

- Each migration lives under @./migrations/scripts
- Migration filenames follow the format: `NNN-migration-title` where migration-title is, at the most, a three word summary of what the migration does and NNN is the next number in sequence based on the current file name in @./migrations/scripts
- Each migration must have:
- `NNN-migration-title.ts` - main migration logic
- `NNN-migration-title.test.ts` - migration logic tests
- Each migration should export a default function named "migrate"

## Additions

Additions are optional features that developers choose to add via `create-plugin add`. They are not versioned and can be run at any time to enhance a plugin with new capabilities.

### Addition Behavior

- Additions add new features or capabilities to a plugin (e.g., i18n support, testing frameworks, etc.)
- It should be safe to run multiple times
- Always use defensive programming: check if features already exist before adding them
- Use `additionsDebug()` for logging to help with troubleshooting
- If the addition accepts user input, export a `schema` object using `valibot` for input validation
- Each addition should export a default function that takes `(context: Context, options?: T)` and returns `Context`
6 changes: 3 additions & 3 deletions packages/create-plugin/src/codemods/additions/additions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { Codemod } from '../types.js';

export default [
{
name: 'example-addition',
description: 'Adds an example addition to the plugin',
scriptPath: import.meta.resolve('./scripts/example-addition.js'),
name: 'i18n',
description: 'Adds internationalization (i18n) support to the plugin',
scriptPath: import.meta.resolve('./scripts/i18n/index.js'),
},
] satisfies Codemod[];
161 changes: 161 additions & 0 deletions packages/create-plugin/src/codemods/additions/scripts/i18n/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
# I18n Addition

Adds internationalization (i18n) support to a Grafana plugin.

## Usage

```bash
npx @grafana/create-plugin add i18n --locales <locales>
```

## Requirements

- **Grafana >= 11.0.0**: i18n is not supported for Grafana versions prior to 11.0.0. If your plugin's `grafanaDependency` is set to a version < 11.0.0, the script will automatically update it to `>=11.0.0` (it will not exit with an error).
- **React >= 18**: The `@grafana/i18n` package requires React 18 or higher. If your plugin uses React < 18, the script will exit with an error and prompt you to upgrade.

## Required Flags

### `--locales`

A comma-separated list of locale codes to support in your plugin.

**Format:** Locale codes must follow the `xx-XX` pattern (e.g., `en-US`, `es-ES`, `sv-SE`)

**Example:**

```bash
npx @grafana/create-plugin add i18n --locales en-US,es-ES,sv-SE
```

## What This Addition Does

**Important:** This script sets up the infrastructure and configuration needed for translations. After running this script, you'll need to:

1. Mark up your code with translation functions (`t()` and `<Trans>`)
2. Run `npm run i18n-extract` to extract translatable strings
3. Fill in the locale JSON files with translated strings

This addition configures your plugin for internationalization by:

1. **Updating `docker-compose.yaml`** - Adds the `localizationForPlugins` feature toggle to your local Grafana instance
2. **Updating `src/plugin.json`** - Adds the `languages` array and updates `grafanaDependency`
3. **Creating locale files** - Creates empty JSON files for each locale at `src/locales/{locale}/{pluginId}.json`
4. **Adding dependencies** - Installs `@grafana/i18n` and optionally `semver` (for backward compatibility)
5. **Updating ESLint config** - Adds i18n linting rules to catch untranslated strings
6. **Initializing i18n in module.ts** - Adds `initPluginTranslations()` call to your plugin's entry point
7. **Creating support files**:
- `i18next.config.ts` - Configuration for extracting translations
- `src/loadResources.ts` - (Only for Grafana < 12.1.0) Custom resource loader
8. **Adding npm scripts** - Adds `i18n-extract` script to extract translations from your code

## Backward Compatibility

**Note:** i18n is not supported for Grafana versions prior to 11.0.0.

The addition automatically detects your plugin's `grafanaDependency` version:

### Grafana >= 12.1.0

- Sets `grafanaDependency` to `>=12.1.0`
- Grafana handles loading translations automatically
- Simple initialization: `await initPluginTranslations(pluginJson.id)`
- No `loadResources.ts` file needed
- No `semver` dependency needed

### Grafana 11.0.0 - 12.0.x

- Keeps or sets `grafanaDependency` to `>=11.0.0`
- Plugin handles loading translations
- Creates `src/loadResources.ts` for custom resource loading
- Adds runtime version check using `semver`
- Initialization with loaders: `await initPluginTranslations(pluginJson.id, loaders)`

## Running Multiple Times

This addition can be run multiple times safely. It uses defensive programming to check if configurations already exist before adding them, preventing duplicates and overwrites:

### Adding New Locales

You can run the command again with additional locales to add them:

```bash
# First run
npx @grafana/create-plugin add i18n --locales en-US

# Later, add more locales
npx @grafana/create-plugin add i18n --locales en-US,es-ES,sv-SE
```

The addition will:

- Merge new locales into `plugin.json` without duplicates
- Create only the new locale files (won't overwrite existing ones)
- Skip updating files that already have i18n configured

## Files Created

```
your-plugin/
├── docker-compose.yaml # Modified: adds localizationForPlugins toggle
├── src/
│ ├── plugin.json # Modified: adds languages array
│ ├── module.ts # Modified: adds i18n initialization
│ ├── loadResources.ts # Created: (Grafana 11.x only) resource loader
│ └── locales/
│ ├── en-US/
│ │ └── your-plugin-id.json # Created: empty translation file
│ ├── es-ES/
│ │ └── your-plugin-id.json # Created: empty translation file
│ └── sv-SE/
│ └── your-plugin-id.json # Created: empty translation file
├── i18next.config.ts # Created: extraction config
├── eslint.config.mjs # Modified: adds i18n linting rules
└── package.json # Modified: adds dependencies and scripts
```

## Dependencies Added

**Always:**

- `@grafana/i18n` (v12.2.2) - i18n utilities and types
- `i18next-cli` (dev) - Translation extraction tool

**For Grafana 11.x only:**

- `semver` - Runtime version checking
- `@types/semver` (dev) - TypeScript types for semver

## Next Steps

After running this addition:

1. **Use in code**: Import and use the translation functions to mark up your code:

```typescript
import { t, Trans } from '@grafana/i18n';

// Use t() for simple strings
const title = t('components.myComponent.title', 'Default Title');

// Use Trans for JSX
<Trans i18nKey="components.myComponent.description">
This is a description
</Trans>
```

2. **Extract translations**: Run `npm run i18n-extract` to scan your code for translatable strings
3. **Add translations**: Fill in your locale JSON files with translated strings

## Debug Output

Enable debug logging to see what the addition is doing:

```bash
DEBUG=create-plugin:additions npx @grafana/create-plugin add i18n --locales en-US,es-ES
```

## References

- [Grafana i18n Documentation](https://grafana.com/developers/plugin-tools/how-to-guides/plugin-internationalization)
- [Grafana 11.x i18n Documentation](https://grafana.com/developers/plugin-tools/how-to-guides/plugin-internationalization-grafana-11)
- [Available Languages](https://github.com/grafana/grafana/blob/main/packages/grafana-i18n/src/constants.ts)
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
import * as recast from 'recast';
import * as babelParser from 'recast/parsers/babel-ts.js';

import type { Context } from '../../../context.js';
import { additionsDebug } from '../../../utils.js';

const { builders } = recast.types;

export function addI18nInitialization(context: Context, needsBackwardCompatibility: boolean): void {
// Find module.ts or module.tsx
const moduleTsPath = context.doesFileExist('src/module.ts')
? 'src/module.ts'
: context.doesFileExist('src/module.tsx')
? 'src/module.tsx'
: null;

if (!moduleTsPath) {
additionsDebug('No module.ts or module.tsx found, skipping i18n initialization');
return;
}

const moduleContent = context.getFile(moduleTsPath);
if (!moduleContent) {
return;
}

// Defensive: check if i18n is already initialized
if (moduleContent.includes('initPluginTranslations')) {
additionsDebug('i18n already initialized in module file');
return;
}

try {
const ast = recast.parse(moduleContent, {
parser: babelParser,
});

const imports = [];

// Add necessary imports based on backward compatibility
imports.push(
builders.importDeclaration(
[builders.importSpecifier(builders.identifier('initPluginTranslations'))],
builders.literal('@grafana/i18n')
)
);

imports.push(
builders.importDeclaration(
[builders.importDefaultSpecifier(builders.identifier('pluginJson'))],
builders.literal('plugin.json')
)
);

if (needsBackwardCompatibility) {
imports.push(
builders.importDeclaration(
[builders.importSpecifier(builders.identifier('config'))],
builders.literal('@grafana/runtime')
)
);
imports.push(
builders.importDeclaration(
[builders.importDefaultSpecifier(builders.identifier('semver'))],
builders.literal('semver')
)
);
imports.push(
builders.importDeclaration(
[builders.importSpecifier(builders.identifier('loadResources'))],
builders.literal('./loadResources')
)
);
}

// Find the last import index (use consistent approach for both imports and initialization)
const lastImportIndex = ast.program.body.findLastIndex((node: any) => node.type === 'ImportDeclaration');

// Add imports after the last import statement
if (lastImportIndex !== -1) {
ast.program.body.splice(lastImportIndex + 1, 0, ...imports);
} else {
ast.program.body.unshift(...imports);
}

// Add i18n initialization code
const i18nInitCode = needsBackwardCompatibility
? `// Before Grafana version 12.1.0 the plugin is responsible for loading translation resources
// In Grafana version 12.1.0 and later Grafana is responsible for loading translation resources
const loaders = semver.lt(config?.buildInfo?.version, '12.1.0') ? [loadResources] : [];

await initPluginTranslations(pluginJson.id, loaders);`
: `await initPluginTranslations(pluginJson.id);`;

// Parse the initialization code and insert it at the top level (after imports)
const initAst = recast.parse(i18nInitCode, {
parser: babelParser,
});

// Find the last import index again (after adding new imports)
const finalLastImportIndex = ast.program.body.findLastIndex((node: any) => node.type === 'ImportDeclaration');
if (finalLastImportIndex !== -1) {
ast.program.body.splice(finalLastImportIndex + 1, 0, ...initAst.program.body);
} else {
ast.program.body.unshift(...initAst.program.body);
}

const output = recast.print(ast, {
tabWidth: 2,
trailingComma: true,
lineTerminator: '\n',
}).code;

context.updateFile(moduleTsPath, output);
additionsDebug(`Updated ${moduleTsPath} with i18n initialization`);
} catch (error) {
additionsDebug('Error updating module file:', error);
}
}

export function createLoadResourcesFile(context: Context): void {
const loadResourcesPath = 'src/loadResources.ts';

// Defensive: skip if already exists
if (context.doesFileExist(loadResourcesPath)) {
additionsDebug('loadResources.ts already exists, skipping');
return;
}

const pluginJsonRaw = context.getFile('src/plugin.json');
if (!pluginJsonRaw) {
additionsDebug('Cannot create loadResources.ts without plugin.json');
return;
}

const loadResourcesContent = `import { LANGUAGES, ResourceLoader, Resources } from '@grafana/i18n';
import pluginJson from 'plugin.json';

const resources = LANGUAGES.reduce<Record<string, () => Promise<{ default: Resources }>>>((acc, lang) => {
acc[lang.code] = () => import(\`./locales/\${lang.code}/\${pluginJson.id}.json\`);
return acc;
}, {});

export const loadResources: ResourceLoader = async (resolvedLanguage: string) => {
try {
const translation = await resources[resolvedLanguage]();
return translation.default;
} catch (error) {
// This makes sure that the plugin doesn't crash when the resolved language in Grafana isn't supported by the plugin
console.error(\`The plugin '\${pluginJson.id}' doesn't support the language '\${resolvedLanguage}'\`, error);
return {};
}
};
`;

context.addFile(loadResourcesPath, loadResourcesContent);
additionsDebug('Created src/loadResources.ts for backward compatibility');
}
Loading
Loading