@grafana/create-plugin 6.3.0-canary.2320.19638409321.0 → 6.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,157 +0,0 @@
1
- # I18n Addition
2
-
3
- Adds internationalization (i18n) support to a Grafana plugin.
4
-
5
- ## Usage
6
-
7
- ```bash
8
- npx @grafana/create-plugin add i18n --locales <locales>
9
- ```
10
-
11
- ## Required Flags
12
-
13
- ### `--locales`
14
-
15
- A comma-separated list of locale codes to support in your plugin.
16
-
17
- **Format:** Locale codes must follow the `xx-XX` pattern (e.g., `en-US`, `es-ES`, `sv-SE`)
18
-
19
- **Example:**
20
-
21
- ```bash
22
- npx @grafana/create-plugin add i18n --locales en-US,es-ES,sv-SE
23
- ```
24
-
25
- ## What This Addition Does
26
-
27
- This addition configures your plugin for internationalization by:
28
-
29
- 1. **Updating `docker-compose.yaml`** - Adds the `localizationForPlugins` feature toggle to your local Grafana instance
30
- 2. **Updating `src/plugin.json`** - Adds the `languages` array and updates `grafanaDependency`
31
- 3. **Creating locale files** - Creates empty JSON files for each locale at `src/locales/{locale}/{pluginId}.json`
32
- 4. **Adding dependencies** - Installs `@grafana/i18n` and optionally `semver` (for backward compatibility)
33
- 5. **Updating ESLint config** - Adds i18n linting rules to catch untranslated strings
34
- 6. **Initializing i18n in module.ts** - Adds `initPluginTranslations()` call to your plugin's entry point
35
- 7. **Creating support files**:
36
- - `i18next.config.ts` - Configuration for extracting translations
37
- - `src/loadResources.ts` - (Only for Grafana < 12.1.0) Custom resource loader
38
- 8. **Adding npm scripts** - Adds `i18n-extract` script to extract translations from your code
39
-
40
- ## Backward Compatibility
41
-
42
- The addition automatically detects your plugin's `grafanaDependency` version:
43
-
44
- ### Grafana >= 12.1.0 (Modern)
45
-
46
- - Sets `grafanaDependency` to `>=12.1.0`
47
- - Grafana handles loading translations automatically
48
- - Simple initialization: `await initPluginTranslations(pluginJson.id)`
49
- - No `loadResources.ts` file needed
50
- - No `semver` dependency needed
51
-
52
- ### Grafana 11.0.0 - 12.0.x (Backward Compatible)
53
-
54
- - Keeps or sets `grafanaDependency` to `>=11.0.0`
55
- - Plugin handles loading translations
56
- - Creates `src/loadResources.ts` for custom resource loading
57
- - Adds runtime version check using `semver`
58
- - Initialization with loaders: `await initPluginTranslations(pluginJson.id, loaders)`
59
-
60
- ## Running Multiple Times (Idempotent)
61
-
62
- This addition is **defensive** and can be run multiple times safely. Each operation checks if it's already been done:
63
-
64
- ### Adding New Locales
65
-
66
- You can run the command again with additional locales to add them:
67
-
68
- ```bash
69
- # First run
70
- npx @grafana/create-plugin add i18n --locales en-US
71
-
72
- # Later, add more locales
73
- npx @grafana/create-plugin add i18n --locales en-US,es-ES,sv-SE
74
- ```
75
-
76
- The addition will:
77
-
78
- - ✅ Merge new locales into `plugin.json` without duplicates
79
- - ✅ Create only the new locale files (won't overwrite existing ones)
80
- - ✅ Skip updating files that already have i18n configured
81
-
82
- ### What Won't Be Duplicated
83
-
84
- - **Locale files**: Existing locale JSON files are never overwritten (preserves your translations)
85
- - **Dependencies**: Won't re-add dependencies that already exist
86
- - **ESLint config**: Won't duplicate the i18n plugin import or rules
87
- - **Module initialization**: Won't add `initPluginTranslations` if it's already present
88
- - **Support files**: Won't overwrite `i18next.config.ts` or `loadResources.ts` if they exist
89
- - **npm scripts**: Won't overwrite the `i18n-extract` script if it exists
90
- - **Docker feature toggle**: Won't duplicate the feature toggle
91
-
92
- ## Files Created
93
-
94
- ```
95
- your-plugin/
96
- ├── docker-compose.yaml # Modified: adds localizationForPlugins toggle
97
- ├── src/
98
- │ ├── plugin.json # Modified: adds languages array
99
- │ ├── module.ts # Modified: adds i18n initialization
100
- │ ├── loadResources.ts # Created: (Grafana 11.x only) resource loader
101
- │ └── locales/
102
- │ ├── en-US/
103
- │ │ └── your-plugin-id.json # Created: empty translation file
104
- │ ├── es-ES/
105
- │ │ └── your-plugin-id.json # Created: empty translation file
106
- │ └── sv-SE/
107
- │ └── your-plugin-id.json # Created: empty translation file
108
- ├── i18next.config.ts # Created: extraction config
109
- ├── eslint.config.mjs # Modified: adds i18n linting rules
110
- └── package.json # Modified: adds dependencies and scripts
111
- ```
112
-
113
- ## Dependencies Added
114
-
115
- **Always:**
116
-
117
- - `@grafana/i18n` (v12.2.2) - i18n utilities and types
118
- - `i18next-cli` (dev) - Translation extraction tool
119
-
120
- **For Grafana 11.x only:**
121
-
122
- - `semver` - Runtime version checking
123
- - `@types/semver` (dev) - TypeScript types for semver
124
-
125
- ## Next Steps
126
-
127
- After running this addition:
128
-
129
- 1. **Extract translations**: Run `npm run i18n-extract` to scan your code for translatable strings
130
- 2. **Add translations**: Fill in your locale JSON files with translated strings
131
- 3. **Use in code**: Import and use the translation functions:
132
-
133
- ```typescript
134
- import { t, Trans } from '@grafana/i18n';
135
-
136
- // Use t() for simple strings
137
- const title = t('components.myComponent.title', 'Default Title');
138
-
139
- // Use Trans for JSX
140
- <Trans i18nKey="components.myComponent.description">
141
- This is a description
142
- </Trans>
143
- ```
144
-
145
- ## Debug Output
146
-
147
- Enable debug logging to see what the addition is doing:
148
-
149
- ```bash
150
- DEBUG=create-plugin:additions npx @grafana/create-plugin add i18n --locales en-US,es-ES
151
- ```
152
-
153
- ## References
154
-
155
- - [Grafana i18n Documentation](https://grafana.com/developers/plugin-tools/how-to-guides/plugin-internationalization)
156
- - [Grafana 11.x i18n Documentation](https://grafana.com/developers/plugin-tools/how-to-guides/plugin-internationalization-grafana-11)
157
- - [Available Languages](https://github.com/grafana/grafana/blob/main/packages/grafana-i18n/src/constants.ts)
@@ -1,156 +0,0 @@
1
- import * as recast from 'recast';
2
- import * as babelParser from 'recast/parsers/babel-ts.js';
3
-
4
- import type { Context } from '../../../context.js';
5
- import { additionsDebug } from '../../../utils.js';
6
-
7
- const { builders } = recast.types;
8
-
9
- export function addI18nInitialization(context: Context, needsBackwardCompatibility: boolean): void {
10
- // Find module.ts or module.tsx
11
- const moduleTsPath = context.doesFileExist('src/module.ts')
12
- ? 'src/module.ts'
13
- : context.doesFileExist('src/module.tsx')
14
- ? 'src/module.tsx'
15
- : null;
16
-
17
- if (!moduleTsPath) {
18
- additionsDebug('No module.ts or module.tsx found, skipping i18n initialization');
19
- return;
20
- }
21
-
22
- const moduleContent = context.getFile(moduleTsPath);
23
- if (!moduleContent) {
24
- return;
25
- }
26
-
27
- // Defensive: check if i18n is already initialized
28
- if (moduleContent.includes('initPluginTranslations')) {
29
- additionsDebug('i18n already initialized in module file');
30
- return;
31
- }
32
-
33
- try {
34
- const ast = recast.parse(moduleContent, {
35
- parser: babelParser,
36
- });
37
-
38
- const imports = [];
39
-
40
- // Add necessary imports based on backward compatibility
41
- imports.push(
42
- builders.importDeclaration(
43
- [builders.importSpecifier(builders.identifier('initPluginTranslations'))],
44
- builders.literal('@grafana/i18n')
45
- )
46
- );
47
-
48
- imports.push(
49
- builders.importDeclaration(
50
- [builders.importDefaultSpecifier(builders.identifier('pluginJson'))],
51
- builders.literal('plugin.json')
52
- )
53
- );
54
-
55
- if (needsBackwardCompatibility) {
56
- imports.push(
57
- builders.importDeclaration(
58
- [builders.importSpecifier(builders.identifier('config'))],
59
- builders.literal('@grafana/runtime')
60
- )
61
- );
62
- imports.push(
63
- builders.importDeclaration(
64
- [builders.importDefaultSpecifier(builders.identifier('semver'))],
65
- builders.literal('semver')
66
- )
67
- );
68
- imports.push(
69
- builders.importDeclaration(
70
- [builders.importSpecifier(builders.identifier('loadResources'))],
71
- builders.literal('./loadResources')
72
- )
73
- );
74
- }
75
-
76
- // Add imports after the first import statement
77
- const firstImportIndex = ast.program.body.findIndex((node: any) => node.type === 'ImportDeclaration');
78
- if (firstImportIndex !== -1) {
79
- ast.program.body.splice(firstImportIndex + 1, 0, ...imports);
80
- } else {
81
- ast.program.body.unshift(...imports);
82
- }
83
-
84
- // Add i18n initialization code
85
- const i18nInitCode = needsBackwardCompatibility
86
- ? `// Before Grafana version 12.1.0 the plugin is responsible for loading translation resources
87
- // In Grafana version 12.1.0 and later Grafana is responsible for loading translation resources
88
- const loaders = semver.lt(config?.buildInfo?.version, '12.1.0') ? [loadResources] : [];
89
-
90
- await initPluginTranslations(pluginJson.id, loaders);`
91
- : `await initPluginTranslations(pluginJson.id);`;
92
-
93
- // Parse the initialization code and insert it at the top level (after imports)
94
- const initAst = recast.parse(i18nInitCode, {
95
- parser: babelParser,
96
- });
97
-
98
- // Find the last import index
99
- const lastImportIndex = ast.program.body.findLastIndex((node: any) => node.type === 'ImportDeclaration');
100
- if (lastImportIndex !== -1) {
101
- ast.program.body.splice(lastImportIndex + 1, 0, ...initAst.program.body);
102
- } else {
103
- ast.program.body.unshift(...initAst.program.body);
104
- }
105
-
106
- const output = recast.print(ast, {
107
- tabWidth: 2,
108
- trailingComma: true,
109
- lineTerminator: '\n',
110
- }).code;
111
-
112
- context.updateFile(moduleTsPath, output);
113
- additionsDebug(`Updated ${moduleTsPath} with i18n initialization`);
114
- } catch (error) {
115
- additionsDebug('Error updating module file:', error);
116
- }
117
- }
118
-
119
- export function createLoadResourcesFile(context: Context): void {
120
- const loadResourcesPath = 'src/loadResources.ts';
121
-
122
- // Defensive: skip if already exists
123
- if (context.doesFileExist(loadResourcesPath)) {
124
- additionsDebug('loadResources.ts already exists, skipping');
125
- return;
126
- }
127
-
128
- const pluginJsonRaw = context.getFile('src/plugin.json');
129
- if (!pluginJsonRaw) {
130
- additionsDebug('Cannot create loadResources.ts without plugin.json');
131
- return;
132
- }
133
-
134
- const loadResourcesContent = `import { LANGUAGES, ResourceLoader, Resources } from '@grafana/i18n';
135
- import pluginJson from 'plugin.json';
136
-
137
- const resources = LANGUAGES.reduce<Record<string, () => Promise<{ default: Resources }>>>((acc, lang) => {
138
- acc[lang.code] = async () => await import(\`./locales/\${lang.code}/\${pluginJson.id}.json\`);
139
- return acc;
140
- }, {});
141
-
142
- export const loadResources: ResourceLoader = async (resolvedLanguage: string) => {
143
- try {
144
- const translation = await resources[resolvedLanguage]();
145
- return translation.default;
146
- } catch (error) {
147
- // This makes sure that the plugin doesn't crash when the resolved language in Grafana isn't supported by the plugin
148
- console.error(\`The plugin '\${pluginJson.id}' doesn't support the language '\${resolvedLanguage}'\`, error);
149
- return {};
150
- }
151
- };
152
- `;
153
-
154
- context.addFile(loadResourcesPath, loadResourcesContent);
155
- additionsDebug('Created src/loadResources.ts for backward compatibility');
156
- }
@@ -1,139 +0,0 @@
1
- import { coerce, gte } from 'semver';
2
- import { parseDocument, stringify } from 'yaml';
3
-
4
- import type { Context } from '../../../context.js';
5
- import { additionsDebug } from '../../../utils.js';
6
-
7
- export function updateDockerCompose(context: Context): void {
8
- if (!context.doesFileExist('docker-compose.yaml')) {
9
- additionsDebug('docker-compose.yaml not found, skipping');
10
- return;
11
- }
12
-
13
- const composeContent = context.getFile('docker-compose.yaml');
14
- if (!composeContent) {
15
- return;
16
- }
17
-
18
- try {
19
- const composeDoc = parseDocument(composeContent);
20
- const currentEnv = composeDoc.getIn(['services', 'grafana', 'environment']);
21
-
22
- if (!currentEnv) {
23
- additionsDebug('No environment section found in docker-compose.yaml, skipping');
24
- return;
25
- }
26
-
27
- // Check if the feature toggle is already set
28
- if (typeof currentEnv === 'object') {
29
- const envMap = currentEnv as any;
30
- const toggleValue = envMap.get('GF_FEATURE_TOGGLES_ENABLE');
31
-
32
- if (toggleValue) {
33
- const toggleStr = toggleValue.toString();
34
- if (toggleStr.includes('localizationForPlugins')) {
35
- additionsDebug('localizationForPlugins already in GF_FEATURE_TOGGLES_ENABLE');
36
- return;
37
- }
38
- // Append to existing feature toggles
39
- composeDoc.setIn(
40
- ['services', 'grafana', 'environment', 'GF_FEATURE_TOGGLES_ENABLE'],
41
- `${toggleStr},localizationForPlugins`
42
- );
43
- } else {
44
- // Set new feature toggle
45
- composeDoc.setIn(['services', 'grafana', 'environment', 'GF_FEATURE_TOGGLES_ENABLE'], 'localizationForPlugins');
46
- }
47
-
48
- context.updateFile('docker-compose.yaml', stringify(composeDoc));
49
- additionsDebug('Updated docker-compose.yaml with localizationForPlugins feature toggle');
50
- }
51
- } catch (error) {
52
- additionsDebug('Error updating docker-compose.yaml:', error);
53
- }
54
- }
55
-
56
- export function updatePluginJson(context: Context, locales: string[], needsBackwardCompatibility: boolean): void {
57
- if (!context.doesFileExist('src/plugin.json')) {
58
- additionsDebug('src/plugin.json not found, skipping');
59
- return;
60
- }
61
-
62
- const pluginJsonRaw = context.getFile('src/plugin.json');
63
- if (!pluginJsonRaw) {
64
- return;
65
- }
66
-
67
- try {
68
- const pluginJson = JSON.parse(pluginJsonRaw);
69
-
70
- // Merge locales with existing languages (defensive: avoid duplicates)
71
- const existingLanguages = Array.isArray(pluginJson.languages) ? pluginJson.languages : [];
72
- const mergedLanguages = [...new Set([...existingLanguages, ...locales])];
73
- pluginJson.languages = mergedLanguages;
74
-
75
- // Update grafanaDependency based on backward compatibility needs
76
- if (!pluginJson.dependencies) {
77
- pluginJson.dependencies = {};
78
- }
79
-
80
- const currentGrafanaDep = pluginJson.dependencies.grafanaDependency || '>=11.0.0';
81
- const targetVersion = needsBackwardCompatibility ? '11.0.0' : '12.1.0';
82
- const minVersion = coerce(targetVersion);
83
- const currentVersion = coerce(currentGrafanaDep.replace(/^[><=]+/, ''));
84
-
85
- if (!currentVersion || !minVersion || !gte(currentVersion, minVersion)) {
86
- pluginJson.dependencies.grafanaDependency = `>=${targetVersion}`;
87
- additionsDebug(`Updated grafanaDependency to >=${targetVersion}`);
88
- }
89
-
90
- context.updateFile('src/plugin.json', JSON.stringify(pluginJson, null, 2));
91
- additionsDebug('Updated src/plugin.json with languages:', locales);
92
- } catch (error) {
93
- additionsDebug('Error updating src/plugin.json:', error);
94
- }
95
- }
96
-
97
- export function createI18nextConfig(context: Context): void {
98
- // Defensive: skip if already exists
99
- if (context.doesFileExist('i18next.config.ts')) {
100
- additionsDebug('i18next.config.ts already exists, skipping');
101
- return;
102
- }
103
-
104
- const pluginJsonRaw = context.getFile('src/plugin.json');
105
- if (!pluginJsonRaw) {
106
- additionsDebug('Cannot create i18next.config.ts without plugin.json');
107
- return;
108
- }
109
-
110
- try {
111
- const pluginJson = JSON.parse(pluginJsonRaw);
112
- const pluginId = pluginJson.id;
113
-
114
- if (!pluginId) {
115
- additionsDebug('No plugin ID found in plugin.json');
116
- return;
117
- }
118
-
119
- const i18nextConfig = `import { defineConfig } from 'i18next-cli';
120
- import pluginJson from './src/plugin.json';
121
-
122
- export default defineConfig({
123
- locales: pluginJson.languages,
124
- extract: {
125
- input: ['src/**/*.{tsx,ts}'],
126
- output: 'src/locales/{{language}}/{{namespace}}.json',
127
- defaultNS: pluginJson.id,
128
- functions: ['t', '*.t'],
129
- transComponents: ['Trans'],
130
- },
131
- });
132
- `;
133
-
134
- context.addFile('i18next.config.ts', i18nextConfig);
135
- additionsDebug('Created i18next.config.ts');
136
- } catch (error) {
137
- additionsDebug('Error creating i18next.config.ts:', error);
138
- }
139
- }