bejamas 0.0.0-canary.58c2686

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,574 @@
1
+ import { __require, logger, spinner } from "./spinner-B-Vrcyil.js";
2
+ import { createRequire } from "module";
3
+ import { existsSync, mkdirSync } from "fs";
4
+ import path, { dirname, extname, join, posix, relative } from "path";
5
+ import { readdir, writeFile } from "fs/promises";
6
+ import { Project, SyntaxKind } from "ts-morph";
7
+
8
+ //#region src/docs/generate-mdx/utils.ts
9
+ const RESERVED_COMPONENTS = new Set([
10
+ "Fragment",
11
+ "CodePackageManagers",
12
+ "DocsTabs",
13
+ "DocsTabItem",
14
+ "DocsCodePackageManagers",
15
+ "Tabs",
16
+ "TabItem"
17
+ ]);
18
+ function slugify(input) {
19
+ return input.replace(/\.(astro|md|mdx|tsx|ts|jsx|js)$/i, "").replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/\s+/g, "-").replace(/_+/g, "-").toLowerCase();
20
+ }
21
+ function extractFrontmatter(source) {
22
+ const match = source.match(/^---\n([\s\S]*?)\n---/);
23
+ return match && match[1] || "";
24
+ }
25
+ function toIdentifier(name) {
26
+ const base = name.replace(/\.[^.]+$/, "").replace(/[^a-zA-Z0-9]+/g, " ").trim().replace(/\b\w/g, (c) => c.toUpperCase()).replace(/\s+/g, "");
27
+ return /^[A-Za-z_]/.test(base) ? base : `Ex${base}`;
28
+ }
29
+ function parseJsDocMetadata(frontmatterCode) {
30
+ const jsDocMatch = frontmatterCode.match(/\/\*\*([\s\S]*?)\*\//);
31
+ if (!jsDocMatch) return {};
32
+ const lines = jsDocMatch[1].split("\n").map((l) => l.replace(/^\s*\*\s?/, ""));
33
+ const meta = {};
34
+ let inUsage = false;
35
+ let inExamples = false;
36
+ let inPrimaryExample = false;
37
+ const usageLines = [];
38
+ const examplesLines = [];
39
+ const primaryExampleLines = [];
40
+ for (const rawLine of lines) {
41
+ const line = rawLine;
42
+ if (inUsage) if (line.trim().startsWith("@")) inUsage = false;
43
+ else {
44
+ usageLines.push(line);
45
+ continue;
46
+ }
47
+ if (inPrimaryExample) if (line.trim().startsWith("@")) inPrimaryExample = false;
48
+ else {
49
+ primaryExampleLines.push(line);
50
+ continue;
51
+ }
52
+ if (inExamples) if (line.trim().startsWith("@")) inExamples = false;
53
+ else {
54
+ examplesLines.push(line);
55
+ continue;
56
+ }
57
+ if (line.trim().startsWith("@component")) meta.name = line.replace("@component", "").trim();
58
+ else if (line.trim().startsWith("@title")) meta.title = line.replace("@title", "").trim();
59
+ else if (line.trim().startsWith("@description")) meta.description = line.replace("@description", "").trim();
60
+ else if (line.trim().startsWith("@usage")) {
61
+ inUsage = true;
62
+ continue;
63
+ } else if (line.trim().startsWith("@examples")) {
64
+ inExamples = true;
65
+ continue;
66
+ } else if (line.trim().startsWith("@example")) {
67
+ inPrimaryExample = true;
68
+ continue;
69
+ }
70
+ }
71
+ if (usageLines.length) meta.usageMDX = usageLines.join("\n").trim();
72
+ if (examplesLines.length) meta.examplesMDX = examplesLines.join("\n").trim();
73
+ if (primaryExampleLines.length) meta.primaryExampleMDX = primaryExampleLines.join("\n").trim();
74
+ return meta;
75
+ }
76
+ function extractPropsFromAstroProps(sourceFile) {
77
+ function unwrapAstroProps(node) {
78
+ let current = node;
79
+ for (let i = 0; i < 10; i += 1) {
80
+ const kind = current.getKind();
81
+ if (kind === SyntaxKind.PropertyAccessExpression) {
82
+ const expr = current.getExpression();
83
+ if (expr && expr.getText() === "Astro" && current.getName() === "props") return current;
84
+ return null;
85
+ }
86
+ if (kind === SyntaxKind.AsExpression || kind === SyntaxKind.TypeAssertion || kind === SyntaxKind.SatisfiesExpression || kind === SyntaxKind.NonNullExpression || kind === SyntaxKind.ParenthesizedExpression) {
87
+ const next = current.getExpression && current.getExpression();
88
+ if (!next) return null;
89
+ current = next;
90
+ continue;
91
+ }
92
+ return null;
93
+ }
94
+ return null;
95
+ }
96
+ const target = sourceFile.getDescendantsOfKind(SyntaxKind.VariableDeclaration).find((decl) => {
97
+ const init = decl.getInitializer();
98
+ if (!init) return false;
99
+ return !!unwrapAstroProps(init);
100
+ });
101
+ if (!target) return [];
102
+ const nameNode = target.getNameNode();
103
+ if (!nameNode || nameNode.getKind() !== SyntaxKind.ObjectBindingPattern) return [];
104
+ return nameNode.asKindOrThrow(SyntaxKind.ObjectBindingPattern).getElements().map((el) => {
105
+ if (!!el.getDotDotDotToken()) return {
106
+ isRest: true,
107
+ hasDefault: false,
108
+ alias: el.getName()
109
+ };
110
+ const propertyNameNode = el.getPropertyNameNode();
111
+ const name = el.getName();
112
+ const propName = propertyNameNode ? propertyNameNode.getText() : name;
113
+ const initializer = el.getInitializer();
114
+ let defaultValue;
115
+ if (initializer) defaultValue = initializer.getText();
116
+ return {
117
+ name: propName,
118
+ hasDefault: initializer != null,
119
+ defaultValue
120
+ };
121
+ });
122
+ }
123
+ function extractPropsFromDeclaredProps(sourceFile) {
124
+ function normalizeTypeText(text) {
125
+ if (!text) return "";
126
+ return text.replace(/\s+/g, " ").replace(/;\s*$/, "").trim();
127
+ }
128
+ const iface = sourceFile.getInterface("Props");
129
+ if (iface) return iface.getProperties().map((prop) => {
130
+ const name = prop.getName();
131
+ const typeNode = prop.getTypeNode();
132
+ const rawType = typeNode ? typeNode.getText() : prop.getType().getText();
133
+ const typeText = normalizeTypeText(rawType);
134
+ const optional = prop.hasQuestionToken();
135
+ return {
136
+ name,
137
+ type: typeText,
138
+ optional
139
+ };
140
+ });
141
+ const typeAlias = sourceFile.getTypeAlias("Props");
142
+ if (typeAlias) {
143
+ const typeNode = typeAlias.getTypeNode();
144
+ if (typeNode && typeNode.getKind() === SyntaxKind.TypeLiteral) return typeNode.asKindOrThrow(SyntaxKind.TypeLiteral).getProperties().map((prop) => {
145
+ const name = prop.getName();
146
+ const tn = prop.getTypeNode();
147
+ const rawType = tn ? tn.getText() : prop.getType().getText();
148
+ const typeText = normalizeTypeText(rawType);
149
+ const optional = prop.hasQuestionToken();
150
+ return {
151
+ name,
152
+ type: typeText,
153
+ optional
154
+ };
155
+ });
156
+ }
157
+ return [];
158
+ }
159
+ function resolveUiRoot(cwd) {
160
+ const require$1 = createRequire(import.meta.url);
161
+ const envRoot = process.env.BEJAMAS_UI_ROOT;
162
+ if (envRoot && existsSync(path.join(envRoot, "package.json"))) return envRoot;
163
+ try {
164
+ const pkgPath = require$1.resolve("@bejamas/ui/package.json", { paths: [cwd] });
165
+ return path.dirname(pkgPath);
166
+ } catch {}
167
+ let current = cwd;
168
+ for (let i = 0; i < 6; i += 1) {
169
+ const candidate = path.join(current, "packages", "ui", "package.json");
170
+ if (existsSync(candidate)) return path.dirname(candidate);
171
+ const parent = path.dirname(current);
172
+ if (parent === current) break;
173
+ current = parent;
174
+ }
175
+ try {
176
+ const anyEntry = require$1.resolve("@bejamas/ui/*", { paths: [cwd] });
177
+ return path.resolve(anyEntry, "..", "..");
178
+ } catch {}
179
+ throw new Error("Unable to locate @bejamas/ui in the workspace");
180
+ }
181
+ function resolveOutDir(cwd) {
182
+ const envOut = process.env.BEJAMAS_DOCS_OUT_DIR;
183
+ if (envOut && envOut.length) return path.isAbsolute(envOut) ? envOut : path.resolve(cwd, envOut);
184
+ return path.resolve(cwd, "../../apps/web/src/content/docs/components");
185
+ }
186
+ function detectHasImportTopLevel(block, pascalName) {
187
+ if (!block) return false;
188
+ let inFence = false;
189
+ const importLineRegex = /* @__PURE__ */ new RegExp(`^\\s*import\\s+.*\\bfrom\\s+['"][^'"]+\\b${pascalName}\\.astro['"]`);
190
+ for (const line of block.split("\n")) {
191
+ if (line.trim().startsWith("```")) {
192
+ inFence = !inFence;
193
+ continue;
194
+ }
195
+ if (!inFence && importLineRegex.test(line)) return true;
196
+ }
197
+ return false;
198
+ }
199
+ function normalizeBlockMDX(block) {
200
+ if (!block) return "";
201
+ return block.replace(/from\s+['"]@\/ui\/components\//g, "from '@bejamas/ui/components/");
202
+ }
203
+ function normalizeUsageMDX(usageMDX, pascalName) {
204
+ const normalized = normalizeBlockMDX(usageMDX);
205
+ const hasImport = detectHasImportTopLevel(normalized, pascalName);
206
+ return {
207
+ text: normalized.trim(),
208
+ hasImport
209
+ };
210
+ }
211
+ function extractComponentTagsFromMDX(block) {
212
+ if (!block) return [];
213
+ let inFence = false;
214
+ const found = /* @__PURE__ */ new Set();
215
+ const tagRegex = /<([A-Z][A-Za-z0-9_]*)\b/g;
216
+ for (const line of block.split("\n")) {
217
+ if (line.trim().startsWith("```")) {
218
+ inFence = !inFence;
219
+ continue;
220
+ }
221
+ if (inFence) continue;
222
+ let match;
223
+ while ((match = tagRegex.exec(line)) !== null) {
224
+ const name = match[1];
225
+ found.add(name);
226
+ }
227
+ }
228
+ return Array.from(found);
229
+ }
230
+ async function discoverExamples(componentFilePath, componentsDir) {
231
+ const fileBase = path.basename(componentFilePath, path.extname(componentFilePath));
232
+ const kebabBase = slugify(fileBase);
233
+ const candidates = [join(dirname(componentFilePath), `${fileBase}.examples`), join(dirname(componentFilePath), `${kebabBase}.examples`)];
234
+ const found = [];
235
+ for (const dir of candidates) try {
236
+ const items = await readdir(dir, { withFileTypes: true });
237
+ for (const it of items) if (it.isFile() && extname(it.name).toLowerCase() === ".astro") {
238
+ const abs = join(dir, it.name);
239
+ const relFromComponents = path.relative(componentsDir, abs).split(path.sep).join(posix.sep);
240
+ found.push(relFromComponents);
241
+ }
242
+ } catch {}
243
+ return found;
244
+ }
245
+ function createSourceFileFromFrontmatter(frontmatterCode) {
246
+ return new Project({ useInMemoryFileSystem: true }).createSourceFile("Component.ts", frontmatterCode, { overwrite: true });
247
+ }
248
+
249
+ //#endregion
250
+ //#region src/docs/generate-mdx/mdx-builder.ts
251
+ function buildMdx(params) {
252
+ const { importName, importPath, title, description, usageMDX, hasImport, propsList, propsTable, examples, examplesBlocks, autoImports, lucideIcons, primaryExampleMDX, componentSource, commandName } = params;
253
+ const sortedLucide = (lucideIcons ?? []).slice().sort();
254
+ const externalTopImports = [`import { Tabs as DocsTabs, TabItem as DocsTabItem } from '@astrojs/starlight/components';`, sortedLucide.length ? `import { ${sortedLucide.join(", ")} } from '@lucide/astro';` : null].filter((v) => v != null).slice().sort((a, b) => String(a).localeCompare(String(b)));
255
+ const uiAutoLines = (autoImports ?? []).slice().sort().map((name) => `import ${name} from '@bejamas/ui/components/${name}.astro';`);
256
+ const exampleLines = (examples ?? []).map((ex) => `import ${ex.importName} from '${ex.importPath}';`).sort((a, b) => a.localeCompare(b));
257
+ const internalTopImports = [
258
+ !hasImport ? `import ${importName} from '${importPath}';` : null,
259
+ ...uiAutoLines,
260
+ ...exampleLines
261
+ ].filter((v) => v != null).slice().sort((a, b) => String(a).localeCompare(String(b)));
262
+ const importLines = [
263
+ ...externalTopImports,
264
+ externalTopImports.length && internalTopImports.length ? "" : null,
265
+ ...internalTopImports
266
+ ].filter((v) => v !== null && v !== void 0);
267
+ const extractTags = (snippet) => {
268
+ const found = /* @__PURE__ */ new Set();
269
+ const tagRegex = /<([A-Z][A-Za-z0-9_]*)\b/g;
270
+ let m;
271
+ while ((m = tagRegex.exec(snippet)) !== null) found.add(m[1]);
272
+ return found;
273
+ };
274
+ const buildSnippetImportLines = (snippet) => {
275
+ if (!snippet || !snippet.length) return [];
276
+ const used = extractTags(snippet);
277
+ const usedIcons = sortedLucide.filter((n) => used.has(n));
278
+ const usedUi = (autoImports ?? []).filter((n) => used.has(n)).slice().sort();
279
+ const includeMain = !hasImport && used.has(importName);
280
+ const external = [];
281
+ if (usedIcons.length) external.push(`import { ${usedIcons.join(", ")} } from '@lucide/astro';`);
282
+ const internal = [];
283
+ if (includeMain) internal.push(`import ${importName} from '${importPath}';`);
284
+ internal.push(...usedUi.map((name) => `import ${name} from '@bejamas/ui/components/${name}.astro';`));
285
+ const externalSorted = external.slice().sort((a, b) => a.localeCompare(b));
286
+ const internalSorted = internal.slice().sort((a, b) => a.localeCompare(b));
287
+ return [
288
+ ...externalSorted,
289
+ externalSorted.length && internalSorted.length ? "" : null,
290
+ ...internalSorted
291
+ ].filter((v) => v !== null && v !== void 0);
292
+ };
293
+ const primaryExampleSection = primaryExampleMDX && primaryExampleMDX.length ? `<DocsTabs>
294
+ <DocsTabItem label="Preview">
295
+ <div class="not-content sl-bejamas-component-preview flex justify-center p-10 border border-border rounded-xl min-h-[450px] items-center">
296
+ ${primaryExampleMDX}
297
+ </div>
298
+ </DocsTabItem>
299
+ <DocsTabItem label="Source">
300
+
301
+ \`\`\`astro
302
+ ${(() => {
303
+ const lines = buildSnippetImportLines(primaryExampleMDX);
304
+ return lines.length ? `---\n${lines.join("\n")}\n---\n\n` : "";
305
+ })()}${primaryExampleMDX}
306
+ \`\`\`
307
+ </DocsTabItem>
308
+ </DocsTabs>` : null;
309
+ const exampleSections = [];
310
+ if (examplesBlocks && examplesBlocks.length) for (const blk of examplesBlocks) exampleSections.push(`### ${blk.title}
311
+
312
+ <DocsTabs>
313
+ <DocsTabItem label="Preview">
314
+ <div class="not-content sl-bejamas-component-preview flex justify-center p-10 border border-border rounded-xl min-h-[450px] items-center">
315
+ ${blk.body}
316
+ </div>
317
+ </DocsTabItem>
318
+ <DocsTabItem label="Source">
319
+
320
+ \`\`\`astro
321
+ ${(() => {
322
+ const lines = buildSnippetImportLines(blk.body);
323
+ return lines.length ? `---\n${lines.join("\n")}\n---\n\n` : "";
324
+ })()}${blk.body}
325
+ \`\`\`
326
+ </DocsTabItem>
327
+ </DocsTabs>`);
328
+ if (examples && examples.length) for (const ex of examples) exampleSections.push(`### ${ex.title}
329
+
330
+ <DocsTabs>
331
+ <DocsTabItem label="Preview">
332
+ <div class="not-content">
333
+ <${ex.importName} />
334
+ </div>
335
+ </DocsTabItem>
336
+ <DocsTabItem label="Source">
337
+
338
+ \`\`\`astro
339
+ ${ex.source}
340
+ \`\`\`
341
+ </DocsTabItem>
342
+ </DocsTabs>`);
343
+ const formatDefault = (val) => {
344
+ if (val == null) return "";
345
+ let raw = String(val).trim();
346
+ if (!raw.length) return "";
347
+ raw = raw.replace(/[\u201C\u201D\u201E\u201F]/g, "\"").replace(/[\u2018\u2019]/g, "'");
348
+ const isSingleQuoted = /^'[^']*'$/.test(raw);
349
+ const isDoubleQuoted = /^"[^"]*"$/.test(raw);
350
+ const isBacktickSimple = /^`[^`]*`$/.test(raw) && raw.indexOf("${") === -1;
351
+ let content = raw;
352
+ if (isSingleQuoted || isDoubleQuoted || isBacktickSimple) content = `"${raw.slice(1, -1)}"`;
353
+ content = content.replace(/\|/g, "\\|");
354
+ const hasTick = content.includes("`");
355
+ const hasDoubleTick = content.includes("``");
356
+ const fence = !hasTick ? "`" : !hasDoubleTick ? "``" : "```";
357
+ return `${fence}${content}${fence}`;
358
+ };
359
+ const installationSection = `## Installation
360
+ <DocsTabs syncKey="installation">
361
+ <DocsTabItem label="CLI">
362
+
363
+ <DocsTabs syncKey="pkg">
364
+ <DocsTabItem label="bun">
365
+
366
+ \`\`\`bash
367
+ bunx bejamas add ${commandName}
368
+ \`\`\`
369
+
370
+ </DocsTabItem>
371
+ <DocsTabItem label="npm">
372
+
373
+ \`\`\`bash
374
+ npx bejamas add ${commandName}
375
+ \`\`\`
376
+
377
+ </DocsTabItem>
378
+ <DocsTabItem label="pnpm">
379
+
380
+ \`\`\`bash
381
+ pnpm dlx bejamas add ${commandName}
382
+ \`\`\`
383
+
384
+ </DocsTabItem>
385
+ <DocsTabItem label="yarn">
386
+
387
+ \`\`\`bash
388
+ yarn dlx bejamas add ${commandName}
389
+ \`\`\`
390
+
391
+ </DocsTabItem>
392
+ </DocsTabs>
393
+ </DocsTabItem>
394
+ <DocsTabItem label="Manual">
395
+
396
+ \`\`\`astro
397
+ ${componentSource}
398
+ \`\`\`
399
+ </DocsTabItem>
400
+ </DocsTabs>`;
401
+ return [
402
+ "---",
403
+ `title: ${title}`,
404
+ description ? `description: ${description}` : null,
405
+ "---",
406
+ "",
407
+ ...importLines,
408
+ importLines.length ? "" : null,
409
+ description ? description : null,
410
+ description ? "" : null,
411
+ primaryExampleSection,
412
+ primaryExampleSection ? "" : null,
413
+ installationSection,
414
+ "",
415
+ usageMDX && usageMDX.length ? `## Usage\n\n${usageMDX}` : null,
416
+ "",
417
+ propsTable && propsTable.length ? `## Props\n\n| Prop | Type | Default |\n|---|---|---|\n${propsTable.map((p) => `| <code>${p.name}</code> | \`${(p.type || "").replace(/\|/g, "\\|")}\` | ${formatDefault(p.defaultValue)} |`).join("\n")}` : propsList ? `## Props\n\n${propsList}` : null,
418
+ propsTable && propsTable.length || propsList ? "" : null,
419
+ exampleSections.length ? `## Examples\n\n` + exampleSections.join("\n\n") : null
420
+ ].filter((v) => v !== null && v !== void 0).join("\n").trim() + "\n";
421
+ }
422
+
423
+ //#endregion
424
+ //#region src/docs/generate-mdx/index.ts
425
+ async function main() {
426
+ const DEBUG = process.env.BEJAMAS_DEBUG === "1" || process.env.BEJAMAS_DEBUG === "true";
427
+ const cwd = process.env.BEJAMAS_DOCS_CWD && process.env.BEJAMAS_DOCS_CWD.length ? process.env.BEJAMAS_DOCS_CWD : process.cwd();
428
+ const uiRoot = resolveUiRoot(cwd);
429
+ const componentsDir = join(uiRoot, "src", "components");
430
+ const outDir = resolveOutDir(cwd);
431
+ mkdirSync(outDir, { recursive: true });
432
+ if (DEBUG) {
433
+ logger.info(`[docs-generator] cwd: ${cwd}`);
434
+ logger.info(`[docs-generator] uiRoot: ${uiRoot}`);
435
+ logger.info(`[docs-generator] componentsDir: ${componentsDir}`);
436
+ logger.info(`[docs-generator] outDir: ${outDir}`);
437
+ }
438
+ const files = (await readdir(componentsDir, { withFileTypes: true })).filter((e) => e.isFile() && extname(e.name).toLowerCase() === ".astro");
439
+ if (DEBUG) {
440
+ logger.info(`[docs-generator] components found: ${files.length}`);
441
+ if (files.length) logger.info(`[docs-generator] first few: ${files.slice(0, 5).map((f) => f.name).join(", ")}`);
442
+ }
443
+ let generatedCount = 0;
444
+ const total = files.length;
445
+ const spin = spinner(`Generating docs (0/${total})`).start();
446
+ for (const f of files) {
447
+ const filePath = join(componentsDir, f.name);
448
+ const astroFile = await (await import("fs/promises")).readFile(filePath, "utf-8");
449
+ const frontmatterCode = extractFrontmatter(astroFile);
450
+ const sourceFile = createSourceFileFromFrontmatter(frontmatterCode);
451
+ const meta = parseJsDocMetadata(frontmatterCode);
452
+ const declaredProps = extractPropsFromDeclaredProps(sourceFile);
453
+ const destructuredProps = extractPropsFromAstroProps(sourceFile);
454
+ const defaultsMap = /* @__PURE__ */ new Map();
455
+ for (const p of destructuredProps) if (p.name && p.hasDefault) defaultsMap.set(p.name, p.defaultValue || null);
456
+ const propsTable = (declaredProps.length ? declaredProps : []).map((p) => ({
457
+ name: p.name,
458
+ type: p.type,
459
+ required: !p.optional,
460
+ defaultValue: defaultsMap.has(p.name) ? defaultsMap.get(p.name) : null
461
+ }));
462
+ const slug = `${slugify(f.name)}`;
463
+ const pascal = f.name.replace(/\.(astro)$/i, "");
464
+ const title = meta.title || meta.name || pascal;
465
+ const description = meta.description || "";
466
+ const propsList = "";
467
+ const importName = pascal;
468
+ const importPath = `@bejamas/ui/components/${pascal}.astro`;
469
+ const { text: usageMDX, hasImport: hasImportUsage } = normalizeUsageMDX(meta.usageMDX || "", pascal);
470
+ const primaryExampleMDX = normalizeBlockMDX(meta.primaryExampleMDX || "").trim();
471
+ const examplesMDX = normalizeBlockMDX(meta.examplesMDX || "").trim();
472
+ const hasImportExamples = detectHasImportTopLevel(examplesMDX, pascal);
473
+ const hasImportPrimary = detectHasImportTopLevel(primaryExampleMDX, pascal);
474
+ const hasImport = hasImportUsage || hasImportExamples || hasImportPrimary;
475
+ let exampleRelPaths = [];
476
+ let examples = [];
477
+ const examplesBlocksRaw = examplesMDX;
478
+ if (parseExamplesBlocks(examplesBlocksRaw).length === 0) {
479
+ exampleRelPaths = await discoverExamples(filePath, componentsDir);
480
+ examples = (exampleRelPaths || []).map((rel) => {
481
+ const importPath$1 = `@bejamas/ui/components/${rel.split(__require("path").sep).join(__require("path").posix.sep)}`;
482
+ const abs = join(componentsDir, rel);
483
+ const source = __require("fs").readFileSync(abs, "utf-8");
484
+ const base = toIdentifier(__require("path").basename(rel, __require("path").extname(rel)));
485
+ return {
486
+ importName: `${pascal}${base}`,
487
+ importPath: importPath$1,
488
+ title: base,
489
+ source
490
+ };
491
+ });
492
+ }
493
+ const usedInUsage = extractComponentTagsFromMDX(usageMDX).filter((n) => n !== pascal);
494
+ const usedInExamples = extractComponentTagsFromMDX(examplesMDX).filter((n) => n !== pascal);
495
+ const usedInPrimary = extractComponentTagsFromMDX(primaryExampleMDX).filter((n) => n !== pascal);
496
+ const autoSet = new Set([
497
+ ...usedInUsage,
498
+ ...usedInExamples,
499
+ ...usedInPrimary
500
+ ]);
501
+ const autoImports = Array.from(autoSet).filter((name) => !RESERVED_COMPONENTS.has(name)).filter((name) => true);
502
+ const lucideIcons = autoImports.filter((n) => /Icon$/.test(n));
503
+ const uiAutoImports = autoImports.filter((n) => !/Icon$/.test(n));
504
+ const mdx = buildMdx({
505
+ importName,
506
+ importPath,
507
+ title,
508
+ description,
509
+ usageMDX,
510
+ hasImport,
511
+ propsList,
512
+ propsTable,
513
+ examples,
514
+ examplesBlocks: parseExamplesBlocks(examplesBlocksRaw),
515
+ autoImports: uiAutoImports,
516
+ lucideIcons,
517
+ primaryExampleMDX,
518
+ componentSource: astroFile.trim(),
519
+ commandName: slug
520
+ });
521
+ const outFile = join(outDir, `${slug}.mdx`);
522
+ mkdirSync(dirname(outFile), { recursive: true });
523
+ await writeFile(outFile, mdx, "utf-8");
524
+ generatedCount += 1;
525
+ spin.text = `Generating docs (${generatedCount}/${total}) - ${title}`;
526
+ if (DEBUG) logger.info(`Generated ${outFile}`);
527
+ }
528
+ spin.succeed(`Created ${generatedCount} file${generatedCount === 1 ? "" : "s"}:`);
529
+ files.map((f) => {
530
+ const slug = `${slugify(f.name)}`;
531
+ const outFile = join(outDir, `${slug}.mdx`);
532
+ return relative(cwd, outFile);
533
+ }).sort((a, b) => a.localeCompare(b)).forEach((p) => {
534
+ logger.log(` - ${p}`);
535
+ });
536
+ logger.break();
537
+ }
538
+ function parseExamplesBlocks(examplesMDX) {
539
+ if (!examplesMDX) return [];
540
+ const lines = examplesMDX.split("\n");
541
+ const blocks = [];
542
+ let current = {
543
+ title: "",
544
+ body: []
545
+ };
546
+ for (const line of lines) {
547
+ const heading = line.match(/^###\s+(.+)$/);
548
+ if (heading) {
549
+ if (current.title || current.body.length) blocks.push(current);
550
+ current = {
551
+ title: heading[1].trim(),
552
+ body: []
553
+ };
554
+ continue;
555
+ }
556
+ current.body.push(line);
557
+ }
558
+ if (current.title || current.body.length) blocks.push(current);
559
+ return blocks.map((b, idx) => ({
560
+ title: b.title || `Example ${idx + 1}`,
561
+ body: b.body.join("\n").trim()
562
+ }));
563
+ }
564
+ async function runDocsGenerator() {
565
+ await main();
566
+ }
567
+ if (process.env.BEJAMAS_SKIP_AUTO_RUN !== "1" && process.env.BEJAMAS_SKIP_AUTO_RUN !== "true") runDocsGenerator().catch((err) => {
568
+ logger.error(String(err));
569
+ process.exit(1);
570
+ });
571
+
572
+ //#endregion
573
+ export { runDocsGenerator };
574
+ //# sourceMappingURL=generate-mdx-DHm_37lA.js.map