-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Expand file tree
/
Copy pathplugin-mappings.ts
More file actions
479 lines (405 loc) · 14.1 KB
/
plugin-mappings.ts
File metadata and controls
479 lines (405 loc) · 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
import { workspaceRoot, type GeneratorsJson } from '@nx/devkit';
import { existsSync, lstatSync, readdirSync, readFileSync } from 'node:fs';
import { basename, extname, join } from 'node:path';
import frontMatter from 'front-matter';
import type { SidebarItem, SidebarSubItem } from '../../utils/sidebar.types';
/**
* Map of plugins names to their technology grouping
*/
export const pluginToTechnology: Record<string, string> = {
typescript: 'typescript',
js: 'typescript',
angular: 'angular',
'angular-rspack': 'angular',
'angular-rsbuild': 'angular',
'angular-rspack-compiler': 'angular',
react: 'react',
next: 'react',
remix: 'react',
'react-native': 'react',
expo: 'react',
vue: 'vue',
nuxt: 'vue',
node: 'node',
express: 'node',
nest: 'node',
java: 'java',
gradle: 'java',
maven: 'java',
dotnet: 'dotnet',
'module-federation': 'module-federation',
eslint: 'eslint',
'eslint-plugin': 'eslint',
oxlint: 'oxlint',
webpack: 'build-tools',
vite: 'build-tools',
rollup: 'build-tools',
esbuild: 'build-tools',
rspack: 'build-tools',
rsbuild: 'build-tools',
docker: 'build-tools',
cypress: 'test-tools',
jest: 'test-tools',
playwright: 'test-tools',
storybook: 'test-tools',
detox: 'test-tools',
vitest: 'test-tools',
};
/**
* Get technology category for a given plugin name
* @param pluginName The plugin name (e.g., 'react', 'next', 'webpack')
* @returns Technology category (e.g., 'react', 'build-tools') or 'other' if not found
*/
export function getTechnologyCategory(pluginName: string): string {
return pluginToTechnology[pluginName];
}
/**
* Get all plugins that belong to a specific technology category
* @param technologyCategory The technology category (e.g., 'react', 'build-tools')
* @returns Array of plugin names in that category
*/
export function getPluginsInTechnology(technologyCategory: string): string[] {
return Object.entries(pluginToTechnology)
.filter(([_, category]) => category === technologyCategory)
.map(([pluginName, _]) => pluginName);
}
/**
* Get all unique technology categories
* @returns Array of all technology category names
*/
export function getAllTechnologyCategories(): string[] {
return Array.from(new Set(Object.values(pluginToTechnology))).sort();
}
/**
* Get the flattened sidebar items for a given plugin's static guide content.
* Returns an array of sidebar items that can be spread into a custom group.
*
* @param plugin The plugin name (e.g., 'angular', 'react', 'next')
* @param technologyCategory Optional category override (e.g., 'react' for 'next')
*/
export function getTechnologyKBItems(
plugin: string,
technologyCategory?: string
): SidebarSubItem[] {
const remappedPluginName = pluginSpecialCasePluginRemapping(plugin);
const baseUrl =
technologyCategory && technologyCategory !== remappedPluginName
? `/technologies/${technologyCategory}/${remappedPluginName}`
: `/technologies/${remappedPluginName}`;
const contentDir = join(
workspaceRoot,
'astro-docs',
'src',
'content',
'docs',
baseUrl
);
// Get all static files for this plugin
const staticFiles = getStaticPluginFiles(contentDir);
// Filter out the Introduction item (already linked in Technologies & Tools section)
const filteredItems: SidebarItem[] = staticFiles.filter((file) => {
if (typeof file === 'string') return false;
return file.label !== 'Introduction';
});
// Flatten: hoist children of nested groups (e.g. "Guides" → its children)
const flatItems: SidebarItem[] = [];
for (const item of filteredItems) {
if (
typeof item === 'object' &&
'items' in item &&
Array.isArray((item as SidebarSubItem).items)
) {
flatItems.push(...(item as SidebarSubItem).items);
} else {
flatItems.push(item);
}
}
return flatItems as SidebarSubItem[];
}
/**
* Get the API reference sidebar items (Generators, Executors, Migrations) for a given plugin.
* Returns an array of link items that can be spread into a custom group.
*
* @param plugin The plugin name (e.g., 'angular', 'react', 'next')
* @param technologyCategory Optional category override (e.g., 'react' for 'next')
* @param labelPrefix Optional prefix for labels (e.g., 'Next.js' → 'Next.js Generators')
*/
export function getTechnologyAPIItems(
plugin: string,
technologyCategory?: string,
labelPrefix?: string
): SidebarSubItem[] {
const remappedPluginName = pluginSpecialCasePluginRemapping(plugin);
const baseUrl =
technologyCategory && technologyCategory !== remappedPluginName
? `/technologies/${technologyCategory}/${remappedPluginName}`
: `/technologies/${remappedPluginName}`;
const pluginPath = join(pluginBasePath, plugin);
const items: SidebarSubItem[] = [];
if (!existsSync(pluginPath) || !lstatSync(pluginPath).isDirectory()) {
return items;
}
const prefix = labelPrefix ? `${labelPrefix} ` : '';
if (hasValidConfig(pluginPath, 'generators')) {
items.push({
label: `${prefix}Generators`,
link: `${baseUrl}/generators`,
});
}
if (hasValidConfig(pluginPath, 'executors')) {
items.push({
label: `${prefix}Executors`,
link: `${baseUrl}/executors`,
});
}
if (hasValidConfig(pluginPath, 'migrations')) {
items.push({
label: `${prefix}Migrations`,
link: `${baseUrl}/migrations`,
});
}
return items;
}
const pluginBasePath = join(workspaceRoot, 'packages');
/**
* get all the linkable pages for a given plugin for the sidebar
*/
export function getPluginItems(
plugin: string,
technologyCategory?: string
): SidebarSubItem[] {
const items: SidebarItem[] = [];
const pluginPath = join(pluginBasePath, plugin);
const remappedPluginName = pluginSpecialCasePluginRemapping(plugin);
// NOTE: some docs are at the top level of a category, so the route needs to reflect that
const baseUrl =
technologyCategory && technologyCategory !== remappedPluginName
? `/technologies/${technologyCategory}/${remappedPluginName}`
: `/technologies/${remappedPluginName}`;
if (existsSync(pluginPath)) {
if (!lstatSync(pluginPath).isDirectory()) {
throw new Error(`Plugin base path is not a directory: ${pluginBasePath}`);
}
const packageJsonPath = join(pluginPath, 'package.json');
if (!existsSync(packageJsonPath)) {
throw new Error(`package.json does not exist: ${packageJsonPath}`);
}
const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));
if (!packageJson.name) {
throw new Error(`package.json does not have a name: ${packageJsonPath}`);
}
items.push(...getTechnologyAPIItems(plugin, technologyCategory));
} else {
console.warn(
`Plugin path does not exist: ${pluginPath}. Only attempting to load static files.`
);
}
// TODO: when moving from `astro-docs` this path will need to also be updated
const staticFiles = getStaticPluginFiles(
join(workspaceRoot, 'astro-docs', 'src', 'content', 'docs', baseUrl)
);
// Enforce consistent ordering across all technology sections
// Order: Introduction → Guides → Generated items (Generators, Executors, Migrations) → Everything else
const finalItems: SidebarSubItem[] = [];
let introItem: SidebarItem | undefined;
let guidesItem: SidebarItem | undefined;
const otherStaticFiles: SidebarItem[] = [];
if (staticFiles.length > 0) {
for (const file of staticFiles) {
if (typeof file === 'string') continue;
const isIntro = file.label === 'Introduction';
if (isIntro) {
introItem = file;
} else if (file.label === 'Guides') {
guidesItem = file;
} else {
otherStaticFiles.push(file);
}
}
}
introItem && finalItems.push(introItem as SidebarSubItem);
guidesItem && finalItems.push(guidesItem as SidebarSubItem);
finalItems.push(...(items as SidebarSubItem[]));
finalItems.push(...(otherStaticFiles as SidebarSubItem[]));
return finalItems;
}
function hasValidConfig(
pluginPath: string,
type: 'executors' | 'generators' | 'migrations'
): boolean {
const configPath = join(pluginPath, `${type}.json`);
if (!existsSync(configPath)) {
return false;
}
const content = JSON.parse(readFileSync(configPath, 'utf-8'));
if (type === 'executors') {
const hasExecutors =
content.executors &&
typeof content.executors === 'object' &&
Object.keys(content.executors).length > 0;
return hasExecutors && hasVisibleImpls(content.executors);
}
// migrations can be generators or packageJsonUpdates
const hasGenerators =
isGeneratorsConfig(content) && hasVisibleImpls(content.generators);
const hasPackageJsonUpdates =
content.packageJsonUpdates &&
typeof content.packageJsonUpdates === 'object' &&
Object.keys(content.packageJsonUpdates).length > 0;
return hasGenerators || hasPackageJsonUpdates;
}
/**
* Extract label from frontmatter with fallback priority:
* 1. sidebar.label
* 2. title
* 3. filename (fallback)
*/
function extractLabelFromFile(filePath: string, fileName: string): string {
try {
const fileContent = readFileSync(filePath, 'utf-8');
const parsed = frontMatter<{
title?: string;
sidebar?: { label?: string };
}>(fileContent);
// Priority 1: sidebar.label
if (parsed.attributes?.sidebar?.label) {
return parsed.attributes.sidebar.label;
}
// Priority 2: title
if (parsed.attributes?.title) {
return parsed.attributes.title;
}
} catch (error) {
// If parsing fails, fall back to filename
console.warn(`Failed to parse frontmatter for ${filePath}:`, error);
}
// Priority 3: filename (fallback)
return fileName;
}
function getStaticPluginFiles(pluginContentDir: string): SidebarItem[] {
const staticFiles: SidebarItem[] = [];
if (!existsSync(pluginContentDir)) {
return staticFiles;
}
try {
// eg. "/technologies/build-tools/esbuild/introduction.mdoc" -> "build-tools/esbuild/introdumentation.mdoc"
const baseUrl = pluginContentDir.split(`/technologies/`).pop();
// Get all plugin names to check against subdirectories
const allPluginNames = Object.keys(pluginToTechnology);
// Recursive function to process directories and build nested structure
function processDirectory(
dirPath: string,
relativePath: string = ''
): SidebarItem[] {
const items: SidebarItem[] = [];
const files = readdirSync(dirPath, { withFileTypes: true });
// Sort to ensure consistent ordering (directories first, then files)
files.sort((a, b) => {
if (a.isDirectory() && !b.isDirectory()) return -1;
if (!a.isDirectory() && b.isDirectory()) return 1;
return a.name.localeCompare(b.name);
});
for (const file of files) {
const fullPath = join(dirPath, file.name);
if (file.isDirectory()) {
// Skip this directory if it's the name of another plugin
if (allPluginNames.includes(file.name)) {
continue;
}
// Process subdirectory recursively
const newRelativePath = relativePath
? `${relativePath}/${file.name}`
: file.name;
const subItems = processDirectory(fullPath, newRelativePath);
// Only add the directory group if it contains items
if (subItems.length > 0) {
// Check if there's an index.mdoc file in this directory
const indexPath = join(fullPath, 'index.mdoc');
const hasIndex = existsSync(indexPath);
// For directories with content, add them as a group
// If there's an index.mdoc, we'll use its title for the label
if (hasIndex) {
const label = extractLabelFromFile(indexPath, file.name);
items.push({
label: label,
collapsed: true,
items: subItems,
} as SidebarSubItem);
} else {
items.push({
label: file.name,
collapsed: true,
items: subItems,
} as SidebarSubItem);
}
}
} else if (
file.isFile() &&
(file.name.endsWith('.md') ||
file.name.endsWith('.mdx') ||
file.name.endsWith('.mdoc'))
) {
const fileName = basename(file.name, extname(file.name));
// Skip index files as they're handled by directory processing
if (fileName === 'index') {
continue;
}
const fileSlug = fileName.split(' ').join('-').toLowerCase();
// Build the full slug including the relative path
const fullSlug = relativePath
? `technologies/${baseUrl}/${relativePath}/${fileSlug}`
: `technologies/${baseUrl}/${fileSlug}`;
// Extract label from frontmatter with fallback priority
const label = extractLabelFromFile(fullPath, fileName);
items.push({
label: label,
slug: fullSlug.toLowerCase(),
});
}
}
return items;
}
// Start processing from the root plugin content directory
return processDirectory(pluginContentDir);
} catch (error) {
console.warn(
`Skipping ${pluginContentDir}. Issue reading static files:`,
error
);
}
return staticFiles;
}
/*
* Apply the same remapping logic used in sidebar generation
* TODO: caleb, this is bad and I hate it but it is what is is
**/
export function pluginSpecialCasePluginRemapping(pluginName: string) {
switch (pluginName) {
// we call the js plugin `typescript` in the URLs technologies
case 'js':
return 'typescript';
default:
return pluginName;
}
}
function isGeneratorsConfig(
content: unknown
): content is GeneratorsJson & Pick<Required<GeneratorsJson>, 'generators'> {
return !!(
content &&
typeof content === 'object' &&
'generators' in content &&
typeof content.generators === 'object'
);
}
/**
* validate that a generator/migration/executor config has at least 1 visible implmentation
**/
function hasVisibleImpls(content: Record<string, unknown>): boolean {
return (
content &&
Object.values(content).some(
(impl: any) => typeof impl === 'object' && !impl.hidden
)
);
}