@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.
@@ -0,0 +1,156 @@
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
+ }
@@ -0,0 +1,139 @@
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
+ }