@grafana/create-plugin 6.2.0-canary.2233.18586197736.0 → 6.2.0-canary.2233.18644853669.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.
|
@@ -0,0 +1,433 @@
|
|
|
1
|
+
import * as recast from 'recast';
|
|
2
|
+
import { additionsDebug } from '../utils.js';
|
|
3
|
+
import { coerce, gte } from 'semver';
|
|
4
|
+
import { parseDocument, stringify } from 'yaml';
|
|
5
|
+
import { addDependenciesToPackageJson } from '../../migrations/utils.js';
|
|
6
|
+
|
|
7
|
+
const { builders } = recast.types;
|
|
8
|
+
function migrate(context, options = { locales: ["en-US"] }) {
|
|
9
|
+
const { locales } = options;
|
|
10
|
+
additionsDebug("Adding i18n support with locales:", locales);
|
|
11
|
+
if (isI18nConfigured(context)) {
|
|
12
|
+
additionsDebug("i18n already configured, skipping");
|
|
13
|
+
return context;
|
|
14
|
+
}
|
|
15
|
+
const needsBackwardCompatibility = checkNeedsBackwardCompatibility(context);
|
|
16
|
+
additionsDebug("Needs backward compatibility:", needsBackwardCompatibility);
|
|
17
|
+
if (!needsBackwardCompatibility) {
|
|
18
|
+
updateDockerCompose(context);
|
|
19
|
+
}
|
|
20
|
+
updatePluginJson(context, locales, needsBackwardCompatibility);
|
|
21
|
+
createLocaleFiles(context, locales);
|
|
22
|
+
addI18nDependency(context);
|
|
23
|
+
if (needsBackwardCompatibility) {
|
|
24
|
+
addSemverDependency(context);
|
|
25
|
+
}
|
|
26
|
+
updateEslintConfig(context);
|
|
27
|
+
addI18nInitialization(context, needsBackwardCompatibility);
|
|
28
|
+
if (needsBackwardCompatibility) {
|
|
29
|
+
createLoadResourcesFile(context);
|
|
30
|
+
}
|
|
31
|
+
addI18nextCli(context);
|
|
32
|
+
createI18nextConfig(context);
|
|
33
|
+
return context;
|
|
34
|
+
}
|
|
35
|
+
function isI18nConfigured(context) {
|
|
36
|
+
if (!context.doesFileExist("src/plugin.json")) {
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
const pluginJsonRaw = context.getFile("src/plugin.json");
|
|
40
|
+
if (!pluginJsonRaw) {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
try {
|
|
44
|
+
const pluginJson = JSON.parse(pluginJsonRaw);
|
|
45
|
+
if (pluginJson.languages && Array.isArray(pluginJson.languages) && pluginJson.languages.length > 0) {
|
|
46
|
+
additionsDebug("Found languages in plugin.json, i18n already configured");
|
|
47
|
+
return true;
|
|
48
|
+
}
|
|
49
|
+
} catch (error) {
|
|
50
|
+
additionsDebug("Error parsing plugin.json:", error);
|
|
51
|
+
}
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
function checkNeedsBackwardCompatibility(context) {
|
|
55
|
+
const pluginJsonRaw = context.getFile("src/plugin.json");
|
|
56
|
+
if (!pluginJsonRaw) {
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
try {
|
|
60
|
+
const pluginJson = JSON.parse(pluginJsonRaw);
|
|
61
|
+
const currentGrafanaDep = pluginJson.dependencies?.grafanaDependency || ">=11.0.0";
|
|
62
|
+
const minVersion = coerce("12.1.0");
|
|
63
|
+
const currentVersion = coerce(currentGrafanaDep.replace(/^[><=]+/, ""));
|
|
64
|
+
if (currentVersion && minVersion && gte(currentVersion, minVersion)) {
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
return true;
|
|
68
|
+
} catch (error) {
|
|
69
|
+
additionsDebug("Error checking backward compatibility:", error);
|
|
70
|
+
return true;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
function updateDockerCompose(context) {
|
|
74
|
+
if (!context.doesFileExist("docker-compose.yaml")) {
|
|
75
|
+
additionsDebug("docker-compose.yaml not found, skipping");
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
const composeContent = context.getFile("docker-compose.yaml");
|
|
79
|
+
if (!composeContent) {
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
try {
|
|
83
|
+
const composeDoc = parseDocument(composeContent);
|
|
84
|
+
const currentEnv = composeDoc.getIn(["services", "grafana", "environment"]);
|
|
85
|
+
if (!currentEnv) {
|
|
86
|
+
additionsDebug("No environment section found in docker-compose.yaml, skipping");
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
if (typeof currentEnv === "object") {
|
|
90
|
+
const envMap = currentEnv;
|
|
91
|
+
const toggleValue = envMap.get("GF_FEATURE_TOGGLES_ENABLE");
|
|
92
|
+
if (toggleValue) {
|
|
93
|
+
const toggleStr = toggleValue.toString();
|
|
94
|
+
if (toggleStr.includes("localizationForPlugins")) {
|
|
95
|
+
additionsDebug("localizationForPlugins already in GF_FEATURE_TOGGLES_ENABLE");
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
composeDoc.setIn(
|
|
99
|
+
["services", "grafana", "environment", "GF_FEATURE_TOGGLES_ENABLE"],
|
|
100
|
+
`${toggleStr},localizationForPlugins`
|
|
101
|
+
);
|
|
102
|
+
} else {
|
|
103
|
+
composeDoc.setIn(["services", "grafana", "environment", "GF_FEATURE_TOGGLES_ENABLE"], "localizationForPlugins");
|
|
104
|
+
}
|
|
105
|
+
context.updateFile("docker-compose.yaml", stringify(composeDoc));
|
|
106
|
+
additionsDebug("Updated docker-compose.yaml with localizationForPlugins feature toggle");
|
|
107
|
+
}
|
|
108
|
+
} catch (error) {
|
|
109
|
+
additionsDebug("Error updating docker-compose.yaml:", error);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
function updatePluginJson(context, locales, needsBackwardCompatibility) {
|
|
113
|
+
if (!context.doesFileExist("src/plugin.json")) {
|
|
114
|
+
additionsDebug("src/plugin.json not found, skipping");
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
const pluginJsonRaw = context.getFile("src/plugin.json");
|
|
118
|
+
if (!pluginJsonRaw) {
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
try {
|
|
122
|
+
const pluginJson = JSON.parse(pluginJsonRaw);
|
|
123
|
+
pluginJson.languages = locales;
|
|
124
|
+
if (!pluginJson.dependencies) {
|
|
125
|
+
pluginJson.dependencies = {};
|
|
126
|
+
}
|
|
127
|
+
const currentGrafanaDep = pluginJson.dependencies.grafanaDependency || ">=11.0.0";
|
|
128
|
+
const targetVersion = needsBackwardCompatibility ? "11.0.0" : "12.1.0";
|
|
129
|
+
const minVersion = coerce(targetVersion);
|
|
130
|
+
const currentVersion = coerce(currentGrafanaDep.replace(/^[><=]+/, ""));
|
|
131
|
+
if (!currentVersion || !minVersion || !gte(currentVersion, minVersion)) {
|
|
132
|
+
pluginJson.dependencies.grafanaDependency = `>=${targetVersion}`;
|
|
133
|
+
additionsDebug(`Updated grafanaDependency to >=${targetVersion}`);
|
|
134
|
+
}
|
|
135
|
+
context.updateFile("src/plugin.json", JSON.stringify(pluginJson, null, 2));
|
|
136
|
+
additionsDebug("Updated src/plugin.json with languages:", locales);
|
|
137
|
+
} catch (error) {
|
|
138
|
+
additionsDebug("Error updating src/plugin.json:", error);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
function createLocaleFiles(context, locales) {
|
|
142
|
+
const pluginJsonRaw = context.getFile("src/plugin.json");
|
|
143
|
+
if (!pluginJsonRaw) {
|
|
144
|
+
additionsDebug("Cannot create locale files without plugin.json");
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
try {
|
|
148
|
+
const pluginJson = JSON.parse(pluginJsonRaw);
|
|
149
|
+
const pluginId = pluginJson.id;
|
|
150
|
+
const pluginName = pluginJson.name || pluginId;
|
|
151
|
+
if (!pluginId) {
|
|
152
|
+
additionsDebug("No plugin ID found in plugin.json");
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
const exampleTranslations = {
|
|
156
|
+
components: {
|
|
157
|
+
exampleComponent: {
|
|
158
|
+
title: `${pluginName} component title`,
|
|
159
|
+
description: "Example description"
|
|
160
|
+
}
|
|
161
|
+
},
|
|
162
|
+
config: {
|
|
163
|
+
title: `${pluginName} configuration`,
|
|
164
|
+
apiUrl: {
|
|
165
|
+
label: "API URL",
|
|
166
|
+
placeholder: "Enter API URL"
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
for (const locale of locales) {
|
|
171
|
+
const localePath = `src/locales/${locale}/${pluginId}.json`;
|
|
172
|
+
if (!context.doesFileExist(localePath)) {
|
|
173
|
+
context.addFile(localePath, JSON.stringify(exampleTranslations, null, 2));
|
|
174
|
+
additionsDebug(`Created ${localePath} with example translations`);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
} catch (error) {
|
|
178
|
+
additionsDebug("Error creating locale files:", error);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
function addI18nDependency(context) {
|
|
182
|
+
addDependenciesToPackageJson(context, { "@grafana/i18n": "12.2.2" }, {});
|
|
183
|
+
additionsDebug("Added @grafana/i18n dependency version 12.2.2");
|
|
184
|
+
}
|
|
185
|
+
function addSemverDependency(context) {
|
|
186
|
+
addDependenciesToPackageJson(context, { semver: "^7.6.0" }, { "@types/semver": "^7.5.0" });
|
|
187
|
+
additionsDebug("Added semver dependency for backward compatibility");
|
|
188
|
+
}
|
|
189
|
+
function addI18nextCli(context) {
|
|
190
|
+
addDependenciesToPackageJson(context, {}, { "i18next-cli": "^1.1.1" });
|
|
191
|
+
const packageJsonRaw = context.getFile("package.json");
|
|
192
|
+
if (!packageJsonRaw) {
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
try {
|
|
196
|
+
const packageJson = JSON.parse(packageJsonRaw);
|
|
197
|
+
if (!packageJson.scripts) {
|
|
198
|
+
packageJson.scripts = {};
|
|
199
|
+
}
|
|
200
|
+
if (!packageJson.scripts["i18n-extract"]) {
|
|
201
|
+
packageJson.scripts["i18n-extract"] = "i18next-cli extract --sync-primary";
|
|
202
|
+
context.updateFile("package.json", JSON.stringify(packageJson, null, 2));
|
|
203
|
+
additionsDebug("Added i18n-extract script to package.json");
|
|
204
|
+
}
|
|
205
|
+
} catch (error) {
|
|
206
|
+
additionsDebug("Error adding i18n-extract script:", error);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
function updateEslintConfig(context) {
|
|
210
|
+
if (!context.doesFileExist("eslint.config.mjs")) {
|
|
211
|
+
additionsDebug("eslint.config.mjs not found, skipping");
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
const eslintConfigRaw = context.getFile("eslint.config.mjs");
|
|
215
|
+
if (!eslintConfigRaw) {
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
if (eslintConfigRaw.includes("@grafana/eslint-plugin-plugins")) {
|
|
219
|
+
additionsDebug("ESLint i18n rule already configured");
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
try {
|
|
223
|
+
const ast = recast.parse(eslintConfigRaw, {
|
|
224
|
+
parser: require("recast/parsers/babel-ts")
|
|
225
|
+
});
|
|
226
|
+
const imports = ast.program.body.filter((node) => node.type === "ImportDeclaration");
|
|
227
|
+
const lastImport = imports[imports.length - 1];
|
|
228
|
+
if (lastImport) {
|
|
229
|
+
const pluginImport = builders.importDeclaration(
|
|
230
|
+
[builders.importDefaultSpecifier(builders.identifier("grafanaPluginsPlugin"))],
|
|
231
|
+
builders.literal("@grafana/eslint-plugin-plugins")
|
|
232
|
+
);
|
|
233
|
+
const lastImportIndex = ast.program.body.indexOf(lastImport);
|
|
234
|
+
ast.program.body.splice(lastImportIndex + 1, 0, pluginImport);
|
|
235
|
+
}
|
|
236
|
+
recast.visit(ast, {
|
|
237
|
+
visitCallExpression(path) {
|
|
238
|
+
if (path.node.callee.name === "defineConfig" && path.node.arguments[0]?.type === "ArrayExpression") {
|
|
239
|
+
const configArray = path.node.arguments[0];
|
|
240
|
+
const pluginsConfig = builders.objectExpression([
|
|
241
|
+
builders.property(
|
|
242
|
+
"init",
|
|
243
|
+
builders.identifier("plugins"),
|
|
244
|
+
builders.objectExpression([
|
|
245
|
+
builders.property(
|
|
246
|
+
"init",
|
|
247
|
+
builders.literal("grafanaPlugins"),
|
|
248
|
+
builders.identifier("grafanaPluginsPlugin")
|
|
249
|
+
)
|
|
250
|
+
])
|
|
251
|
+
),
|
|
252
|
+
builders.property(
|
|
253
|
+
"init",
|
|
254
|
+
builders.identifier("rules"),
|
|
255
|
+
builders.objectExpression([
|
|
256
|
+
builders.property(
|
|
257
|
+
"init",
|
|
258
|
+
builders.literal("grafanaPlugins/no-untranslated-strings"),
|
|
259
|
+
builders.literal("warn")
|
|
260
|
+
)
|
|
261
|
+
])
|
|
262
|
+
)
|
|
263
|
+
]);
|
|
264
|
+
configArray.elements.push(pluginsConfig);
|
|
265
|
+
}
|
|
266
|
+
this.traverse(path);
|
|
267
|
+
}
|
|
268
|
+
});
|
|
269
|
+
const output = recast.print(ast, {
|
|
270
|
+
tabWidth: 2,
|
|
271
|
+
trailingComma: true,
|
|
272
|
+
lineTerminator: "\n"
|
|
273
|
+
}).code;
|
|
274
|
+
context.updateFile("eslint.config.mjs", output);
|
|
275
|
+
additionsDebug("Updated eslint.config.mjs with i18n linting rules");
|
|
276
|
+
} catch (error) {
|
|
277
|
+
additionsDebug("Error updating eslint.config.mjs:", error);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
function createI18nextConfig(context) {
|
|
281
|
+
if (context.doesFileExist("i18next.config.ts")) {
|
|
282
|
+
additionsDebug("i18next.config.ts already exists, skipping");
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
const pluginJsonRaw = context.getFile("src/plugin.json");
|
|
286
|
+
if (!pluginJsonRaw) {
|
|
287
|
+
additionsDebug("Cannot create i18next.config.ts without plugin.json");
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
try {
|
|
291
|
+
const pluginJson = JSON.parse(pluginJsonRaw);
|
|
292
|
+
const pluginId = pluginJson.id;
|
|
293
|
+
if (!pluginId) {
|
|
294
|
+
additionsDebug("No plugin ID found in plugin.json");
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
const i18nextConfig = `import { defineConfig } from 'i18next-cli';
|
|
298
|
+
import pluginJson from './src/plugin.json';
|
|
299
|
+
|
|
300
|
+
export default defineConfig({
|
|
301
|
+
locales: pluginJson.languages,
|
|
302
|
+
extract: {
|
|
303
|
+
input: ['src/**/*.{tsx,ts}'],
|
|
304
|
+
output: 'src/locales/{{language}}/{{namespace}}.json',
|
|
305
|
+
defaultNS: pluginJson.id,
|
|
306
|
+
functions: ['t', '*.t'],
|
|
307
|
+
transComponents: ['Trans'],
|
|
308
|
+
},
|
|
309
|
+
});
|
|
310
|
+
`;
|
|
311
|
+
context.addFile("i18next.config.ts", i18nextConfig);
|
|
312
|
+
additionsDebug("Created i18next.config.ts");
|
|
313
|
+
} catch (error) {
|
|
314
|
+
additionsDebug("Error creating i18next.config.ts:", error);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
function addI18nInitialization(context, needsBackwardCompatibility) {
|
|
318
|
+
const moduleTsPath = context.doesFileExist("src/module.ts") ? "src/module.ts" : context.doesFileExist("src/module.tsx") ? "src/module.tsx" : null;
|
|
319
|
+
if (!moduleTsPath) {
|
|
320
|
+
additionsDebug("No module.ts or module.tsx found, skipping i18n initialization");
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
const moduleContent = context.getFile(moduleTsPath);
|
|
324
|
+
if (!moduleContent) {
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
if (moduleContent.includes("initPluginTranslations")) {
|
|
328
|
+
additionsDebug("i18n already initialized in module file");
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
try {
|
|
332
|
+
const ast = recast.parse(moduleContent, {
|
|
333
|
+
parser: require("recast/parsers/babel-ts")
|
|
334
|
+
});
|
|
335
|
+
const imports = [];
|
|
336
|
+
imports.push(
|
|
337
|
+
builders.importDeclaration(
|
|
338
|
+
[builders.importSpecifier(builders.identifier("initPluginTranslations"))],
|
|
339
|
+
builders.literal("@grafana/i18n")
|
|
340
|
+
)
|
|
341
|
+
);
|
|
342
|
+
imports.push(
|
|
343
|
+
builders.importDeclaration(
|
|
344
|
+
[builders.importDefaultSpecifier(builders.identifier("pluginJson"))],
|
|
345
|
+
builders.literal("plugin.json")
|
|
346
|
+
)
|
|
347
|
+
);
|
|
348
|
+
if (needsBackwardCompatibility) {
|
|
349
|
+
imports.push(
|
|
350
|
+
builders.importDeclaration(
|
|
351
|
+
[builders.importSpecifier(builders.identifier("config"))],
|
|
352
|
+
builders.literal("@grafana/runtime")
|
|
353
|
+
)
|
|
354
|
+
);
|
|
355
|
+
imports.push(
|
|
356
|
+
builders.importDeclaration(
|
|
357
|
+
[builders.importDefaultSpecifier(builders.identifier("semver"))],
|
|
358
|
+
builders.literal("semver")
|
|
359
|
+
)
|
|
360
|
+
);
|
|
361
|
+
imports.push(
|
|
362
|
+
builders.importDeclaration(
|
|
363
|
+
[builders.importSpecifier(builders.identifier("loadResources"))],
|
|
364
|
+
builders.literal("./loadResources")
|
|
365
|
+
)
|
|
366
|
+
);
|
|
367
|
+
}
|
|
368
|
+
const firstImportIndex = ast.program.body.findIndex((node) => node.type === "ImportDeclaration");
|
|
369
|
+
if (firstImportIndex !== -1) {
|
|
370
|
+
ast.program.body.splice(firstImportIndex + 1, 0, ...imports);
|
|
371
|
+
} else {
|
|
372
|
+
ast.program.body.unshift(...imports);
|
|
373
|
+
}
|
|
374
|
+
const i18nInitCode = needsBackwardCompatibility ? `// Before Grafana version 12.1.0 the plugin is responsible for loading translation resources
|
|
375
|
+
// In Grafana version 12.1.0 and later Grafana is responsible for loading translation resources
|
|
376
|
+
const loaders = semver.lt(config?.buildInfo?.version, '12.1.0') ? [loadResources] : [];
|
|
377
|
+
|
|
378
|
+
await initPluginTranslations(pluginJson.id, loaders);` : `await initPluginTranslations(pluginJson.id);`;
|
|
379
|
+
const initAst = recast.parse(i18nInitCode, {
|
|
380
|
+
parser: require("recast/parsers/babel-ts")
|
|
381
|
+
});
|
|
382
|
+
const lastImportIndex = ast.program.body.findLastIndex((node) => node.type === "ImportDeclaration");
|
|
383
|
+
if (lastImportIndex !== -1) {
|
|
384
|
+
ast.program.body.splice(lastImportIndex + 1, 0, ...initAst.program.body);
|
|
385
|
+
} else {
|
|
386
|
+
ast.program.body.unshift(...initAst.program.body);
|
|
387
|
+
}
|
|
388
|
+
const output = recast.print(ast, {
|
|
389
|
+
tabWidth: 2,
|
|
390
|
+
trailingComma: true,
|
|
391
|
+
lineTerminator: "\n"
|
|
392
|
+
}).code;
|
|
393
|
+
context.updateFile(moduleTsPath, output);
|
|
394
|
+
additionsDebug(`Updated ${moduleTsPath} with i18n initialization`);
|
|
395
|
+
} catch (error) {
|
|
396
|
+
additionsDebug("Error updating module file:", error);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
function createLoadResourcesFile(context) {
|
|
400
|
+
const loadResourcesPath = "src/loadResources.ts";
|
|
401
|
+
if (context.doesFileExist(loadResourcesPath)) {
|
|
402
|
+
additionsDebug("loadResources.ts already exists, skipping");
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
const pluginJsonRaw = context.getFile("src/plugin.json");
|
|
406
|
+
if (!pluginJsonRaw) {
|
|
407
|
+
additionsDebug("Cannot create loadResources.ts without plugin.json");
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
const loadResourcesContent = `import { LANGUAGES, ResourceLoader, Resources } from '@grafana/i18n';
|
|
411
|
+
import pluginJson from 'plugin.json';
|
|
412
|
+
|
|
413
|
+
const resources = LANGUAGES.reduce<Record<string, () => Promise<{ default: Resources }>>>((acc, lang) => {
|
|
414
|
+
acc[lang.code] = async () => await import(\`./locales/\${lang.code}/\${pluginJson.id}.json\`);
|
|
415
|
+
return acc;
|
|
416
|
+
}, {});
|
|
417
|
+
|
|
418
|
+
export const loadResources: ResourceLoader = async (resolvedLanguage: string) => {
|
|
419
|
+
try {
|
|
420
|
+
const translation = await resources[resolvedLanguage]();
|
|
421
|
+
return translation.default;
|
|
422
|
+
} catch (error) {
|
|
423
|
+
// This makes sure that the plugin doesn't crash when the resolved language in Grafana isn't supported by the plugin
|
|
424
|
+
console.error(\`The plugin '\${pluginJson.id}' doesn't support the language '\${resolvedLanguage}'\`, error);
|
|
425
|
+
return {};
|
|
426
|
+
}
|
|
427
|
+
};
|
|
428
|
+
`;
|
|
429
|
+
context.addFile(loadResourcesPath, loadResourcesContent);
|
|
430
|
+
additionsDebug("Created src/loadResources.ts for backward compatibility");
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
export { migrate as default };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@grafana/create-plugin",
|
|
3
|
-
"version": "6.2.0-canary.2233.
|
|
3
|
+
"version": "6.2.0-canary.2233.18644853669.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": "4eb067f4f28b42ef18426827a1443073a97c3efd"
|
|
65
65
|
}
|
|
@@ -34,10 +34,10 @@ describe('add-i18n', () => {
|
|
|
34
34
|
await expect(migrateWithOptions).toBeIdempotent(context);
|
|
35
35
|
});
|
|
36
36
|
|
|
37
|
-
it('should add i18n support with a single locale', () => {
|
|
37
|
+
it('should add i18n support with a single locale (backward compatibility for Grafana < 12.1.0)', () => {
|
|
38
38
|
const context = new Context('/virtual');
|
|
39
39
|
|
|
40
|
-
// Set up a minimal plugin structure
|
|
40
|
+
// Set up a minimal plugin structure with Grafana 11.0.0 (needs backward compatibility)
|
|
41
41
|
context.addFile(
|
|
42
42
|
'src/plugin.json',
|
|
43
43
|
JSON.stringify({
|
|
@@ -71,26 +71,38 @@ describe('add-i18n', () => {
|
|
|
71
71
|
// Check plugin.json was updated
|
|
72
72
|
const pluginJson = JSON.parse(result.getFile('src/plugin.json') || '{}');
|
|
73
73
|
expect(pluginJson.languages).toEqual(['en-US']);
|
|
74
|
-
|
|
74
|
+
// Should stay at 11.0.0 for backward compatibility
|
|
75
|
+
expect(pluginJson.dependencies.grafanaDependency).toBe('>=11.0.0');
|
|
75
76
|
|
|
76
|
-
// Check locale file was created
|
|
77
|
+
// Check locale file was created with example translations
|
|
77
78
|
expect(result.doesFileExist('src/locales/en-US/test-plugin.json')).toBe(true);
|
|
78
79
|
const localeContent = result.getFile('src/locales/en-US/test-plugin.json');
|
|
79
|
-
|
|
80
|
+
const localeData = JSON.parse(localeContent || '{}');
|
|
81
|
+
expect(localeData).toHaveProperty('components');
|
|
82
|
+
expect(localeData).toHaveProperty('config');
|
|
80
83
|
|
|
81
84
|
// Check package.json was updated with dependencies
|
|
82
85
|
const packageJson = JSON.parse(result.getFile('package.json') || '{}');
|
|
83
|
-
expect(packageJson.dependencies['@grafana/i18n']).
|
|
86
|
+
expect(packageJson.dependencies['@grafana/i18n']).toBe('12.2.2');
|
|
87
|
+
expect(packageJson.dependencies['semver']).toBe('^7.6.0');
|
|
88
|
+
expect(packageJson.devDependencies['@types/semver']).toBe('^7.5.0');
|
|
84
89
|
expect(packageJson.devDependencies['i18next-cli']).toBeDefined();
|
|
85
90
|
expect(packageJson.scripts['i18n-extract']).toBe('i18next-cli extract --sync-primary');
|
|
86
91
|
|
|
87
|
-
// Check docker-compose.yaml was updated
|
|
92
|
+
// Check docker-compose.yaml was NOT updated (backward compat doesn't add feature toggle)
|
|
88
93
|
const dockerCompose = result.getFile('docker-compose.yaml');
|
|
89
|
-
expect(dockerCompose).toContain('localizationForPlugins');
|
|
94
|
+
expect(dockerCompose).not.toContain('localizationForPlugins');
|
|
90
95
|
|
|
91
|
-
// Check module.ts was updated
|
|
96
|
+
// Check module.ts was updated with backward compatibility code
|
|
92
97
|
const moduleTs = result.getFile('src/module.ts');
|
|
93
|
-
expect(moduleTs).toContain('
|
|
98
|
+
expect(moduleTs).toContain('initPluginTranslations');
|
|
99
|
+
expect(moduleTs).toContain('semver');
|
|
100
|
+
expect(moduleTs).toContain('loadResources');
|
|
101
|
+
|
|
102
|
+
// Check loadResources.ts was created for backward compatibility
|
|
103
|
+
expect(result.doesFileExist('src/loadResources.ts')).toBe(true);
|
|
104
|
+
const loadResources = result.getFile('src/loadResources.ts');
|
|
105
|
+
expect(loadResources).toContain('ResourceLoader');
|
|
94
106
|
|
|
95
107
|
// Check i18next.config.ts was created
|
|
96
108
|
expect(result.doesFileExist('i18next.config.ts')).toBe(true);
|
|
@@ -185,7 +197,7 @@ describe('add-i18n', () => {
|
|
|
185
197
|
expect(finalChanges).toBe(initialChanges);
|
|
186
198
|
});
|
|
187
199
|
|
|
188
|
-
it('should handle existing feature toggles in docker-compose.yaml', () => {
|
|
200
|
+
it('should handle existing feature toggles in docker-compose.yaml (Grafana >= 12.1.0)', () => {
|
|
189
201
|
const context = new Context('/virtual');
|
|
190
202
|
|
|
191
203
|
context.addFile(
|
|
@@ -195,7 +207,7 @@ describe('add-i18n', () => {
|
|
|
195
207
|
type: 'panel',
|
|
196
208
|
name: 'Test Plugin',
|
|
197
209
|
dependencies: {
|
|
198
|
-
grafanaDependency: '>=
|
|
210
|
+
grafanaDependency: '>=12.1.0',
|
|
199
211
|
},
|
|
200
212
|
})
|
|
201
213
|
);
|
|
@@ -23,28 +23,44 @@ export default function migrate(context: Context, options: I18nOptions = { local
|
|
|
23
23
|
return context;
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
-
//
|
|
27
|
-
|
|
26
|
+
// Determine if we need backward compatibility (Grafana < 12.1.0)
|
|
27
|
+
const needsBackwardCompatibility = checkNeedsBackwardCompatibility(context);
|
|
28
|
+
additionsDebug('Needs backward compatibility:', needsBackwardCompatibility);
|
|
29
|
+
|
|
30
|
+
// 1. Update docker-compose.yaml with feature toggle (only if >= 12.1.0)
|
|
31
|
+
if (!needsBackwardCompatibility) {
|
|
32
|
+
updateDockerCompose(context);
|
|
33
|
+
}
|
|
28
34
|
|
|
29
35
|
// 2. Update plugin.json with languages and grafanaDependency
|
|
30
|
-
updatePluginJson(context, locales);
|
|
36
|
+
updatePluginJson(context, locales, needsBackwardCompatibility);
|
|
31
37
|
|
|
32
|
-
// 3. Create locale folders and files
|
|
38
|
+
// 3. Create locale folders and files with example translations
|
|
33
39
|
createLocaleFiles(context, locales);
|
|
34
40
|
|
|
35
41
|
// 4. Add @grafana/i18n dependency
|
|
36
42
|
addI18nDependency(context);
|
|
37
43
|
|
|
38
|
-
// 5.
|
|
44
|
+
// 5. Add semver dependency for backward compatibility
|
|
45
|
+
if (needsBackwardCompatibility) {
|
|
46
|
+
addSemverDependency(context);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// 6. Update eslint.config.mjs if needed
|
|
39
50
|
updateEslintConfig(context);
|
|
40
51
|
|
|
41
|
-
//
|
|
42
|
-
addI18nInitialization(context);
|
|
52
|
+
// 7. Add i18n initialization to module file
|
|
53
|
+
addI18nInitialization(context, needsBackwardCompatibility);
|
|
43
54
|
|
|
44
|
-
//
|
|
55
|
+
// 8. Create loadResources.ts for backward compatibility
|
|
56
|
+
if (needsBackwardCompatibility) {
|
|
57
|
+
createLoadResourcesFile(context);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// 9. Add i18next-cli as dev dependency and add script
|
|
45
61
|
addI18nextCli(context);
|
|
46
62
|
|
|
47
|
-
//
|
|
63
|
+
// 10. Create i18next.config.ts
|
|
48
64
|
createI18nextConfig(context);
|
|
49
65
|
|
|
50
66
|
return context;
|
|
@@ -74,6 +90,29 @@ function isI18nConfigured(context: Context): boolean {
|
|
|
74
90
|
return false;
|
|
75
91
|
}
|
|
76
92
|
|
|
93
|
+
function checkNeedsBackwardCompatibility(context: Context): boolean {
|
|
94
|
+
const pluginJsonRaw = context.getFile('src/plugin.json');
|
|
95
|
+
if (!pluginJsonRaw) {
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
try {
|
|
100
|
+
const pluginJson = JSON.parse(pluginJsonRaw);
|
|
101
|
+
const currentGrafanaDep = pluginJson.dependencies?.grafanaDependency || '>=11.0.0';
|
|
102
|
+
const minVersion = coerce('12.1.0');
|
|
103
|
+
const currentVersion = coerce(currentGrafanaDep.replace(/^[><=]+/, ''));
|
|
104
|
+
|
|
105
|
+
// If current version is less than 12.1.0, we need backward compatibility
|
|
106
|
+
if (currentVersion && minVersion && gte(currentVersion, minVersion)) {
|
|
107
|
+
return false; // Already >= 12.1.0, no backward compat needed
|
|
108
|
+
}
|
|
109
|
+
return true; // < 12.1.0, needs backward compat
|
|
110
|
+
} catch (error) {
|
|
111
|
+
additionsDebug('Error checking backward compatibility:', error);
|
|
112
|
+
return true; // Default to backward compat on error
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
77
116
|
function updateDockerCompose(context: Context): void {
|
|
78
117
|
if (!context.doesFileExist('docker-compose.yaml')) {
|
|
79
118
|
additionsDebug('docker-compose.yaml not found, skipping');
|
|
@@ -123,7 +162,7 @@ function updateDockerCompose(context: Context): void {
|
|
|
123
162
|
}
|
|
124
163
|
}
|
|
125
164
|
|
|
126
|
-
function updatePluginJson(context: Context, locales: string[]): void {
|
|
165
|
+
function updatePluginJson(context: Context, locales: string[], needsBackwardCompatibility: boolean): void {
|
|
127
166
|
if (!context.doesFileExist('src/plugin.json')) {
|
|
128
167
|
additionsDebug('src/plugin.json not found, skipping');
|
|
129
168
|
return;
|
|
@@ -140,18 +179,19 @@ function updatePluginJson(context: Context, locales: string[]): void {
|
|
|
140
179
|
// Add languages array
|
|
141
180
|
pluginJson.languages = locales;
|
|
142
181
|
|
|
143
|
-
//
|
|
182
|
+
// Update grafanaDependency based on backward compatibility needs
|
|
144
183
|
if (!pluginJson.dependencies) {
|
|
145
184
|
pluginJson.dependencies = {};
|
|
146
185
|
}
|
|
147
186
|
|
|
148
187
|
const currentGrafanaDep = pluginJson.dependencies.grafanaDependency || '>=11.0.0';
|
|
149
|
-
const
|
|
188
|
+
const targetVersion = needsBackwardCompatibility ? '11.0.0' : '12.1.0';
|
|
189
|
+
const minVersion = coerce(targetVersion);
|
|
150
190
|
const currentVersion = coerce(currentGrafanaDep.replace(/^[><=]+/, ''));
|
|
151
191
|
|
|
152
192
|
if (!currentVersion || !minVersion || !gte(currentVersion, minVersion)) {
|
|
153
|
-
pluginJson.dependencies.grafanaDependency =
|
|
154
|
-
additionsDebug(
|
|
193
|
+
pluginJson.dependencies.grafanaDependency = `>=${targetVersion}`;
|
|
194
|
+
additionsDebug(`Updated grafanaDependency to >=${targetVersion}`);
|
|
155
195
|
}
|
|
156
196
|
|
|
157
197
|
context.updateFile('src/plugin.json', JSON.stringify(pluginJson, null, 2));
|
|
@@ -172,19 +212,37 @@ function createLocaleFiles(context: Context, locales: string[]): void {
|
|
|
172
212
|
try {
|
|
173
213
|
const pluginJson = JSON.parse(pluginJsonRaw);
|
|
174
214
|
const pluginId = pluginJson.id;
|
|
215
|
+
const pluginName = pluginJson.name || pluginId;
|
|
175
216
|
|
|
176
217
|
if (!pluginId) {
|
|
177
218
|
additionsDebug('No plugin ID found in plugin.json');
|
|
178
219
|
return;
|
|
179
220
|
}
|
|
180
221
|
|
|
222
|
+
// Create example translation structure
|
|
223
|
+
const exampleTranslations = {
|
|
224
|
+
components: {
|
|
225
|
+
exampleComponent: {
|
|
226
|
+
title: `${pluginName} component title`,
|
|
227
|
+
description: 'Example description',
|
|
228
|
+
},
|
|
229
|
+
},
|
|
230
|
+
config: {
|
|
231
|
+
title: `${pluginName} configuration`,
|
|
232
|
+
apiUrl: {
|
|
233
|
+
label: 'API URL',
|
|
234
|
+
placeholder: 'Enter API URL',
|
|
235
|
+
},
|
|
236
|
+
},
|
|
237
|
+
};
|
|
238
|
+
|
|
181
239
|
// Create locale files for each locale
|
|
182
240
|
for (const locale of locales) {
|
|
183
241
|
const localePath = `src/locales/${locale}/${pluginId}.json`;
|
|
184
242
|
|
|
185
243
|
if (!context.doesFileExist(localePath)) {
|
|
186
|
-
context.addFile(localePath, JSON.stringify(
|
|
187
|
-
additionsDebug(`Created ${localePath}`);
|
|
244
|
+
context.addFile(localePath, JSON.stringify(exampleTranslations, null, 2));
|
|
245
|
+
additionsDebug(`Created ${localePath} with example translations`);
|
|
188
246
|
}
|
|
189
247
|
}
|
|
190
248
|
} catch (error) {
|
|
@@ -193,8 +251,14 @@ function createLocaleFiles(context: Context, locales: string[]): void {
|
|
|
193
251
|
}
|
|
194
252
|
|
|
195
253
|
function addI18nDependency(context: Context): void {
|
|
196
|
-
addDependenciesToPackageJson(context, { '@grafana/i18n': '
|
|
197
|
-
additionsDebug('Added @grafana/i18n dependency');
|
|
254
|
+
addDependenciesToPackageJson(context, { '@grafana/i18n': '12.2.2' }, {});
|
|
255
|
+
additionsDebug('Added @grafana/i18n dependency version 12.2.2');
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function addSemverDependency(context: Context): void {
|
|
259
|
+
// Add semver as regular dependency and @types/semver as dev dependency for backward compatibility
|
|
260
|
+
addDependenciesToPackageJson(context, { semver: '^7.6.0' }, { '@types/semver': '^7.5.0' });
|
|
261
|
+
additionsDebug('Added semver dependency for backward compatibility');
|
|
198
262
|
}
|
|
199
263
|
|
|
200
264
|
function addI18nextCli(context: Context): void {
|
|
@@ -355,7 +419,7 @@ export default defineConfig({
|
|
|
355
419
|
}
|
|
356
420
|
}
|
|
357
421
|
|
|
358
|
-
function addI18nInitialization(context: Context): void {
|
|
422
|
+
function addI18nInitialization(context: Context, needsBackwardCompatibility: boolean): void {
|
|
359
423
|
// Find module.ts or module.tsx
|
|
360
424
|
const moduleTsPath = context.doesFileExist('src/module.ts')
|
|
361
425
|
? 'src/module.ts'
|
|
@@ -374,7 +438,7 @@ function addI18nInitialization(context: Context): void {
|
|
|
374
438
|
}
|
|
375
439
|
|
|
376
440
|
// Check if i18n is already initialized
|
|
377
|
-
if (moduleContent.includes('
|
|
441
|
+
if (moduleContent.includes('initPluginTranslations')) {
|
|
378
442
|
additionsDebug('i18n already initialized in module file');
|
|
379
443
|
return;
|
|
380
444
|
}
|
|
@@ -384,18 +448,72 @@ function addI18nInitialization(context: Context): void {
|
|
|
384
448
|
parser: require('recast/parsers/babel-ts'),
|
|
385
449
|
});
|
|
386
450
|
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
451
|
+
const imports = [];
|
|
452
|
+
|
|
453
|
+
// Add necessary imports based on backward compatibility
|
|
454
|
+
imports.push(
|
|
455
|
+
builders.importDeclaration(
|
|
456
|
+
[builders.importSpecifier(builders.identifier('initPluginTranslations'))],
|
|
457
|
+
builders.literal('@grafana/i18n')
|
|
458
|
+
)
|
|
391
459
|
);
|
|
392
460
|
|
|
393
|
-
|
|
461
|
+
imports.push(
|
|
462
|
+
builders.importDeclaration(
|
|
463
|
+
[builders.importDefaultSpecifier(builders.identifier('pluginJson'))],
|
|
464
|
+
builders.literal('plugin.json')
|
|
465
|
+
)
|
|
466
|
+
);
|
|
467
|
+
|
|
468
|
+
if (needsBackwardCompatibility) {
|
|
469
|
+
imports.push(
|
|
470
|
+
builders.importDeclaration(
|
|
471
|
+
[builders.importSpecifier(builders.identifier('config'))],
|
|
472
|
+
builders.literal('@grafana/runtime')
|
|
473
|
+
)
|
|
474
|
+
);
|
|
475
|
+
imports.push(
|
|
476
|
+
builders.importDeclaration(
|
|
477
|
+
[builders.importDefaultSpecifier(builders.identifier('semver'))],
|
|
478
|
+
builders.literal('semver')
|
|
479
|
+
)
|
|
480
|
+
);
|
|
481
|
+
imports.push(
|
|
482
|
+
builders.importDeclaration(
|
|
483
|
+
[builders.importSpecifier(builders.identifier('loadResources'))],
|
|
484
|
+
builders.literal('./loadResources')
|
|
485
|
+
)
|
|
486
|
+
);
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
// Add imports after the first import statement
|
|
394
490
|
const firstImportIndex = ast.program.body.findIndex((node: any) => node.type === 'ImportDeclaration');
|
|
395
491
|
if (firstImportIndex !== -1) {
|
|
396
|
-
ast.program.body.splice(firstImportIndex + 1, 0,
|
|
492
|
+
ast.program.body.splice(firstImportIndex + 1, 0, ...imports);
|
|
493
|
+
} else {
|
|
494
|
+
ast.program.body.unshift(...imports);
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
// Add i18n initialization code
|
|
498
|
+
const i18nInitCode = needsBackwardCompatibility
|
|
499
|
+
? `// Before Grafana version 12.1.0 the plugin is responsible for loading translation resources
|
|
500
|
+
// In Grafana version 12.1.0 and later Grafana is responsible for loading translation resources
|
|
501
|
+
const loaders = semver.lt(config?.buildInfo?.version, '12.1.0') ? [loadResources] : [];
|
|
502
|
+
|
|
503
|
+
await initPluginTranslations(pluginJson.id, loaders);`
|
|
504
|
+
: `await initPluginTranslations(pluginJson.id);`;
|
|
505
|
+
|
|
506
|
+
// Parse the initialization code and insert it at the top level (after imports)
|
|
507
|
+
const initAst = recast.parse(i18nInitCode, {
|
|
508
|
+
parser: require('recast/parsers/babel-ts'),
|
|
509
|
+
});
|
|
510
|
+
|
|
511
|
+
// Find the last import index
|
|
512
|
+
const lastImportIndex = ast.program.body.findLastIndex((node: any) => node.type === 'ImportDeclaration');
|
|
513
|
+
if (lastImportIndex !== -1) {
|
|
514
|
+
ast.program.body.splice(lastImportIndex + 1, 0, ...initAst.program.body);
|
|
397
515
|
} else {
|
|
398
|
-
ast.program.body.unshift(
|
|
516
|
+
ast.program.body.unshift(...initAst.program.body);
|
|
399
517
|
}
|
|
400
518
|
|
|
401
519
|
const output = recast.print(ast, {
|
|
@@ -405,8 +523,46 @@ function addI18nInitialization(context: Context): void {
|
|
|
405
523
|
}).code;
|
|
406
524
|
|
|
407
525
|
context.updateFile(moduleTsPath, output);
|
|
408
|
-
additionsDebug(`Updated ${moduleTsPath} with i18n
|
|
526
|
+
additionsDebug(`Updated ${moduleTsPath} with i18n initialization`);
|
|
409
527
|
} catch (error) {
|
|
410
528
|
additionsDebug('Error updating module file:', error);
|
|
411
529
|
}
|
|
412
530
|
}
|
|
531
|
+
|
|
532
|
+
function createLoadResourcesFile(context: Context): void {
|
|
533
|
+
const loadResourcesPath = 'src/loadResources.ts';
|
|
534
|
+
|
|
535
|
+
if (context.doesFileExist(loadResourcesPath)) {
|
|
536
|
+
additionsDebug('loadResources.ts already exists, skipping');
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
const pluginJsonRaw = context.getFile('src/plugin.json');
|
|
541
|
+
if (!pluginJsonRaw) {
|
|
542
|
+
additionsDebug('Cannot create loadResources.ts without plugin.json');
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
const loadResourcesContent = `import { LANGUAGES, ResourceLoader, Resources } from '@grafana/i18n';
|
|
547
|
+
import pluginJson from 'plugin.json';
|
|
548
|
+
|
|
549
|
+
const resources = LANGUAGES.reduce<Record<string, () => Promise<{ default: Resources }>>>((acc, lang) => {
|
|
550
|
+
acc[lang.code] = async () => await import(\`./locales/\${lang.code}/\${pluginJson.id}.json\`);
|
|
551
|
+
return acc;
|
|
552
|
+
}, {});
|
|
553
|
+
|
|
554
|
+
export const loadResources: ResourceLoader = async (resolvedLanguage: string) => {
|
|
555
|
+
try {
|
|
556
|
+
const translation = await resources[resolvedLanguage]();
|
|
557
|
+
return translation.default;
|
|
558
|
+
} catch (error) {
|
|
559
|
+
// This makes sure that the plugin doesn't crash when the resolved language in Grafana isn't supported by the plugin
|
|
560
|
+
console.error(\`The plugin '\${pluginJson.id}' doesn't support the language '\${resolvedLanguage}'\`, error);
|
|
561
|
+
return {};
|
|
562
|
+
}
|
|
563
|
+
};
|
|
564
|
+
`;
|
|
565
|
+
|
|
566
|
+
context.addFile(loadResourcesPath, loadResourcesContent);
|
|
567
|
+
additionsDebug('Created src/loadResources.ts for backward compatibility');
|
|
568
|
+
}
|