@grafana/create-plugin 6.3.0-canary.2319.19627830170.0 → 6.3.0-canary.2320.19632326797.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.
- package/dist/codemods/additions/additions.js +5 -0
- package/dist/codemods/additions/scripts/i18n/code-generation.js +122 -0
- package/dist/codemods/additions/scripts/i18n/config-updates.js +113 -0
- package/dist/codemods/additions/scripts/i18n/index.js +49 -0
- package/dist/codemods/additions/scripts/i18n/tooling.js +119 -0
- package/dist/codemods/additions/scripts/i18n/utils.js +50 -0
- package/dist/codemods/utils.js +2 -2
- package/package.json +2 -2
- package/src/codemods/additions/additions.ts +5 -0
- package/src/codemods/additions/scripts/i18n/README.md +157 -0
- package/src/codemods/additions/scripts/i18n/code-generation.ts +156 -0
- package/src/codemods/additions/scripts/i18n/config-updates.ts +139 -0
- package/src/codemods/additions/scripts/i18n/index.test.ts +770 -0
- package/src/codemods/additions/scripts/i18n/index.ts +81 -0
- package/src/codemods/additions/scripts/i18n/tooling.ts +146 -0
- package/src/codemods/additions/scripts/i18n/utils.ts +60 -0
- package/templates/github/workflows/ci.yml +1 -1
|
@@ -3,6 +3,11 @@ var defaultAdditions = [
|
|
|
3
3
|
name: "example-addition",
|
|
4
4
|
description: "Adds an example addition to the plugin",
|
|
5
5
|
scriptPath: import.meta.resolve("./scripts/example-addition.js")
|
|
6
|
+
},
|
|
7
|
+
{
|
|
8
|
+
name: "i18n",
|
|
9
|
+
description: "Adds internationalization (i18n) support to the plugin",
|
|
10
|
+
scriptPath: import.meta.resolve("./scripts/i18n/index.js")
|
|
6
11
|
}
|
|
7
12
|
];
|
|
8
13
|
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import * as recast from 'recast';
|
|
2
|
+
import * as babelParser from 'recast/parsers/babel-ts.js';
|
|
3
|
+
import { additionsDebug } from '../../../utils.js';
|
|
4
|
+
|
|
5
|
+
const { builders } = recast.types;
|
|
6
|
+
function addI18nInitialization(context, needsBackwardCompatibility) {
|
|
7
|
+
const moduleTsPath = context.doesFileExist("src/module.ts") ? "src/module.ts" : context.doesFileExist("src/module.tsx") ? "src/module.tsx" : null;
|
|
8
|
+
if (!moduleTsPath) {
|
|
9
|
+
additionsDebug("No module.ts or module.tsx found, skipping i18n initialization");
|
|
10
|
+
return;
|
|
11
|
+
}
|
|
12
|
+
const moduleContent = context.getFile(moduleTsPath);
|
|
13
|
+
if (!moduleContent) {
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
if (moduleContent.includes("initPluginTranslations")) {
|
|
17
|
+
additionsDebug("i18n already initialized in module file");
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
try {
|
|
21
|
+
const ast = recast.parse(moduleContent, {
|
|
22
|
+
parser: babelParser
|
|
23
|
+
});
|
|
24
|
+
const imports = [];
|
|
25
|
+
imports.push(
|
|
26
|
+
builders.importDeclaration(
|
|
27
|
+
[builders.importSpecifier(builders.identifier("initPluginTranslations"))],
|
|
28
|
+
builders.literal("@grafana/i18n")
|
|
29
|
+
)
|
|
30
|
+
);
|
|
31
|
+
imports.push(
|
|
32
|
+
builders.importDeclaration(
|
|
33
|
+
[builders.importDefaultSpecifier(builders.identifier("pluginJson"))],
|
|
34
|
+
builders.literal("plugin.json")
|
|
35
|
+
)
|
|
36
|
+
);
|
|
37
|
+
if (needsBackwardCompatibility) {
|
|
38
|
+
imports.push(
|
|
39
|
+
builders.importDeclaration(
|
|
40
|
+
[builders.importSpecifier(builders.identifier("config"))],
|
|
41
|
+
builders.literal("@grafana/runtime")
|
|
42
|
+
)
|
|
43
|
+
);
|
|
44
|
+
imports.push(
|
|
45
|
+
builders.importDeclaration(
|
|
46
|
+
[builders.importDefaultSpecifier(builders.identifier("semver"))],
|
|
47
|
+
builders.literal("semver")
|
|
48
|
+
)
|
|
49
|
+
);
|
|
50
|
+
imports.push(
|
|
51
|
+
builders.importDeclaration(
|
|
52
|
+
[builders.importSpecifier(builders.identifier("loadResources"))],
|
|
53
|
+
builders.literal("./loadResources")
|
|
54
|
+
)
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
const firstImportIndex = ast.program.body.findIndex((node) => node.type === "ImportDeclaration");
|
|
58
|
+
if (firstImportIndex !== -1) {
|
|
59
|
+
ast.program.body.splice(firstImportIndex + 1, 0, ...imports);
|
|
60
|
+
} else {
|
|
61
|
+
ast.program.body.unshift(...imports);
|
|
62
|
+
}
|
|
63
|
+
const i18nInitCode = needsBackwardCompatibility ? `// Before Grafana version 12.1.0 the plugin is responsible for loading translation resources
|
|
64
|
+
// In Grafana version 12.1.0 and later Grafana is responsible for loading translation resources
|
|
65
|
+
const loaders = semver.lt(config?.buildInfo?.version, '12.1.0') ? [loadResources] : [];
|
|
66
|
+
|
|
67
|
+
await initPluginTranslations(pluginJson.id, loaders);` : `await initPluginTranslations(pluginJson.id);`;
|
|
68
|
+
const initAst = recast.parse(i18nInitCode, {
|
|
69
|
+
parser: babelParser
|
|
70
|
+
});
|
|
71
|
+
const lastImportIndex = ast.program.body.findLastIndex((node) => node.type === "ImportDeclaration");
|
|
72
|
+
if (lastImportIndex !== -1) {
|
|
73
|
+
ast.program.body.splice(lastImportIndex + 1, 0, ...initAst.program.body);
|
|
74
|
+
} else {
|
|
75
|
+
ast.program.body.unshift(...initAst.program.body);
|
|
76
|
+
}
|
|
77
|
+
const output = recast.print(ast, {
|
|
78
|
+
tabWidth: 2,
|
|
79
|
+
trailingComma: true,
|
|
80
|
+
lineTerminator: "\n"
|
|
81
|
+
}).code;
|
|
82
|
+
context.updateFile(moduleTsPath, output);
|
|
83
|
+
additionsDebug(`Updated ${moduleTsPath} with i18n initialization`);
|
|
84
|
+
} catch (error) {
|
|
85
|
+
additionsDebug("Error updating module file:", error);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
function createLoadResourcesFile(context) {
|
|
89
|
+
const loadResourcesPath = "src/loadResources.ts";
|
|
90
|
+
if (context.doesFileExist(loadResourcesPath)) {
|
|
91
|
+
additionsDebug("loadResources.ts already exists, skipping");
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
const pluginJsonRaw = context.getFile("src/plugin.json");
|
|
95
|
+
if (!pluginJsonRaw) {
|
|
96
|
+
additionsDebug("Cannot create loadResources.ts without plugin.json");
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
const loadResourcesContent = `import { LANGUAGES, ResourceLoader, Resources } from '@grafana/i18n';
|
|
100
|
+
import pluginJson from 'plugin.json';
|
|
101
|
+
|
|
102
|
+
const resources = LANGUAGES.reduce<Record<string, () => Promise<{ default: Resources }>>>((acc, lang) => {
|
|
103
|
+
acc[lang.code] = async () => await import(\`./locales/\${lang.code}/\${pluginJson.id}.json\`);
|
|
104
|
+
return acc;
|
|
105
|
+
}, {});
|
|
106
|
+
|
|
107
|
+
export const loadResources: ResourceLoader = async (resolvedLanguage: string) => {
|
|
108
|
+
try {
|
|
109
|
+
const translation = await resources[resolvedLanguage]();
|
|
110
|
+
return translation.default;
|
|
111
|
+
} catch (error) {
|
|
112
|
+
// This makes sure that the plugin doesn't crash when the resolved language in Grafana isn't supported by the plugin
|
|
113
|
+
console.error(\`The plugin '\${pluginJson.id}' doesn't support the language '\${resolvedLanguage}'\`, error);
|
|
114
|
+
return {};
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
`;
|
|
118
|
+
context.addFile(loadResourcesPath, loadResourcesContent);
|
|
119
|
+
additionsDebug("Created src/loadResources.ts for backward compatibility");
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export { addI18nInitialization, createLoadResourcesFile };
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { coerce, gte } from 'semver';
|
|
2
|
+
import { parseDocument, stringify } from 'yaml';
|
|
3
|
+
import { additionsDebug } from '../../../utils.js';
|
|
4
|
+
|
|
5
|
+
function updateDockerCompose(context) {
|
|
6
|
+
if (!context.doesFileExist("docker-compose.yaml")) {
|
|
7
|
+
additionsDebug("docker-compose.yaml not found, skipping");
|
|
8
|
+
return;
|
|
9
|
+
}
|
|
10
|
+
const composeContent = context.getFile("docker-compose.yaml");
|
|
11
|
+
if (!composeContent) {
|
|
12
|
+
return;
|
|
13
|
+
}
|
|
14
|
+
try {
|
|
15
|
+
const composeDoc = parseDocument(composeContent);
|
|
16
|
+
const currentEnv = composeDoc.getIn(["services", "grafana", "environment"]);
|
|
17
|
+
if (!currentEnv) {
|
|
18
|
+
additionsDebug("No environment section found in docker-compose.yaml, skipping");
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
if (typeof currentEnv === "object") {
|
|
22
|
+
const envMap = currentEnv;
|
|
23
|
+
const toggleValue = envMap.get("GF_FEATURE_TOGGLES_ENABLE");
|
|
24
|
+
if (toggleValue) {
|
|
25
|
+
const toggleStr = toggleValue.toString();
|
|
26
|
+
if (toggleStr.includes("localizationForPlugins")) {
|
|
27
|
+
additionsDebug("localizationForPlugins already in GF_FEATURE_TOGGLES_ENABLE");
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
composeDoc.setIn(
|
|
31
|
+
["services", "grafana", "environment", "GF_FEATURE_TOGGLES_ENABLE"],
|
|
32
|
+
`${toggleStr},localizationForPlugins`
|
|
33
|
+
);
|
|
34
|
+
} else {
|
|
35
|
+
composeDoc.setIn(["services", "grafana", "environment", "GF_FEATURE_TOGGLES_ENABLE"], "localizationForPlugins");
|
|
36
|
+
}
|
|
37
|
+
context.updateFile("docker-compose.yaml", stringify(composeDoc));
|
|
38
|
+
additionsDebug("Updated docker-compose.yaml with localizationForPlugins feature toggle");
|
|
39
|
+
}
|
|
40
|
+
} catch (error) {
|
|
41
|
+
additionsDebug("Error updating docker-compose.yaml:", error);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function updatePluginJson(context, locales, needsBackwardCompatibility) {
|
|
45
|
+
if (!context.doesFileExist("src/plugin.json")) {
|
|
46
|
+
additionsDebug("src/plugin.json not found, skipping");
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
const pluginJsonRaw = context.getFile("src/plugin.json");
|
|
50
|
+
if (!pluginJsonRaw) {
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
try {
|
|
54
|
+
const pluginJson = JSON.parse(pluginJsonRaw);
|
|
55
|
+
const existingLanguages = Array.isArray(pluginJson.languages) ? pluginJson.languages : [];
|
|
56
|
+
const mergedLanguages = [.../* @__PURE__ */ new Set([...existingLanguages, ...locales])];
|
|
57
|
+
pluginJson.languages = mergedLanguages;
|
|
58
|
+
if (!pluginJson.dependencies) {
|
|
59
|
+
pluginJson.dependencies = {};
|
|
60
|
+
}
|
|
61
|
+
const currentGrafanaDep = pluginJson.dependencies.grafanaDependency || ">=11.0.0";
|
|
62
|
+
const targetVersion = needsBackwardCompatibility ? "11.0.0" : "12.1.0";
|
|
63
|
+
const minVersion = coerce(targetVersion);
|
|
64
|
+
const currentVersion = coerce(currentGrafanaDep.replace(/^[><=]+/, ""));
|
|
65
|
+
if (!currentVersion || !minVersion || !gte(currentVersion, minVersion)) {
|
|
66
|
+
pluginJson.dependencies.grafanaDependency = `>=${targetVersion}`;
|
|
67
|
+
additionsDebug(`Updated grafanaDependency to >=${targetVersion}`);
|
|
68
|
+
}
|
|
69
|
+
context.updateFile("src/plugin.json", JSON.stringify(pluginJson, null, 2));
|
|
70
|
+
additionsDebug("Updated src/plugin.json with languages:", locales);
|
|
71
|
+
} catch (error) {
|
|
72
|
+
additionsDebug("Error updating src/plugin.json:", error);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function createI18nextConfig(context) {
|
|
76
|
+
if (context.doesFileExist("i18next.config.ts")) {
|
|
77
|
+
additionsDebug("i18next.config.ts already exists, skipping");
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
const pluginJsonRaw = context.getFile("src/plugin.json");
|
|
81
|
+
if (!pluginJsonRaw) {
|
|
82
|
+
additionsDebug("Cannot create i18next.config.ts without plugin.json");
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
try {
|
|
86
|
+
const pluginJson = JSON.parse(pluginJsonRaw);
|
|
87
|
+
const pluginId = pluginJson.id;
|
|
88
|
+
if (!pluginId) {
|
|
89
|
+
additionsDebug("No plugin ID found in plugin.json");
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
const i18nextConfig = `import { defineConfig } from 'i18next-cli';
|
|
93
|
+
import pluginJson from './src/plugin.json';
|
|
94
|
+
|
|
95
|
+
export default defineConfig({
|
|
96
|
+
locales: pluginJson.languages,
|
|
97
|
+
extract: {
|
|
98
|
+
input: ['src/**/*.{tsx,ts}'],
|
|
99
|
+
output: 'src/locales/{{language}}/{{namespace}}.json',
|
|
100
|
+
defaultNS: pluginJson.id,
|
|
101
|
+
functions: ['t', '*.t'],
|
|
102
|
+
transComponents: ['Trans'],
|
|
103
|
+
},
|
|
104
|
+
});
|
|
105
|
+
`;
|
|
106
|
+
context.addFile("i18next.config.ts", i18nextConfig);
|
|
107
|
+
additionsDebug("Created i18next.config.ts");
|
|
108
|
+
} catch (error) {
|
|
109
|
+
additionsDebug("Error creating i18next.config.ts:", error);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export { createI18nextConfig, updateDockerCompose, updatePluginJson };
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import * as v from 'valibot';
|
|
2
|
+
import { additionsDebug } from '../../../utils.js';
|
|
3
|
+
import { updateDockerCompose, updatePluginJson, createI18nextConfig } from './config-updates.js';
|
|
4
|
+
import { addI18nInitialization, createLoadResourcesFile } from './code-generation.js';
|
|
5
|
+
import { addI18nDependency, addSemverDependency, updateEslintConfig, addI18nextCli } from './tooling.js';
|
|
6
|
+
import { checkNeedsBackwardCompatibility, createLocaleFiles } from './utils.js';
|
|
7
|
+
|
|
8
|
+
const schema = v.object(
|
|
9
|
+
{
|
|
10
|
+
locales: v.pipe(
|
|
11
|
+
v.union([v.string(), v.array(v.string())]),
|
|
12
|
+
v.transform((input) => {
|
|
13
|
+
return typeof input === "string" ? input.split(",").map((s) => s.trim()) : input;
|
|
14
|
+
}),
|
|
15
|
+
v.array(
|
|
16
|
+
v.pipe(
|
|
17
|
+
v.string(),
|
|
18
|
+
v.regex(/^[a-z]{2}-[A-Z]{2}$/, "Locale must be in format xx-XX (e.g., en-US, es-ES, sv-SE)")
|
|
19
|
+
),
|
|
20
|
+
'Please provide a comma-separated list of all supported locales, e.g., "en-US,es-ES,sv-SE"'
|
|
21
|
+
),
|
|
22
|
+
v.minLength(1, 'Please provide a comma-separated list of all supported locales, e.g., "en-US,es-ES,sv-SE"')
|
|
23
|
+
)
|
|
24
|
+
},
|
|
25
|
+
'Please provide a comma-separated list of all supported locales, e.g., "en-US,es-ES,sv-SE"'
|
|
26
|
+
);
|
|
27
|
+
function i18nAddition(context, options) {
|
|
28
|
+
const { locales } = options;
|
|
29
|
+
additionsDebug("Adding i18n support with locales:", locales);
|
|
30
|
+
const needsBackwardCompatibility = checkNeedsBackwardCompatibility(context);
|
|
31
|
+
additionsDebug("Needs backward compatibility:", needsBackwardCompatibility);
|
|
32
|
+
updateDockerCompose(context);
|
|
33
|
+
updatePluginJson(context, locales, needsBackwardCompatibility);
|
|
34
|
+
createLocaleFiles(context, locales);
|
|
35
|
+
addI18nDependency(context);
|
|
36
|
+
if (needsBackwardCompatibility) {
|
|
37
|
+
addSemverDependency(context);
|
|
38
|
+
}
|
|
39
|
+
updateEslintConfig(context);
|
|
40
|
+
addI18nInitialization(context, needsBackwardCompatibility);
|
|
41
|
+
if (needsBackwardCompatibility) {
|
|
42
|
+
createLoadResourcesFile(context);
|
|
43
|
+
}
|
|
44
|
+
addI18nextCli(context);
|
|
45
|
+
createI18nextConfig(context);
|
|
46
|
+
return context;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export { i18nAddition as default, schema };
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import * as recast from 'recast';
|
|
2
|
+
import * as babelParser from 'recast/parsers/babel-ts.js';
|
|
3
|
+
import { addDependenciesToPackageJson, additionsDebug } from '../../../utils.js';
|
|
4
|
+
|
|
5
|
+
const { builders } = recast.types;
|
|
6
|
+
function addI18nDependency(context) {
|
|
7
|
+
addDependenciesToPackageJson(context, { "@grafana/i18n": "^12.2.2" }, {});
|
|
8
|
+
additionsDebug("Added @grafana/i18n dependency version ^12.2.2");
|
|
9
|
+
}
|
|
10
|
+
function addSemverDependency(context) {
|
|
11
|
+
addDependenciesToPackageJson(context, { semver: "^7.6.0" }, { "@types/semver": "^7.5.0" });
|
|
12
|
+
additionsDebug("Added semver dependency");
|
|
13
|
+
}
|
|
14
|
+
function addI18nextCli(context) {
|
|
15
|
+
addDependenciesToPackageJson(context, {}, { "i18next-cli": "^1.1.1" });
|
|
16
|
+
const packageJsonRaw = context.getFile("package.json");
|
|
17
|
+
if (!packageJsonRaw) {
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
try {
|
|
21
|
+
const packageJson = JSON.parse(packageJsonRaw);
|
|
22
|
+
if (!packageJson.scripts) {
|
|
23
|
+
packageJson.scripts = {};
|
|
24
|
+
}
|
|
25
|
+
if (!packageJson.scripts["i18n-extract"]) {
|
|
26
|
+
packageJson.scripts["i18n-extract"] = "i18next-cli extract --sync-primary";
|
|
27
|
+
context.updateFile("package.json", JSON.stringify(packageJson, null, 2));
|
|
28
|
+
additionsDebug("Added i18n-extract script to package.json");
|
|
29
|
+
} else {
|
|
30
|
+
additionsDebug("i18n-extract script already exists, skipping");
|
|
31
|
+
}
|
|
32
|
+
} catch (error) {
|
|
33
|
+
additionsDebug("Error adding i18n-extract script:", error);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
function updateEslintConfig(context) {
|
|
37
|
+
if (!context.doesFileExist("eslint.config.mjs")) {
|
|
38
|
+
additionsDebug("eslint.config.mjs not found, skipping");
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
const eslintConfigRaw = context.getFile("eslint.config.mjs");
|
|
42
|
+
if (!eslintConfigRaw) {
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
if (eslintConfigRaw.includes("@grafana/i18n/eslint-plugin")) {
|
|
46
|
+
additionsDebug("ESLint i18n rule already configured");
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
try {
|
|
50
|
+
const ast = recast.parse(eslintConfigRaw, {
|
|
51
|
+
parser: babelParser
|
|
52
|
+
});
|
|
53
|
+
const imports = ast.program.body.filter((node) => node.type === "ImportDeclaration");
|
|
54
|
+
const lastImport = imports[imports.length - 1];
|
|
55
|
+
if (lastImport) {
|
|
56
|
+
const pluginImport = builders.importDeclaration(
|
|
57
|
+
[builders.importDefaultSpecifier(builders.identifier("grafanaI18nPlugin"))],
|
|
58
|
+
builders.literal("@grafana/i18n/eslint-plugin")
|
|
59
|
+
);
|
|
60
|
+
const lastImportIndex = ast.program.body.indexOf(lastImport);
|
|
61
|
+
ast.program.body.splice(lastImportIndex + 1, 0, pluginImport);
|
|
62
|
+
}
|
|
63
|
+
recast.visit(ast, {
|
|
64
|
+
visitCallExpression(path) {
|
|
65
|
+
if (path.node.callee.name === "defineConfig" && path.node.arguments[0]?.type === "ArrayExpression") {
|
|
66
|
+
const configArray = path.node.arguments[0];
|
|
67
|
+
const i18nConfig = builders.objectExpression([
|
|
68
|
+
builders.property("init", builders.identifier("name"), builders.literal("grafana/i18n-rules")),
|
|
69
|
+
builders.property(
|
|
70
|
+
"init",
|
|
71
|
+
builders.identifier("plugins"),
|
|
72
|
+
builders.objectExpression([
|
|
73
|
+
builders.property("init", builders.literal("@grafana/i18n"), builders.identifier("grafanaI18nPlugin"))
|
|
74
|
+
])
|
|
75
|
+
),
|
|
76
|
+
builders.property(
|
|
77
|
+
"init",
|
|
78
|
+
builders.identifier("rules"),
|
|
79
|
+
builders.objectExpression([
|
|
80
|
+
builders.property(
|
|
81
|
+
"init",
|
|
82
|
+
builders.literal("@grafana/i18n/no-untranslated-strings"),
|
|
83
|
+
builders.arrayExpression([
|
|
84
|
+
builders.literal("error"),
|
|
85
|
+
builders.objectExpression([
|
|
86
|
+
builders.property(
|
|
87
|
+
"init",
|
|
88
|
+
builders.identifier("calleesToIgnore"),
|
|
89
|
+
builders.arrayExpression([builders.literal("^css$"), builders.literal("use[A-Z].*")])
|
|
90
|
+
)
|
|
91
|
+
])
|
|
92
|
+
])
|
|
93
|
+
),
|
|
94
|
+
builders.property(
|
|
95
|
+
"init",
|
|
96
|
+
builders.literal("@grafana/i18n/no-translation-top-level"),
|
|
97
|
+
builders.literal("error")
|
|
98
|
+
)
|
|
99
|
+
])
|
|
100
|
+
)
|
|
101
|
+
]);
|
|
102
|
+
configArray.elements.push(i18nConfig);
|
|
103
|
+
}
|
|
104
|
+
this.traverse(path);
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
const output = recast.print(ast, {
|
|
108
|
+
tabWidth: 2,
|
|
109
|
+
trailingComma: true,
|
|
110
|
+
lineTerminator: "\n"
|
|
111
|
+
}).code;
|
|
112
|
+
context.updateFile("eslint.config.mjs", output);
|
|
113
|
+
additionsDebug("Updated eslint.config.mjs with i18n linting rules");
|
|
114
|
+
} catch (error) {
|
|
115
|
+
additionsDebug("Error updating eslint.config.mjs:", error);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export { addI18nDependency, addI18nextCli, addSemverDependency, updateEslintConfig };
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { coerce, gte } from 'semver';
|
|
2
|
+
import { additionsDebug } from '../../../utils.js';
|
|
3
|
+
|
|
4
|
+
function checkNeedsBackwardCompatibility(context) {
|
|
5
|
+
const pluginJsonRaw = context.getFile("src/plugin.json");
|
|
6
|
+
if (!pluginJsonRaw) {
|
|
7
|
+
return false;
|
|
8
|
+
}
|
|
9
|
+
try {
|
|
10
|
+
const pluginJson = JSON.parse(pluginJsonRaw);
|
|
11
|
+
const currentGrafanaDep = pluginJson.dependencies?.grafanaDependency || ">=11.0.0";
|
|
12
|
+
const minVersion = coerce("12.1.0");
|
|
13
|
+
const currentVersion = coerce(currentGrafanaDep.replace(/^[><=]+/, ""));
|
|
14
|
+
if (currentVersion && minVersion && gte(currentVersion, minVersion)) {
|
|
15
|
+
return false;
|
|
16
|
+
}
|
|
17
|
+
return true;
|
|
18
|
+
} catch (error) {
|
|
19
|
+
additionsDebug("Error checking backward compatibility:", error);
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
function createLocaleFiles(context, locales) {
|
|
24
|
+
const pluginJsonRaw = context.getFile("src/plugin.json");
|
|
25
|
+
if (!pluginJsonRaw) {
|
|
26
|
+
additionsDebug("Cannot create locale files without plugin.json");
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
try {
|
|
30
|
+
const pluginJson = JSON.parse(pluginJsonRaw);
|
|
31
|
+
const pluginId = pluginJson.id;
|
|
32
|
+
if (!pluginId) {
|
|
33
|
+
additionsDebug("No plugin ID found in plugin.json");
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
for (const locale of locales) {
|
|
37
|
+
const localePath = `src/locales/${locale}/${pluginId}.json`;
|
|
38
|
+
if (!context.doesFileExist(localePath)) {
|
|
39
|
+
context.addFile(localePath, JSON.stringify({}, null, 2));
|
|
40
|
+
additionsDebug(`Created ${localePath}`);
|
|
41
|
+
} else {
|
|
42
|
+
additionsDebug(`${localePath} already exists, skipping`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
} catch (error) {
|
|
46
|
+
additionsDebug("Error creating locale files:", error);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export { checkNeedsBackwardCompatibility, createLocaleFiles };
|
package/dist/codemods/utils.js
CHANGED
|
@@ -205,6 +205,6 @@ function sortObjectByKeys(obj) {
|
|
|
205
205
|
return Object.keys(obj).sort().reduce((acc, key) => ({ ...acc, [key]: obj[key] }), {});
|
|
206
206
|
}
|
|
207
207
|
const migrationsDebug = debug.extend("migrations");
|
|
208
|
-
debug.extend("additions");
|
|
208
|
+
const additionsDebug = debug.extend("additions");
|
|
209
209
|
|
|
210
|
-
export { addDependenciesToPackageJson, flushChanges, formatFiles, installNPMDependencies, isVersionGreater, migrationsDebug, printChanges, readJsonFile, removeDependenciesFromPackageJson };
|
|
210
|
+
export { addDependenciesToPackageJson, additionsDebug, flushChanges, formatFiles, installNPMDependencies, isVersionGreater, migrationsDebug, printChanges, readJsonFile, removeDependenciesFromPackageJson };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@grafana/create-plugin",
|
|
3
|
-
"version": "6.3.0-canary.
|
|
3
|
+
"version": "6.3.0-canary.2320.19632326797.0",
|
|
4
4
|
"repository": {
|
|
5
5
|
"directory": "packages/create-plugin",
|
|
6
6
|
"url": "https://github.com/grafana/plugin-tools"
|
|
@@ -61,5 +61,5 @@
|
|
|
61
61
|
"engines": {
|
|
62
62
|
"node": ">=20"
|
|
63
63
|
},
|
|
64
|
-
"gitHead": "
|
|
64
|
+
"gitHead": "5b46b985dfd18a905e572b69ca71c8f5148a8043"
|
|
65
65
|
}
|
|
@@ -6,4 +6,9 @@ export default [
|
|
|
6
6
|
description: 'Adds an example addition to the plugin',
|
|
7
7
|
scriptPath: import.meta.resolve('./scripts/example-addition.js'),
|
|
8
8
|
},
|
|
9
|
+
{
|
|
10
|
+
name: 'i18n',
|
|
11
|
+
description: 'Adds internationalization (i18n) support to the plugin',
|
|
12
|
+
scriptPath: import.meta.resolve('./scripts/i18n/index.js'),
|
|
13
|
+
},
|
|
9
14
|
] satisfies Codemod[];
|
|
@@ -0,0 +1,157 @@
|
|
|
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)
|