@qualcomm-ui/mdx-vite 3.0.3 → 3.1.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/cli.js +29 -30
- package/dist/cli.js.map +3 -3
- package/dist/docs-plugin/markdown/knowledge/knowledge-exporter.d.ts +5 -1
- package/dist/docs-plugin/markdown/knowledge/knowledge-exporter.d.ts.map +1 -1
- package/dist/docs-plugin/markdown/knowledge/section-extractor.d.ts +0 -5
- package/dist/docs-plugin/markdown/knowledge/section-extractor.d.ts.map +1 -1
- package/dist/docs-plugin/markdown/knowledge/types.d.ts +8 -0
- package/dist/docs-plugin/markdown/knowledge/types.d.ts.map +1 -1
- package/dist/docs-plugin/markdown/remark-pipeline.d.ts +2 -2
- package/dist/docs-plugin/markdown/remark-pipeline.d.ts.map +1 -1
- package/dist/docs-plugin/plugin-state.d.ts +1 -0
- package/dist/docs-plugin/plugin-state.d.ts.map +1 -1
- package/dist/docs-plugin/remark/remark-frontmatter-title.d.ts +3 -4
- package/dist/docs-plugin/remark/remark-frontmatter-title.d.ts.map +1 -1
- package/dist/docs-plugin/search-indexer.d.ts.map +1 -1
- package/dist/index.js +118 -101
- package/dist/index.js.map +3 -3
- package/dist/tsbuildinfo +1 -1
- package/package.json +2 -2
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/angular-demo-plugin/angular-demo-plugin.ts", "../src/docs-plugin/config/config-loader.ts", "../src/docs-plugin/path-utils.ts", "../src/docs-plugin/config/config-schema.ts", "../src/docs-plugin/config/zod.ts", "../src/docs-plugin/docs-plugin.ts", "../src/docs-plugin/plugin-state.ts", "../src/docs-plugin/markdown/create-slug.ts", "../src/docs-plugin/markdown/markdown-file-reader.ts", "../src/docs-plugin/markdown/frontmatter-schema.ts", "../src/docs-plugin/markdown/mdx-utils.ts", "../src/docs-plugin/markdown/remark-pipeline.ts", "../src/docs-plugin/remark/remark-alerts.ts", "../src/docs-plugin/remark/remark-code-tabs.ts", "../src/docs-plugin/remark/remark-extract-meta.ts", "../src/docs-plugin/remark/remark-frontmatter-description.ts", "../src/docs-plugin/remark/remark-frontmatter-interpolation.ts", "../src/docs-plugin/remark/remark-frontmatter-title.ts", "../src/docs-plugin/remark/remark-remove-code-blocks.ts", "../src/docs-plugin/remark/remark-remove-jsx.ts", "../src/docs-plugin/remark/remark-self-link-headings.ts", "../src/docs-plugin/remark/remark-spoilers.ts", "../src/docs-plugin/remark/remark-steps.ts", "../src/docs-plugin/markdown/knowledge/knowledge-exporter.ts", "../src/docs-plugin/nav-builder/get-route-meta.ts", "../src/docs-plugin/nav-builder/nav-builder.ts", "../src/docs-plugin/nav-builder/page-map.ts", "../src/docs-plugin/nav-builder/transform-route-meta-array.ts", "../src/docs-plugin/markdown/knowledge/filter-frontmatter.ts", "../src/docs-plugin/markdown/knowledge/plugins/demo-plugin.ts", "../src/docs-plugin/markdown/knowledge/utils.ts", "../src/docs-plugin/markdown/knowledge/plugins/doc-props-plugin.ts", "../src/docs-plugin/markdown/knowledge/plugins/filter-text-directives.ts", "../src/docs-plugin/markdown/knowledge/plugins/npm-install-tabs-plugin.ts", "../src/docs-plugin/markdown/knowledge/plugins/qds-theme-plugin.ts", "../src/docs-plugin/markdown/knowledge/section-extractor.ts", "../src/docs-plugin/search-indexer.ts", "../src/docs-plugin/doc-props/doc-props-indexer.ts", "../src/docs-plugin/mdx-plugins.ts", "../src/exports.ts", "../src/docs-plugin/rehype/rehype-slug.ts", "../src/docs-plugin/rehype/rehype-sectionize.ts", "../src/docs-plugin/shiki/utils.ts", "../src/docs-plugin/shiki/shiki-transformer-code-attribute.ts", "../src/docs-plugin/shiki/shiki-transformer-hidden.ts", "../src/docs-plugin/shiki/shiki-transformer-preview-block.ts", "../src/docs-plugin/shiki/internal/shiki-transformer-tailwind.ts", "../src/react-demo-plugin/demo-plugin-constants.ts", "../src/react-demo-plugin/demo-plugin-utils.ts", "../src/react-demo-plugin/react-demo-plugin.ts"],
|
|
4
|
-
"sourcesContent": ["// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\nimport chalk from \"chalk\"\nimport {type FSWatcher, watch} from \"chokidar\"\nimport {glob} from \"glob\"\nimport {existsSync, statSync} from \"node:fs\"\nimport {readFile} from \"node:fs/promises\"\nimport {basename, dirname, join, relative, resolve} from \"node:path\"\nimport {\n createHighlighter,\n type Highlighter,\n type ThemeRegistration,\n type ThemeRegistrationRaw,\n type ThemeRegistrationResolved,\n} from \"shiki\"\nimport * as ts from \"typescript\"\nimport type {Plugin, ViteDevServer} from \"vite\"\n\nimport {\n type AngularDemoInfo,\n quiCustomDarkTheme,\n type SourceCodeData,\n} from \"@qualcomm-ui/mdx-common\"\nimport {dedent} from \"@qualcomm-ui/utils/dedent\"\n\nimport {getShikiTransformers} from \"../docs-plugin\"\nimport {\n extractPreviewFromHighlightedHtml,\n transformerCodeAttribute,\n transformerPreviewBlock,\n} from \"../docs-plugin/shiki\"\nimport {createShikiTailwindTransformer} from \"../docs-plugin/shiki/internal\"\n\nexport interface AngularDemoPluginOptions {\n demoPattern?: string | string[]\n /**\n * A mapping of <demoId, initialHtml>, which will be used for the initial\n * serverside render of each demo to prevent FOUC.\n */\n initialHtml?: Record<string, string>\n routesDir?: string\n theme?: {\n dark:\n | ThemeRegistrationRaw\n | ThemeRegistration\n | ThemeRegistrationResolved\n | string\n light:\n | ThemeRegistrationRaw\n | ThemeRegistration\n | ThemeRegistrationResolved\n | string\n }\n /**\n * When enabled, transforms Tailwind class names to inline styles in the\n * highlighted code. Non-inlineable classes (hover:, sm:, etc.) are kept as\n * className and their CSS rules are aggregated into a residual-css entry.\n */\n transformTailwindStyles?: boolean\n}\n\ninterface RelativeImport {\n resolvedPath: string\n source: string\n}\n\ninterface PathAlias {\n pattern: RegExp\n replacement: string\n}\n\ninterface HighlightCodeResult {\n full: string\n preview?: string | null\n}\n\nconst VIRTUAL_MODULE_ID = \"\\0virtual:angular-demo-registry\"\nconst LOG_PREFIX = \"[angular-demo]\"\n\nlet hasWatcherInitialized = false\n\nfunction logDev(...args: any[]) {\n if (!hasWatcherInitialized) {\n return\n }\n console.log(...args)\n}\n\nlet demoDimensionsCache: Record<string, DOMRect> = {}\nlet highlighter: Highlighter | null = null\nlet initCount = 0\nconst demoRegistry = new Map<string, AngularDemoInfo>()\nlet hotUpdateDemoIds: string[] = []\n\nexport function angularDemoPlugin({\n demoPattern = \"src/routes/**/demos/*.ts\",\n initialHtml,\n routesDir = \"src/routes\",\n theme = {\n dark: quiCustomDarkTheme,\n light: \"github-light-high-contrast\",\n },\n transformTailwindStyles,\n}: AngularDemoPluginOptions = {}): Plugin {\n let watcher: FSWatcher | null = null\n let devServer: ViteDevServer | null = null\n\n const defaultShikiOptions = {\n defaultColor: \"light-dark()\",\n themes: {\n dark: theme.dark,\n light: theme.light,\n },\n }\n\n return {\n async buildEnd() {\n if (watcher) {\n await watcher.close()\n watcher = null\n hasWatcherInitialized = false\n }\n },\n async buildStart() {\n if (initCount === 0) {\n initCount++\n return\n }\n\n if (!highlighter) {\n try {\n highlighter = await createHighlighter({\n langs: [\"angular-ts\", \"angular-html\", \"css\"],\n themes: [theme.dark, theme.light],\n })\n logDev(`${chalk.blue.bold(LOG_PREFIX)} Shiki highlighter initialized`)\n } catch (error) {\n console.warn(\n `${chalk.blue.bold(LOG_PREFIX)} Failed to initialize highlighter:`,\n error,\n )\n }\n }\n\n logDev(`${chalk.blue.bold(LOG_PREFIX)} Initializing Angular demo scanner`)\n await collectAngularDemos()\n\n if (process.env.NODE_ENV === \"development\") {\n if (!hasWatcherInitialized) {\n hasWatcherInitialized = true\n setupAngularWatcher()\n } else {\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} Watcher already initialized by another instance`,\n )\n }\n }\n },\n configureServer(server) {\n devServer = server\n let dimensionUpdateTimeout: NodeJS.Timeout | null = null\n\n server.ws.on(\n \"custom:store-demo-dimensions\",\n (data: {demoId: string; dimensions: DOMRect}) => {\n const demoId = data.demoId\n demoDimensionsCache[demoId] = data.dimensions\n\n if (dimensionUpdateTimeout) {\n clearTimeout(dimensionUpdateTimeout)\n }\n\n dimensionUpdateTimeout = setTimeout(() => {\n const module = server.moduleGraph.getModuleById(VIRTUAL_MODULE_ID)\n if (module) {\n server.moduleGraph.invalidateModule(module)\n }\n }, 50)\n },\n )\n\n server.ws.on(\"custom:reset-demo-dimensions\", () => {\n demoDimensionsCache = {}\n const module = server.moduleGraph.getModuleById(VIRTUAL_MODULE_ID)\n if (module) {\n server.moduleGraph.invalidateModule(module)\n server.reloadModule(module)\n }\n })\n },\n async handleHotUpdate({file, modules, server}) {\n if (!isAngularDemoFile(file)) {\n if (isCssAsset(file)) {\n return modules\n }\n\n if (file.endsWith(\"main.js\")) {\n const ids = [...hotUpdateDemoIds]\n server.ws.send({\n data: {\n demoInfo: ids.reduce(\n (acc: Record<string, AngularDemoInfo | undefined>, current) => {\n acc[current] = demoRegistry.get(current)\n return acc\n },\n {},\n ),\n },\n event: \"demo-bundle-updated\",\n type: \"custom\",\n })\n }\n\n return []\n }\n\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} Processing Angular demo change: ${chalk.cyan(file)}`,\n )\n\n const code = await readFile(file, \"utf-8\")\n const demoInfo = await parseAngularDemo(file, code)\n\n if (!demoInfo || !isAngularDemoEntrypoint(file)) {\n // might be an imported file\n const affectedDemos: AngularDemoInfo[] =\n await scanDemosForFileImport(file)\n\n if (affectedDemos.length > 0) {\n hotUpdateDemoIds = []\n for (const demo of affectedDemos) {\n hotUpdateDemoIds.push(demo.id)\n }\n }\n\n server.ws.send({\n data: {\n ids: [...hotUpdateDemoIds],\n },\n event: \"demo-bundle-updating\",\n type: \"custom\",\n })\n\n return\n }\n\n delete demoDimensionsCache[demoInfo.id]\n demoRegistry.set(demoInfo.id, demoInfo)\n hotUpdateDemoIds = [demoInfo.id]\n\n server.ws.send({\n data: {\n ids: [...hotUpdateDemoIds],\n },\n event: \"demo-bundle-updating\",\n type: \"custom\",\n })\n\n const mainModule = server.moduleGraph.getModuleById(VIRTUAL_MODULE_ID)\n if (mainModule) {\n server.moduleGraph.invalidateModule(mainModule)\n }\n\n const demoModule = server.moduleGraph.getModuleById(file)\n if (demoModule) {\n server.moduleGraph.invalidateModule(demoModule)\n }\n\n return []\n },\n load(id) {\n if (id === VIRTUAL_MODULE_ID) {\n return generateRegistryModule()\n }\n },\n name: \"angular-demo-plugin\",\n resolveId(id) {\n if (id === \"virtual:angular-demo-registry\") {\n return VIRTUAL_MODULE_ID\n }\n },\n writeBundle() {\n console.log(\n `${chalk.blue.bold(LOG_PREFIX)} Successfully integrated ${chalk.green(demoRegistry.size)} component demos`,\n )\n },\n }\n\n async function collectAngularDemos() {\n if (demoRegistry.size) {\n logDev(\n `${chalk.magenta.bold(LOG_PREFIX)} Using cached ${chalk.cyanBright.bold(demoRegistry.size)} demos`,\n )\n return\n }\n\n const demoFiles = await glob(demoPattern)\n demoRegistry.clear()\n\n for (const filePath of demoFiles) {\n const code = await readFile(filePath, \"utf-8\")\n const demoInfo = await parseAngularDemo(filePath, code)\n if (demoInfo) {\n demoRegistry.set(demoInfo.id, demoInfo)\n }\n }\n }\n\n async function scanDemosForFileImport(\n file: string,\n ): Promise<AngularDemoInfo[]> {\n const affectedDemos: AngularDemoInfo[] = []\n\n for (const [demoId, demo] of demoRegistry.entries()) {\n if (demo.sourceCode.find((entry) => entry.filePath === file)) {\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} Reloading demo ${chalk.cyan(demoId)} due to imported file change: ${chalk.yellow(file)}`,\n )\n\n const code = await readFile(demo.filePath, \"utf-8\")\n const updatedDemo = await parseAngularDemo(demo.filePath, code)\n\n if (updatedDemo) {\n delete demoDimensionsCache[updatedDemo.id]\n demoRegistry.set(updatedDemo.id, updatedDemo)\n affectedDemos.push(updatedDemo)\n hotUpdateDemoIds.push(updatedDemo.id)\n }\n }\n }\n\n return affectedDemos\n }\n\n async function highlightCode(\n code: string,\n language: \"angular-ts\" | \"angular-html\" | \"css\" = \"angular-ts\",\n options: {\n onClassesDetected?: (detected: boolean) => void\n onResidualCss?: (rules: Map<string, string>) => void\n } = {},\n ): Promise<HighlightCodeResult> {\n const {onClassesDetected, onResidualCss} = options\n\n if (!highlighter) {\n return {full: code}\n }\n\n let previewCode: string | null = null\n\n const tailwindTransformers = []\n if (transformTailwindStyles && onResidualCss) {\n const transformer = await createShikiTailwindTransformer({\n onClassesDetected: (detected) => {\n onClassesDetected?.(detected)\n },\n onResidualCss,\n styleFormat: \"html\",\n styles: dedent`\n @layer theme, base, components, utilities;\n @import \"tailwindcss/theme.css\" layer(theme);\n @import \"tailwindcss/utilities.css\" layer(utilities);\n @import \"@qualcomm-ui/tailwind-plugin/qui-strict.css\";\n `,\n })\n tailwindTransformers.push(transformer)\n }\n\n try {\n const highlightedCode = highlighter.codeToHtml(code, {\n ...defaultShikiOptions,\n lang: language,\n transformers: [\n ...getShikiTransformers(),\n ...tailwindTransformers,\n transformerPreviewBlock({\n attributeName: \"data-preview\",\n onComplete: (extractedPreview) => {\n previewCode = extractedPreview\n },\n }),\n transformerCodeAttribute({\n attributeName: \"data-code\",\n }),\n {\n enforce: \"post\",\n name: \"shiki-transformer-trim\",\n preprocess(inner) {\n return inner.trim()\n },\n },\n ],\n })\n\n return {\n full: highlightedCode,\n preview: previewCode\n ? extractPreviewFromHighlightedHtml(highlightedCode)\n : null,\n }\n } catch (error) {\n console.warn(\n `${chalk.blue.bold(LOG_PREFIX)} Failed to highlight code with ${language} language:`,\n error,\n )\n return {full: code}\n }\n }\n\n async function extractRelativeImports(\n filePath: string,\n ): Promise<RelativeImport[]> {\n try {\n const content = await readFile(filePath, \"utf-8\")\n\n const sourceFile = ts.createSourceFile(\n filePath,\n content,\n ts.ScriptTarget.Latest,\n true,\n ts.ScriptKind.TS,\n )\n\n const relativeImports: RelativeImport[] = []\n\n function visit(node: ts.Node) {\n if (ts.isImportDeclaration(node)) {\n const moduleSpecifier = node.moduleSpecifier\n\n if (ts.isStringLiteral(moduleSpecifier)) {\n const source = moduleSpecifier.text\n\n if (isRelativeImport(source)) {\n const resolvedPath = resolveRelativeImport(source, filePath)\n relativeImports.push({resolvedPath, source})\n } else if (!isNodeBuiltin(source)) {\n const pathAliases = loadTsConfigPaths(filePath)\n\n if (isPathAliasImport(source, pathAliases)) {\n const resolvedPath = resolvePathAlias(source, pathAliases)\n if (resolvedPath) {\n relativeImports.push({resolvedPath, source})\n }\n }\n }\n }\n }\n\n ts.forEachChild(node, visit)\n }\n\n visit(sourceFile)\n\n return relativeImports\n } catch (error) {\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} ${chalk.yellowBright(\"Failed to extract imports from\")} ${chalk.cyan(filePath)}:`,\n error,\n )\n return []\n }\n }\n\n async function collectAllImports(\n filePath: string,\n visited = new Set<string>(),\n ): Promise<string[]> {\n if (visited.has(filePath)) {\n return []\n }\n\n visited.add(filePath)\n\n const directImports = await extractRelativeImports(filePath)\n\n for (const {resolvedPath} of directImports) {\n await collectAllImports(resolvedPath, visited)\n }\n\n return Array.from(visited).slice(1)\n }\n\n function stripImports(code: string, fileName: string): string[] {\n try {\n const sourceFile = ts.createSourceFile(\n fileName,\n code,\n ts.ScriptTarget.Latest,\n true,\n ts.ScriptKind.TS,\n )\n\n const importRanges: Array<{end: number; start: number}> = []\n\n function visit(node: ts.Node) {\n if (ts.isImportDeclaration(node)) {\n importRanges.push({\n end: node.getEnd(),\n start: node.getFullStart(),\n })\n }\n\n ts.forEachChild(node, visit)\n }\n\n visit(sourceFile)\n\n return importRanges.map((range) => {\n let endPos = range.end\n if (code[endPos] === \"\\n\") {\n endPos++\n }\n return code.slice(range.start, endPos).trim()\n })\n } catch (error) {\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} ${chalk.redBright(\"Failed to strip imports from\")} ${chalk.cyan(fileName)}:`,\n error,\n )\n return []\n }\n }\n\n async function parseAngularDemo(\n filePath: string,\n code: string,\n ): Promise<AngularDemoInfo | null> {\n try {\n const {\n componentClass,\n hasDefaultExport,\n isStandalone,\n selector,\n templateUrl,\n } = parseAngularComponentMeta(filePath, code)\n\n if (!componentClass || !selector) {\n return null\n }\n\n const demoId = componentClass\n const importPath = relative(process.cwd(), filePath).replace(/\\\\/g, \"/\")\n const fileName = basename(filePath)\n const importsWithoutStrip = stripImports(code, filePath)\n\n const sourceCode: SourceCodeData[] = []\n // Use Map for deduplication across all files in this demo\n const aggregatedRules = new Map<string, string>()\n\n const mainSourceEntry = await buildAngularSourceEntry({\n code,\n fileName,\n filePath,\n language: \"angular-ts\",\n })\n sourceCode.push(mainSourceEntry.sourceCodeData)\n if (mainSourceEntry.residualRules) {\n for (const [className, rule] of mainSourceEntry.residualRules) {\n aggregatedRules.set(className, rule)\n }\n }\n\n if (templateUrl) {\n const templateEntry = await maybeBuildTemplateSourceEntry(\n templateUrl,\n filePath,\n )\n if (templateEntry) {\n sourceCode.push(templateEntry.sourceCodeData)\n if (templateEntry.residualRules) {\n for (const [className, rule] of templateEntry.residualRules) {\n aggregatedRules.set(className, rule)\n }\n }\n }\n }\n\n const importedEntries = await buildImportedSourceEntries(filePath)\n for (const entry of importedEntries) {\n sourceCode.push(entry.sourceCodeData)\n if (entry.residualRules) {\n for (const [className, rule] of entry.residualRules) {\n aggregatedRules.set(className, rule)\n }\n }\n }\n\n // Convert aggregated rules to CSS string\n const aggregatedResidualCss =\n aggregatedRules.size > 0\n ? [...aggregatedRules.values()].join(\"\\n\\n\")\n : undefined\n\n if (aggregatedResidualCss) {\n const cssHighlighted = await highlightCode(aggregatedResidualCss, \"css\")\n sourceCode.push({\n fileName: \"styles.css\",\n highlighted: cssHighlighted,\n type: \"residual-css\",\n })\n }\n\n return {\n componentClass,\n filePath: importPath.startsWith(\".\") ? importPath : `./${importPath}`,\n hasDefaultExport,\n id: demoId,\n imports: importsWithoutStrip,\n initialHtml: initialHtml?.[demoId] || undefined,\n isStandalone,\n lastModified: Date.now(),\n selector,\n sourceCode,\n }\n } catch (error) {\n console.error(\n `${chalk.blue.bold(LOG_PREFIX)} Failed to parse Angular demo ${filePath}:`,\n error,\n )\n return null\n }\n }\n\n function parseAngularComponentMeta(\n filePath: string,\n source: string,\n ): {\n componentClass: string\n hasDefaultExport: boolean\n importsFromAst: string[]\n isStandalone: boolean\n selector: string\n templateUrl: string | null\n } {\n const sourceFile = ts.createSourceFile(\n filePath,\n source,\n ts.ScriptTarget.Latest,\n true,\n ts.ScriptKind.TS,\n )\n\n let componentClass = \"\"\n let selector = \"\"\n let isStandalone = true\n let templateUrl: string | null = null\n let hasDefaultExport = false\n const importsFromAst: string[] = []\n\n function visit(node: ts.Node) {\n if (ts.isImportDeclaration(node)) {\n importsFromAst.push(node.getFullText(sourceFile).trim())\n }\n\n if (ts.isClassDeclaration(node)) {\n const decorators = node.modifiers?.filter(ts.isDecorator)\n const componentDecorator = decorators?.find((decorator) => {\n if (!ts.isCallExpression(decorator.expression)) {\n return false\n }\n const expression = decorator.expression.expression\n return ts.isIdentifier(expression) && expression.text === \"Component\"\n })\n\n if (componentDecorator && node.name) {\n componentClass = node.name.text\n\n if (\n ts.isCallExpression(componentDecorator.expression) &&\n componentDecorator.expression.arguments[0] &&\n ts.isObjectLiteralExpression(\n componentDecorator.expression.arguments[0],\n )\n ) {\n const properties =\n componentDecorator.expression.arguments[0].properties\n\n const selectorProp = properties.find(\n (prop) =>\n ts.isPropertyAssignment(prop) &&\n ts.isIdentifier(prop.name) &&\n prop.name.text === \"selector\",\n ) as ts.PropertyAssignment | undefined\n\n if (selectorProp && ts.isStringLiteral(selectorProp.initializer)) {\n selector = selectorProp.initializer.text\n }\n\n const templateUrlProp = properties.find(\n (prop) =>\n ts.isPropertyAssignment(prop) &&\n ts.isIdentifier(prop.name) &&\n prop.name.text === \"templateUrl\",\n ) as ts.PropertyAssignment | undefined\n\n if (templateUrlProp) {\n const init = templateUrlProp.initializer\n if (ts.isStringLiteral(init)) {\n templateUrl = init.text\n } else if (ts.isNoSubstitutionTemplateLiteral(init)) {\n templateUrl = init.text\n }\n }\n\n const standaloneProp = properties.find(\n (prop) =>\n ts.isPropertyAssignment(prop) &&\n ts.isIdentifier(prop.name) &&\n prop.name.text === \"standalone\",\n ) as ts.PropertyAssignment | undefined\n\n if (\n standaloneProp &&\n standaloneProp.initializer.kind === ts.SyntaxKind.FalseKeyword\n ) {\n isStandalone = false\n }\n }\n }\n }\n\n if (ts.isExportAssignment(node) && !node.isExportEquals) {\n hasDefaultExport = true\n }\n\n ts.forEachChild(node, visit)\n }\n\n visit(sourceFile)\n\n return {\n componentClass,\n hasDefaultExport,\n importsFromAst,\n isStandalone,\n selector,\n templateUrl,\n }\n }\n\n interface BuildAngularSourceEntryParams {\n code: string\n fileName: string\n filePath: string\n language: \"angular-ts\" | \"angular-html\"\n }\n\n interface ExtractedSourceCode {\n residualRules?: Map<string, string>\n sourceCodeData: SourceCodeData\n }\n\n async function buildAngularSourceEntry(\n params: BuildAngularSourceEntryParams,\n ): Promise<ExtractedSourceCode> {\n const {code, fileName, filePath, language} = params\n\n const baseResult = await highlightCode(code, language)\n\n let inlineResult: HighlightCodeResult | undefined\n let classesDetected = false\n let residualRules: Map<string, string> | undefined\n\n if (transformTailwindStyles) {\n inlineResult = await highlightCode(code, language, {\n onClassesDetected: (detected) => {\n classesDetected = detected\n },\n onResidualCss: (rules) => {\n residualRules = rules\n },\n })\n }\n\n return {\n residualRules,\n sourceCodeData: {\n fileName,\n filePath,\n highlighted: {\n full: baseResult.full,\n preview: baseResult.preview,\n },\n highlightedInline:\n classesDetected && inlineResult\n ? {\n full: inlineResult.full,\n preview: inlineResult.preview,\n }\n : undefined,\n type: \"file\",\n },\n }\n }\n\n async function maybeBuildTemplateSourceEntry(\n templateUrl: string,\n fromFilePath: string,\n ): Promise<ExtractedSourceCode | null> {\n const templatePath = resolveTemplateFile(templateUrl, fromFilePath)\n if (!existsSync(templatePath)) {\n return null\n }\n\n try {\n const templateCode = await readFile(templatePath, \"utf-8\")\n\n return buildAngularSourceEntry({\n code: templateCode,\n fileName: basename(templatePath),\n filePath: templatePath,\n language: \"angular-html\",\n })\n } catch (error) {\n console.log(\n `${chalk.blue.bold(LOG_PREFIX)} ${chalk.redBright(\"Failed to read template file:\")} ${chalk.cyan(templatePath)}`,\n error,\n )\n return null\n }\n }\n\n async function buildImportedSourceEntries(\n fromFilePath: string,\n ): Promise<ExtractedSourceCode[]> {\n const entries: ExtractedSourceCode[] = []\n const relativeImports = await collectAllImports(fromFilePath)\n\n for (const resolvedPath of relativeImports) {\n try {\n const importedCode = await readFile(resolvedPath, \"utf-8\")\n\n const entry = await buildAngularSourceEntry({\n code: importedCode,\n fileName: basename(resolvedPath),\n filePath: resolvedPath,\n language: \"angular-ts\",\n })\n\n entries.push(entry)\n } catch (error) {\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} ${chalk.yellowBright(\"Failed to process relative import:\")} ${chalk.cyan(resolvedPath)}`,\n )\n }\n }\n\n return entries\n }\n\n function generateRegistryModule(): string {\n const demos = Array.from(demoRegistry.values())\n\n return `// Auto-generated Angular demo registry\nexport const ANGULAR_DEMOS = {\n${demos\n .map(\n (demo) =>\n ` \"${demo.id}\": ${JSON.stringify(\n {\n componentClass: demo.componentClass,\n dimensions: demoDimensionsCache[demo.id],\n filePath: demo.filePath,\n hasDefaultExport: demo.hasDefaultExport,\n id: demo.id,\n imports: demo.imports,\n initialHtml: demo.initialHtml,\n isStandalone: demo.isStandalone,\n lastModified: demo.lastModified,\n selector: demo.selector,\n sourceCode: demo.sourceCode,\n },\n null,\n 4,\n )}`,\n )\n .join(\",\\n\")}\n}\n\nexport function getAngularDemoInfo(demoId) {\n return ANGULAR_DEMOS[demoId] || null\n}`\n }\n\n function isAngularDemoFile(filePath: string): boolean {\n return (\n filePath.includes(\"/demos/\") &&\n (filePath.endsWith(\".ts\") || filePath.endsWith(\"html\"))\n )\n }\n\n function isAngularDemoEntrypoint(filePath: string): boolean {\n return filePath.endsWith(\"-demo.ts\") || filePath.endsWith(\"-demo.html\")\n }\n\n function isCssAsset(filePath: string) {\n return filePath.endsWith(\".css\")\n }\n\n function isRelativeImport(source: string): boolean {\n return source.startsWith(\"./\") || source.startsWith(\"../\")\n }\n\n function isNodeBuiltin(source: string): boolean {\n const NODE_BUILTINS = [\n \"assert\",\n \"buffer\",\n \"child_process\",\n \"cluster\",\n \"crypto\",\n \"dgram\",\n \"dns\",\n \"domain\",\n \"events\",\n \"fs\",\n \"http\",\n \"https\",\n \"net\",\n \"os\",\n \"path\",\n \"punycode\",\n \"querystring\",\n \"readline\",\n \"stream\",\n \"string_decoder\",\n \"timers\",\n \"tls\",\n \"tty\",\n \"url\",\n \"util\",\n \"v8\",\n \"vm\",\n \"zlib\",\n ]\n\n return source.startsWith(\"node:\") || NODE_BUILTINS.includes(source)\n }\n\n function resolveRelativeImport(source: string, fromFile: string): string {\n const fromDir = dirname(fromFile)\n const resolved = resolve(fromDir, source)\n const extensions = [\".ts\", \".js\"]\n\n for (const ext of extensions) {\n const withExt = resolved + ext\n if (existsSync(withExt)) {\n return withExt\n }\n }\n\n for (const ext of extensions) {\n const indexFile = join(resolved, `index${ext}`)\n if (existsSync(indexFile)) {\n return indexFile\n }\n }\n\n return resolved\n }\n\n function loadTsConfigPaths(fromFile: string): PathAlias[] {\n let currentDir = dirname(fromFile)\n const pathAliases: PathAlias[] = []\n\n while (currentDir !== dirname(currentDir)) {\n const tsconfigPath = join(currentDir, \"tsconfig.json\")\n\n if (existsSync(tsconfigPath)) {\n try {\n const configContent = ts.sys.readFile(tsconfigPath)\n if (!configContent) {\n currentDir = dirname(currentDir)\n continue\n }\n\n const parseResult = ts.parseConfigFileTextToJson(\n tsconfigPath,\n configContent,\n )\n\n if (parseResult.error) {\n currentDir = dirname(currentDir)\n continue\n }\n\n const paths = parseResult.config?.compilerOptions?.paths\n const baseUrl = parseResult.config?.compilerOptions?.baseUrl || \"./\"\n const resolvedBaseUrl = resolve(currentDir, baseUrl)\n\n if (paths) {\n for (const [alias, targets] of Object.entries(paths)) {\n if (Array.isArray(targets) && targets.length > 0) {\n const target = targets[0]\n\n const pattern = new RegExp(\n `^${alias\n .replace(\"*\", \"(.*)\")\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(\"\\\\(\\\\*\\\\)\", \"(.*)\")}$`,\n )\n\n const replacement = resolve(\n resolvedBaseUrl,\n target.replace(\"*\", \"$1\"),\n )\n\n pathAliases.push({pattern, replacement})\n }\n }\n }\n\n const extendsPath = parseResult.config?.extends\n if (extendsPath) {\n const resolvedExtends = resolve(currentDir, extendsPath)\n const extendedAliases = loadTsConfigPathsFromFile(resolvedExtends)\n pathAliases.push(...extendedAliases)\n }\n\n return pathAliases\n } catch (error) {\n currentDir = dirname(currentDir)\n continue\n }\n }\n\n currentDir = dirname(currentDir)\n }\n\n return pathAliases\n }\n\n function setupAngularWatcher() {\n watcher = watch(routesDir, {\n ignoreInitial: true,\n persistent: true,\n })\n\n watcher.on(\"ready\", () => {\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} Registered ${chalk.green(demoRegistry.size)} demo files. Watching for file changes...`,\n )\n })\n\n watcher.on(\"add\", (filePath: string) => {\n try {\n const fileStats = statSync(filePath)\n if (!fileStats || fileStats.size === 0) {\n console.debug(\"Failed to read file stats\", filePath)\n return\n }\n\n if (isAngularDemoFile(filePath)) {\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} New Angular demo: ${chalk.green(filePath)}`,\n )\n void handleAngularDemoUpdate(filePath).then(() => {\n triggerRegistryUpdate()\n })\n }\n } catch {\n console.debug(\"Failed to update registry file stats\")\n }\n })\n\n watcher.on(\"unlink\", (filePath: string) => {\n if (isAngularDemoFile(filePath)) {\n const demoEntry = Array.from(demoRegistry.entries()).find(\n ([, info]) => info.filePath === filePath,\n )\n\n if (demoEntry) {\n const [demoId] = demoEntry\n demoRegistry.delete(demoId)\n\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} Removed demo: ${chalk.red(demoId)}`,\n )\n\n triggerRegistryUpdate()\n }\n }\n })\n }\n\n async function handleAngularDemoUpdate(filePath: string) {\n const code = await readFile(filePath, \"utf-8\")\n const demoInfo = await parseAngularDemo(filePath, code)\n\n if (demoInfo) {\n demoRegistry.set(demoInfo.id, demoInfo)\n }\n }\n\n function triggerRegistryUpdate() {\n if (!devServer) {\n return\n }\n\n const mainModule = devServer.moduleGraph.getModuleById(VIRTUAL_MODULE_ID)\n if (mainModule) {\n devServer.moduleGraph.invalidateModule(mainModule)\n mainModule.lastHMRTimestamp = Date.now()\n devServer.reloadModule(mainModule)\n }\n }\n}\n\nfunction loadTsConfigPathsFromFile(tsconfigPath: string): PathAlias[] {\n const pathAliases: PathAlias[] = []\n const configDir = dirname(tsconfigPath)\n\n try {\n const configContent = ts.sys.readFile(tsconfigPath)\n if (!configContent) {\n return pathAliases\n }\n\n const parseResult = ts.parseConfigFileTextToJson(\n tsconfigPath,\n configContent,\n )\n\n if (parseResult.error) {\n return pathAliases\n }\n\n const paths = parseResult.config?.compilerOptions?.paths\n const baseUrl = parseResult.config?.compilerOptions?.baseUrl || \"./\"\n const resolvedBaseUrl = resolve(configDir, baseUrl)\n\n if (paths) {\n for (const [alias, targets] of Object.entries(paths)) {\n if (Array.isArray(targets) && targets.length > 0) {\n const target = targets[0]\n\n const pattern = new RegExp(\n `^${alias\n .replace(\"*\", \"(.*)\")\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(\"\\\\(\\\\*\\\\)\", \"(.*)\")}$`,\n )\n\n const replacement = resolve(\n resolvedBaseUrl,\n target.replace(\"*\", \"$1\"),\n )\n\n pathAliases.push({pattern, replacement})\n }\n }\n }\n\n const extendsPath = parseResult.config?.extends\n if (extendsPath) {\n let resolvedExtends = resolve(configDir, extendsPath)\n\n if (!resolvedExtends.endsWith(\".json\")) {\n resolvedExtends += \".json\"\n }\n\n if (existsSync(resolvedExtends)) {\n const extendedAliases = loadTsConfigPathsFromFile(resolvedExtends)\n pathAliases.push(...extendedAliases)\n }\n }\n } catch {\n return pathAliases\n }\n\n return pathAliases\n}\n\nfunction isPathAliasImport(source: string, pathAliases: PathAlias[]): boolean {\n return pathAliases.some((alias) => alias.pattern.test(source))\n}\n\nfunction resolvePathAlias(\n source: string,\n pathAliases: PathAlias[],\n): string | null {\n for (const alias of pathAliases) {\n if (alias.pattern.test(source)) {\n const resolvedPath = source.replace(alias.pattern, alias.replacement)\n const extensions = [\".ts\", \".js\"]\n\n for (const ext of extensions) {\n const withExt = resolvedPath + ext\n if (existsSync(withExt)) {\n return withExt\n }\n }\n\n for (const ext of extensions) {\n const indexFile = join(resolvedPath, `index${ext}`)\n if (existsSync(indexFile)) {\n return indexFile\n }\n }\n\n return resolvedPath\n }\n }\n\n return null\n}\n\nfunction resolveTemplateFile(templateUrl: string, fromFile: string): string {\n const fromDir = dirname(fromFile)\n const resolved = resolve(fromDir, templateUrl)\n\n if (existsSync(resolved)) {\n return resolved\n }\n\n if (!resolved.endsWith(\".html\")) {\n const withHtml = `${resolved}.html`\n if (existsSync(withHtml)) {\n return withHtml\n }\n }\n\n return resolved\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {type Config, type CosmiconfigResult, cosmiconfigSync} from \"cosmiconfig\"\n\nimport {removeTrailingSlash} from \"../path-utils\"\n\nimport {configSchema} from \"./config-schema\"\nimport type {ResolvedQuiDocsConfig} from \"./types\"\n\ninterface LoadedCosmicConfig {\n config: Config\n filepath: string\n isEmpty?: boolean\n}\n\nexport interface ConfigLoaderOptions {\n /**\n * Path to the qui-docs config file. This is automatically detected if omitted.\n */\n configFile?: string\n}\n\nexport class ConfigLoader {\n private readonly options: ConfigLoaderOptions\n\n constructor(options: ConfigLoaderOptions) {\n this.options = options\n return this\n }\n\n private getCosmiconfig(): LoadedCosmicConfig {\n const explorer = cosmiconfigSync(\"qui-docs\")\n\n const result: CosmiconfigResult | null = this.options.configFile\n ? explorer.load(this.options.configFile)\n : explorer.search()\n\n if (!result) {\n throw new Error(\n \"Config file not found. Please consult the docs at https://docs.qui.qualcomm.com/guide/page-setup#config\",\n )\n }\n\n return result\n }\n\n private resolveConfigFromCosmiconfig(\n config: CosmiconfigResult,\n ): ResolvedQuiDocsConfig {\n const parsed = configSchema.safeParse(config!.config)\n if (!parsed.success) {\n console.dir(parsed.error.issues, {depth: 10})\n throw new Error(\"Failed to parse config file.\")\n }\n const conf = parsed.data\n return {\n ...conf,\n appDirectory: conf.appDirectory || \"app\",\n filePath: config!.filepath,\n pageDirectory: conf.pageDirectory\n ? removeTrailingSlash(conf.pageDirectory)\n : \"routes\",\n }\n }\n\n loadConfig(): ResolvedQuiDocsConfig {\n const config = this.getCosmiconfig()\n return this.resolveConfigFromCosmiconfig(config)\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\n/**\n * Winblows fix\n */\nexport function fixPath(str: string): string {\n return str.replaceAll(\"\\\\\", \"/\")\n}\n\n/**\n * Removes the trailing slash from a string.\n */\nexport function removeTrailingSlash(str: string): string {\n return str.endsWith(\"/\") ? str.substring(0, str.length - 1) : str\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {z, type ZodObject, type ZodSchema} from \"zod\"\n\nimport type {NavMeta, RouteMeta} from \"../nav-builder/types\"\n\nimport type {\n KnowledgeConfig,\n KnowledgeExtraFile,\n OpenWebUiIntegration,\n PagesExportConfig,\n QuiDocsConfig,\n QuiDocsTypeDocOptions,\n SectionExportConfig,\n} from \"./types\"\nimport {implement} from \"./zod\"\n\nexport const navMetaSchema: ZodObject<{}> = implement<NavMeta>().with({\n id: z.never().optional(),\n sectionTitle: z.string().optional(),\n separator: z.boolean().optional(),\n})\n\nexport const routeMetaSchema: ZodSchema<RouteMeta> =\n implement<RouteMeta>().with({\n children: z.array(z.lazy(() => routeMetaSchema)).optional(),\n expanded: z.boolean().optional(),\n group: z.string().optional(),\n groupOrder: z.string().array().optional(),\n hidden: z.boolean().optional(),\n hideBreadcrumbs: z.boolean().optional(),\n hideFromSearch: z.boolean().optional(),\n hidePageLinks: z.boolean().optional(),\n hideSideNav: z.boolean().optional(),\n hideToc: z.boolean().optional(),\n id: z.string(),\n ignoreRouteMetaOrder: z.boolean().optional(),\n restricted: z.boolean().optional(),\n sectionTitle: z.never().optional(),\n separator: z.never().optional(),\n sideNavTitle: z.string().optional(),\n title: z.string().optional(),\n })\n\nconst typeDocPropsSchema = implement<QuiDocsTypeDocOptions>().with({\n includeInSearchIndex: z.boolean().optional(),\n})\n\nconst knowledgeExtraFileSchema = implement<KnowledgeExtraFile>().with({\n contents: z.string(),\n id: z.string(),\n processAsMdx: z.boolean().optional(),\n title: z.string().optional(),\n})\n\nconst frontmatterConfigSchema = z\n .object({\n exclude: z.array(z.string()).optional(),\n include: z.array(z.string()).optional(),\n })\n .optional()\n\nconst pagesExportsSchema = implement<PagesExportConfig>().with({\n outputPath: z.string().optional(),\n})\n\nconst sectionsExportsSchema = implement<SectionExportConfig>().with({\n depths: z.array(z.number()).optional(),\n minContentLength: z.number().optional(),\n outputPath: z.string().optional(),\n})\n\nconst openWebUiIntegrationSchema = implement<OpenWebUiIntegration>().with({\n envFile: z.string().optional(),\n id: z.string(),\n})\n\nconst knowledgeConfigSchema = implement<KnowledgeConfig>().with({\n baseUrl: z.string().optional(),\n exclude: z.array(z.string()).optional(),\n extraFiles: z.array(knowledgeExtraFileSchema).optional(),\n frontmatter: frontmatterConfigSchema,\n integrations: z\n .object({\n openWebUi: z.array(openWebUiIntegrationSchema).optional(),\n })\n .optional(),\n outputPath: z.string().optional(),\n pageIdPrefix: z.string().optional(),\n pages: pagesExportsSchema.optional(),\n sections: sectionsExportsSchema.optional(),\n})\n\nexport const configSchema = implement<QuiDocsConfig>().with({\n appDirectory: z.string().optional(),\n disableCache: z.boolean().optional(),\n headings: z\n .array(\n z.union([\n z.literal(\"h1\"),\n z.literal(\"h2\"),\n z.literal(\"h3\"),\n z.literal(\"h4\"),\n z.literal(\"h5\"),\n z.literal(\"h6\"),\n ]),\n )\n .optional(),\n hotUpdateIgnore: z.instanceof(RegExp).optional(),\n knowledge: knowledgeConfigSchema.optional(),\n navConfig: z.array(z.union([routeMetaSchema, navMetaSchema])).optional(),\n pageDirectory: z.string().optional(),\n pageTimestampMetadata: z\n .union([\n z.literal(\"off\"),\n z.literal(\"timestamp\"),\n z.literal(\"user-and-timestamp\"),\n ])\n .optional(),\n routingStrategy: z.union([z.literal(\"vite-generouted\"), z.any()]).optional(),\n throwOnError: z.boolean().optional(),\n typeDocProps: z.string().optional(),\n typeDocPropsOptions: typeDocPropsSchema.optional(),\n})\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {z} from \"zod\"\n\ntype Implements<Model> = {\n [key in keyof Model]-?: undefined extends Model[key]\n ? null extends Model[key]\n ? z.ZodNullable<z.ZodOptional<z.ZodType<Model[key]>>>\n : z.ZodOptional<z.ZodType<Model[key]>>\n : null extends Model[key]\n ? z.ZodNullable<z.ZodType<Model[key]>>\n : z.ZodType<Model[key]> | z.ZodDefault<z.ZodType<Model[key]>>\n}\n\nexport function implement<Model = never>() {\n return {\n with: <\n Schema extends Implements<Model> & {\n [unknownKey in Exclude<keyof Schema, keyof Model>]: never\n },\n >(\n schema: Schema,\n ) => z.object(schema),\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {join} from \"node:path\"\nimport type {PluginOption, ResolvedConfig} from \"vite\"\n\nimport {dedent} from \"@qualcomm-ui/utils/dedent\"\n\nimport {ConfigLoader} from \"./config/config-loader\"\nimport {fixPath} from \"./path-utils\"\nimport {\n CONFIG_VIRTUAL_MODULE_ID,\n EXPORTS_VIRTUAL_MODULE_ID,\n PLUGIN_VIRTUAL_MODULE_ID,\n PluginState,\n} from \"./plugin-state\"\n\nconst isDev = process.env.NODE_ENV === \"development\"\n\nexport interface QuiDocsPluginOptions {\n /**\n * Path to the qui-docs config file. This is automatically detected if omitted.\n */\n configFile?: string\n\n /**\n * The current working directory.\n *\n * @default process.cwd()\n */\n cwd?: string\n}\n\nconst state = new PluginState()\n\nexport function quiDocsPlugin(opts?: QuiDocsPluginOptions): PluginOption {\n state.init(fixPath(opts?.cwd ?? process.cwd()))\n\n // https://vitejs.dev/guide/api-plugin#virtual-modules-convention\n\n const configLoader = new ConfigLoader(opts || {})\n const config = configLoader.loadConfig()\n state.createIndexer(config)\n\n let viteConfig: ResolvedConfig\n\n function getPublicDir() {\n return viteConfig.publicDir || join(state.getCwd(), \"public\")\n }\n\n return {\n apply(config, env) {\n return (\n (env.mode === \"development\" && env.command === \"serve\") ||\n (env.mode === \"production\" && env.command === \"build\")\n )\n },\n buildStart: async () => {\n state.buildIndex(state.buildCount > 0)\n state.buildCount++\n\n if (!isDev && state.knowledgeConfig) {\n await state.generateKnowledge(getPublicDir())\n }\n },\n configResolved(resolved) {\n viteConfig = resolved\n },\n configureServer: async (server) => {\n if (!isDev) {\n return\n }\n state.initWatchers(opts?.configFile)\n\n if (state.knowledgeConfig) {\n await state.generateKnowledge(getPublicDir())\n }\n\n server.middlewares.use(\"/__qui-docs/pages\", (_req, res) => {\n res.setHeader(\"Content-Type\", \"application/json\")\n res.end(JSON.stringify(state.pages))\n })\n\n server.middlewares.use(\"/__qui-docs/sections\", (_req, res) => {\n res.setHeader(\"Content-Type\", \"application/json\")\n res.end(JSON.stringify(state.sections))\n })\n\n server.watcher.on(\"add\", (path: string) => {\n if (path.endsWith(\".mdx\")) {\n state.handleChange({\n onComplete: () => {\n server.ws.send({type: \"full-reload\"})\n state.debouncedGenerateKnowledge(getPublicDir())\n },\n })\n }\n })\n server.watcher.on(\"unlink\", (path: string) => {\n if (path.endsWith(\".mdx\")) {\n state.handleChange({\n onComplete: () => {\n server.ws.send({type: \"full-reload\"})\n state.debouncedGenerateKnowledge(getPublicDir())\n },\n })\n }\n })\n state.servers.push(server)\n },\n handleHotUpdate: ({file: updateFile, modules, server}) => {\n if (updateFile.endsWith(\".css\")) {\n return modules\n }\n const file = fixPath(updateFile)\n if (\n (!config.hotUpdateIgnore || !config.hotUpdateIgnore.test(file)) &&\n file !== state.configFilePath\n ) {\n if (\n state.docPropsDirectory &&\n file.startsWith(state.docPropsFilePath)\n ) {\n return []\n }\n\n if (updateFile.endsWith(\".mdx\")) {\n state.debouncedGenerateKnowledge(getPublicDir())\n const files = state.buildIndex(true)\n\n const moduleByFile = server.moduleGraph.getModulesByFile(updateFile)\n if (!moduleByFile?.size) {\n console.debug(\"no module found for file, returning\", updateFile)\n return []\n }\n\n const virtualModule = server.moduleGraph.getModuleById(\n PLUGIN_VIRTUAL_MODULE_ID,\n )\n if (virtualModule) {\n server.moduleGraph.invalidateModule(virtualModule)\n\n server.ws.send({\n data: state.siteData,\n event: \"qui-docs-plugin:refresh-site-data\",\n type: \"custom\",\n })\n }\n if (files.some((file) => file.metadata.changed.frontmatter)) {\n console.debug(\n \"Frontmatter changed, reloading plugin to reflect changes in the page configuration\",\n )\n if (virtualModule) {\n server.moduleGraph.invalidateModule(virtualModule)\n }\n server.ws.send({type: \"full-reload\"})\n return []\n }\n return virtualModule ? [virtualModule] : []\n }\n }\n return []\n },\n load: (id): string | undefined => {\n if (id === PLUGIN_VIRTUAL_MODULE_ID) {\n return `export const siteData = ${JSON.stringify(state.siteData)}`\n }\n if (id === CONFIG_VIRTUAL_MODULE_ID) {\n return `export const quiDocsConfig = ${JSON.stringify({...state.config, cwd: state.cwd, publicDir: viteConfig.publicDir})}`\n }\n if (id === EXPORTS_VIRTUAL_MODULE_ID) {\n if (isDev) {\n // serve the sections/pages as middleware for faster updates in dev mode.\n // This prevents the vite dev server from slowing down from frequent,\n // large module invalidations.\n const {host = \"localhost\", port = 5173} = viteConfig.server\n const hostname = host === true ? \"localhost\" : host || \"localhost\"\n const base = `${viteConfig.server.https ? \"https\" : \"http\"}://${hostname}:${port}`\n return dedent`\n export const getSections = () => fetch('${base}/__qui-docs/sections').then(r => r.json())\n export const getPages = () => fetch('${base}/__qui-docs/pages').then(r => r.json())\n `\n }\n return dedent`\n export const getSections = () => Promise.resolve(${JSON.stringify(state.sections)})\n export const getPages = () => Promise.resolve(${JSON.stringify(state.pages)})\n `\n }\n return undefined\n },\n name: \"qui-mdx-vite-plugin\",\n resolveId: (id) => {\n if (id === PLUGIN_VIRTUAL_MODULE_ID.substring(1)) {\n return PLUGIN_VIRTUAL_MODULE_ID\n }\n if (id === CONFIG_VIRTUAL_MODULE_ID.substring(1)) {\n return CONFIG_VIRTUAL_MODULE_ID\n }\n if (id === EXPORTS_VIRTUAL_MODULE_ID.substring(1)) {\n return EXPORTS_VIRTUAL_MODULE_ID\n }\n return undefined\n },\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport chalk from \"chalk\"\nimport chokidar from \"chokidar\"\nimport {glob} from \"glob\"\nimport {readFileSync} from \"node:fs\"\nimport {mkdir, writeFile} from \"node:fs/promises\"\nimport {join, resolve} from \"node:path\"\nimport prettyMilliseconds from \"pretty-ms\"\nimport type {ViteDevServer} from \"vite\"\n\nimport type {\n KnowledgePages,\n KnowledgeSections,\n PageDocProps,\n SiteData,\n} from \"@qualcomm-ui/mdx-common\"\nimport type {QuiPropTypes} from \"@qualcomm-ui/typedoc-common\"\n\nimport type {ResolvedQuiDocsConfig} from \"./config\"\nimport {ConfigLoader} from \"./config/config-loader\"\nimport {type CompiledMdxFile, MdxFileReader} from \"./markdown\"\nimport {KnowledgeExporter} from \"./markdown/knowledge\"\nimport {fixPath} from \"./path-utils\"\nimport {SearchIndexer} from \"./search-indexer\"\n\nconst isDev = process.env.NODE_ENV === \"development\"\n\n// TODO: deprecate and rename to @qualcomm-ui/docs-plugin/site-data\nexport const PLUGIN_VIRTUAL_MODULE_ID = \"\\0@qualcomm-ui/mdx-vite-plugin\"\nexport const CONFIG_VIRTUAL_MODULE_ID = \"\\0@qualcomm-ui/docs-plugin/config\"\nexport const EXPORTS_VIRTUAL_MODULE_ID =\n \"\\0@qualcomm-ui/docs-plugin/markdown-content\"\n\nexport interface ChangeOptions {\n onComplete?: () => void\n}\n\nexport interface ExportsState {\n dir: string\n enabled: boolean\n pathnames: string[]\n}\n\n/**\n * TODO: adjust when https://github.com/vitejs/vite/discussions/16358 lands.\n */\nexport class PluginState {\n buildCount: number = 0\n config: ResolvedQuiDocsConfig | null = null\n configFilePath: string = \"\"\n docPropsFilePath: string = \"\"\n exports: ExportsState = {dir: \"\", enabled: false, pathnames: []}\n indexer!: SearchIndexer\n configLoader: ConfigLoader | null = null\n knowledgeConfig: ResolvedQuiDocsConfig[\"knowledge\"] = undefined\n pages: KnowledgePages | null = null\n sections: KnowledgeSections | null = null\n routesDir!: string\n servers: ViteDevServer[] = []\n timeout: ReturnType<typeof setTimeout> | undefined = undefined\n exportsTimeout: ReturnType<typeof setTimeout> | undefined = undefined\n watching = false\n\n cwd!: string\n\n init(cwd: string) {\n this.cwd = cwd\n }\n\n getCwd() {\n return this.cwd\n }\n\n get docPropsDirectory() {\n if (!this.docPropsFilePath) {\n return \"\"\n }\n return this.docPropsFilePath.substring(\n 0,\n this.docPropsFilePath.lastIndexOf(\"/\"),\n )\n }\n\n get siteData(): SiteData & {\n config: Omit<ResolvedQuiDocsConfig, \"filePath\">\n exports: ExportsState\n } {\n const {filePath: _filePath, ...config} =\n this.config ?? ({} as ResolvedQuiDocsConfig)\n return {\n config,\n exports: this.exports,\n navItems: this.indexer.navItems,\n pageDocProps: this.indexer.pageDocProps as unknown as PageDocProps,\n pageMap: this.indexer.pageMap,\n searchIndex: this.indexer.searchIndex,\n }\n }\n\n private resolveDocProps(): Record<string, QuiPropTypes> {\n if (!this.docPropsFilePath) {\n return {}\n }\n try {\n return JSON.parse(readFileSync(this.docPropsFilePath, \"utf-8\"))?.props\n } catch (e) {\n console.debug(\n \"Invalid doc props file. Unable to parse JSON. Please check the file\",\n )\n return {}\n }\n }\n\n createIndexer(config: ResolvedQuiDocsConfig) {\n this.config = config\n this.configFilePath = config.filePath\n this.docPropsFilePath = config.typeDocProps\n ? fixPath(resolve(this.cwd, config.typeDocProps))\n : \"\"\n this.routesDir = fixPath(resolve(config.appDirectory, config.pageDirectory))\n this.knowledgeConfig = config.knowledge\n this.indexer = new SearchIndexer({\n ...config,\n srcDir: fixPath(resolve(this.cwd, config.appDirectory)),\n typeDocProps: this.resolveDocProps(),\n })\n\n const knowledgeEnabled = !!config.knowledge\n const outputPath = config.knowledge?.outputPath ?? \"exports\"\n this.exports = {\n dir: knowledgeEnabled ? `/${outputPath}` : \"\",\n enabled: knowledgeEnabled,\n pathnames: [],\n }\n }\n\n buildIndex(shouldLog: boolean): CompiledMdxFile[] {\n const files = glob.sync(\n [`${this.routesDir}/**/*.mdx`, `${this.routesDir}/**/*.tsx`],\n {\n absolute: true,\n cwd: this.cwd,\n },\n )\n\n if (!files.length) {\n return []\n }\n\n const startTime = Date.now()\n\n const compiledMdxFiles = this.indexer.buildIndex(files, shouldLog)\n\n if (isDev && shouldLog) {\n console.debug(\n `${chalk.magenta.bold(`@qualcomm-ui/mdx-vite/docs-plugin:`)} Compiled search index in: ${chalk.blueBright.bold(prettyMilliseconds(Date.now() - startTime))}${this.indexer.cachedFileCount ? chalk.greenBright.bold(` (${this.indexer.cachedFileCount}/${this.indexer.mdxFileCount} files cached)`) : \"\"}`,\n )\n }\n\n return compiledMdxFiles\n }\n\n sendUpdate() {\n for (const server of this.servers) {\n const virtualModule = server.moduleGraph.getModuleById(\n PLUGIN_VIRTUAL_MODULE_ID,\n )\n if (virtualModule) {\n server.moduleGraph.invalidateModule(virtualModule)\n server.reloadModule(virtualModule)\n }\n }\n }\n\n handleChange(opts: ChangeOptions = {}) {\n clearTimeout(this.timeout)\n this.timeout = setTimeout(() => {\n this.buildIndex(true)\n this.sendUpdate()\n opts?.onComplete?.()\n }, 300)\n }\n\n initWatchers(configFile?: string) {\n if (this.watching) {\n return\n }\n this.initConfigWatcher(configFile)\n this.watching = true\n }\n\n private initConfigWatcher(configFile?: string) {\n const paths: string[] = [this.configFilePath]\n if (this.docPropsFilePath) {\n paths.push(this.docPropsFilePath)\n }\n chokidar\n .watch(paths, {\n cwd: this.cwd,\n })\n .on(\"change\", () => {\n console.debug(`qui-docs config changed, reloading plugin`)\n this.configLoader = new ConfigLoader({configFile})\n const resolvedConfig = this.configLoader.loadConfig()\n this.configFilePath = resolvedConfig.filePath\n this.createIndexer(resolvedConfig)\n this.handleChange({\n onComplete: () => {\n this.servers.forEach((server) =>\n server.ws.send({type: \"full-reload\"}),\n )\n },\n })\n })\n }\n\n async generateKnowledge(publicDir: string): Promise<void> {\n if (!this.knowledgeConfig) {\n return\n }\n\n const outputDir = join(\n publicDir,\n this.knowledgeConfig.outputPath ?? \"exports\",\n )\n const startTime = Date.now()\n\n const fileReader = new MdxFileReader(false)\n const exporter = new KnowledgeExporter(\n {\n baseUrl: this.knowledgeConfig.baseUrl,\n docPropsPath: this.docPropsFilePath || undefined,\n exclude: this.knowledgeConfig.exclude,\n extraFiles: this.knowledgeConfig.extraFiles,\n frontmatter: this.knowledgeConfig.frontmatter,\n pageIdPrefix: this.knowledgeConfig.pageIdPrefix,\n pages: this.knowledgeConfig.pages,\n routeDir: this.routesDir,\n sections: this.knowledgeConfig.sections,\n },\n fileReader,\n )\n\n const result = await exporter.generate()\n this.pages = result.pages\n this.sections = result.sections\n\n await mkdir(outputDir, {recursive: true})\n await writeFile(\n join(outputDir, \"sections.json\"),\n JSON.stringify(result.sections, null, 2),\n \"utf-8\",\n )\n await writeFile(\n join(outputDir, \"pages.json\"),\n JSON.stringify(result.pages, null, 2),\n \"utf-8\",\n )\n\n this.exports.pathnames = result.pages.pages.map((p) => p.pathname)\n\n console.debug(\n `${chalk.magenta.bold(`@qualcomm-ui/mdx-vite/docs-plugin:`)} Generated knowledge exports in: ${chalk.blueBright.bold(prettyMilliseconds(Date.now() - startTime))}`,\n )\n }\n\n debouncedGenerateKnowledge(\n publicDir: string,\n opts: {onDone?: () => void} = {},\n ): void {\n if (!this.knowledgeConfig) {\n return\n }\n clearTimeout(this.exportsTimeout)\n this.exportsTimeout = setTimeout(() => {\n void this.generateKnowledge(publicDir).then(() => {\n opts.onDone?.()\n })\n }, 500)\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\n/**\n * Converts heading text to a URL-friendly slug. Handles multi-word text,\n * PascalCase identifiers, and single lowercase words. Does NOT deduplicate \u2014\n * callers manage their own counter state via {@link SlugGenerator}.\n */\nexport function slugify(text: string): string {\n const cleaned = text\n .replace(/[<>]/g, \"\")\n .replace(/[^\\w\\s-]/g, \"\")\n .trim()\n\n if (cleaned.includes(\" \")) {\n return cleaned\n .toLowerCase()\n .replace(/\\s+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n }\n\n // PascalCase \u2192 kebab-case (e.g. \"MyComponent\" \u2192 \"my-component\")\n if ((cleaned.match(/[A-Z]/g) || []).length >= 2) {\n return cleaned\n .replace(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1-$2\")\n .toLowerCase()\n }\n\n return cleaned.toLowerCase()\n}\n\n/**\n * Stateful slug generator that appends `-1`, `-2`, etc. for duplicate slugs\n * within a single page/document scope.\n */\nexport class SlugGenerator {\n private seenIds = new Map<string, number>()\n\n reset(): void {\n this.seenIds.clear()\n }\n\n createSlug(text: string): string {\n const slug = slugify(text)\n const count = this.seenIds.get(slug) || 0\n this.seenIds.set(slug, count + 1)\n return count > 0 ? `${slug}-${count}` : slug\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport chalk from \"chalk\"\nimport {execSync} from \"node:child_process\"\nimport {createHash} from \"node:crypto\"\nimport {readFileSync} from \"node:fs\"\nimport {resolve} from \"node:path\"\nimport remarkFrontmatter from \"remark-frontmatter\"\nimport remarkParse from \"remark-parse\"\nimport remarkParseFrontmatter from \"remark-parse-frontmatter\"\nimport remarkStringify from \"remark-stringify\"\nimport {unified} from \"unified\"\n\nimport type {PageFrontmatter} from \"@qualcomm-ui/mdx-common\"\nimport type {QuiPropTypes} from \"@qualcomm-ui/typedoc-common\"\n\nimport type {PageTimestampMetadataMode} from \"../config\"\n\nimport {frontmatterSchema} from \"./frontmatter-schema\"\nimport type {IndexedPage, IndexedSection} from \"./markdown.types\"\n\nexport interface GitMetadata {\n updatedBy?: string\n updatedOn?: string\n}\n\n/**\n * Runs a single git log command to collect the last commit metadata for all\n * MDX files under srcDir. Returns a map keyed by absolute file path.\n */\nexport function buildGitMetadataMap(\n srcDir: string,\n mode: PageTimestampMetadataMode,\n): Map<string, GitMetadata> {\n const map = new Map<string, GitMetadata>()\n if (mode === \"off\") {\n return map\n }\n\n try {\n const repoRoot = execSync(\"git rev-parse --show-toplevel\", {\n encoding: \"utf-8\",\n }).trim()\n\n const format = mode === \"user-and-timestamp\" ? \"%cI%x09%aN\" : \"%cI\"\n const output = execSync(\n `git log --format=\"COMMIT%x09${format}\" --name-only -- \"${srcDir}/**/*.mdx\"`,\n {encoding: \"utf-8\", stdio: [\"pipe\", \"pipe\", \"pipe\"]},\n )\n\n let currentMetadata: GitMetadata = {}\n\n for (const line of output.split(\"\\n\")) {\n if (line.startsWith(\"COMMIT\\t\")) {\n const parts = line.split(\"\\t\")\n currentMetadata =\n mode === \"user-and-timestamp\"\n ? {updatedBy: parts[2], updatedOn: parts[1]}\n : {updatedOn: parts[1]}\n } else if (line.trim()) {\n const absolutePath = resolve(repoRoot, line.trim())\n if (!map.has(absolutePath)) {\n map.set(absolutePath, currentMetadata)\n }\n }\n }\n } catch {\n // git unavailable \u2014 return empty map\n }\n\n return map\n}\n\ninterface PageCache {\n frontmatter: PageFrontmatter\n md5: string\n page: IndexedPage\n pageDocProps: Record<string, QuiPropTypes>\n pageDocPropSections: IndexedSection[]\n}\n\nexport class MdxFileReader {\n cachedFileCount = 0\n gitMetadataMap: Map<string, GitMetadata> = new Map()\n logWarnings = true\n private mdxCache: Record<string, PageCache> = {}\n\n constructor(\n public enabled: boolean,\n public pageTimestampMetadata: PageTimestampMetadataMode = \"off\",\n ) {}\n\n private hash(input: string) {\n return createHash(\"md5\").update(input).digest(\"hex\")\n }\n\n reset(): void {\n this.cachedFileCount = 0\n }\n\n readCache(filePath: string): PageCache | null {\n return this.mdxCache[filePath] || null\n }\n\n private checkCache(\n filePath: string,\n fileContents: string,\n ): Omit<PageCache, \"md5\"> | undefined {\n if (!this.enabled) {\n return\n }\n\n const fileMd5 = this.hash(fileContents)\n const cached = this.mdxCache[filePath]\n\n if (cached?.md5 !== fileMd5) {\n return\n }\n\n this.cachedFileCount++\n\n return {\n frontmatter: cached.frontmatter,\n page: cached.page,\n pageDocProps: cached.pageDocProps,\n pageDocPropSections: cached.pageDocPropSections,\n }\n }\n\n private parseFrontmatter(\n filepath: string,\n fileContents: string,\n cachedFrontmatter?: PageFrontmatter,\n ): PageFrontmatter {\n let file:\n | {data: {frontmatter: PageFrontmatter}}\n | ReturnType<typeof unified.processSync>\n if (cachedFrontmatter) {\n file = {data: {frontmatter: cachedFrontmatter}}\n } else {\n // Only parse the YAML section \u2014 we just need the frontmatter at this stage.\n const yamlSection = fileContents.substring(\n 0,\n fileContents.indexOf(\"\\n---\") + 4,\n )\n file = unified()\n .use(remarkParse)\n .use(remarkFrontmatter, [\"yaml\"])\n .use(remarkParseFrontmatter)\n .use(remarkStringify)\n .processSync(yamlSection)\n }\n\n const frontmatter: PageFrontmatter = (file.data\n .frontmatter as PageFrontmatter) ?? {title: \"\"}\n\n if (!frontmatter.title) {\n const lines = fileContents.split(\"\\n\")\n const fallbackTitle = lines.find((line) => line.startsWith(\"# \"))\n if (fallbackTitle) {\n frontmatter.title = fallbackTitle.substring(2).trim()\n }\n }\n // TODO: permit omitting title from frontmatter if provided in the navConfig\n if (!frontmatter.title && this.logWarnings) {\n console.debug(chalk.red.bold(\"Missing title:\"), filepath)\n }\n\n const parsedFrontmatter = frontmatterSchema.safeParse(frontmatter)\n\n if (!parsedFrontmatter.success) {\n console.debug(\n `${chalk.redBright.bold(\"Invalid frontmatter detected for file\")}: ${filepath}\\n`,\n )\n console.debug(chalk.redBright.bold(\"Please check the following fields:\"))\n parsedFrontmatter.error.issues.map((issue: any) => {\n console.debug(`- ${issue.path.join(\".\")}`)\n })\n }\n\n return frontmatter\n }\n\n private enrichWithGitMetadata(\n filepath: string,\n frontmatter: PageFrontmatter,\n cached: Omit<PageCache, \"md5\"> | undefined,\n ): void {\n // In dev mode, only fetch git metadata for new files (not in cache).\n // For file updates, reuse cached git metadata to avoid repeated git calls.\n // In production mode, always fetch fresh git metadata.\n const existingCache = this.mdxCache[filepath]\n const shouldFetchGitMetadata = !this.enabled || !existingCache\n\n if (shouldFetchGitMetadata) {\n const gitMetadata = this.gitMetadataMap.get(filepath) ?? {}\n if (!frontmatter.updatedOn && gitMetadata.updatedOn) {\n frontmatter.updatedOn = gitMetadata.updatedOn\n }\n if (!frontmatter.updatedBy && gitMetadata.updatedBy) {\n frontmatter.updatedBy = gitMetadata.updatedBy\n }\n } else if (!cached && existingCache) {\n if (!frontmatter.updatedOn && existingCache.frontmatter.updatedOn) {\n frontmatter.updatedOn = existingCache.frontmatter.updatedOn\n }\n if (!frontmatter.updatedBy && existingCache.frontmatter.updatedBy) {\n frontmatter.updatedBy = existingCache.frontmatter.updatedBy\n }\n }\n }\n\n /**\n * Synchronous file read with MD5 caching and git metadata enrichment.\n * Used by the search indexer on every HMR update.\n */\n readFileSync(filepath: string): {\n cached: Omit<PageCache, \"md5\"> | undefined\n fileContents: string\n frontmatter: PageFrontmatter\n } {\n const fileContents = readFileSync(filepath, \"utf-8\")\n const cached = this.checkCache(filepath, fileContents)\n const frontmatter = this.parseFrontmatter(\n filepath,\n fileContents,\n cached?.frontmatter,\n )\n this.enrichWithGitMetadata(filepath, frontmatter, cached)\n return {cached, fileContents, frontmatter}\n }\n\n updateCache(\n filepath: string,\n fileContents: string,\n cacheData: Omit<PageCache, \"md5\">,\n ): void {\n if (this.enabled) {\n this.mdxCache[filepath] = {...cacheData, md5: this.hash(fileContents)}\n }\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {z, type ZodObject} from \"zod\"\n\nimport type {PageFrontmatter} from \"@qualcomm-ui/mdx-common\"\n\nimport {implement} from \"../config/zod\"\n\n/**\n * Used to validate the MDX frontmatter and emit warnings for pages that violate the\n * schema.\n */\nexport const frontmatterSchema: ZodObject<{}> =\n implement<PageFrontmatter>().with({\n categories: z.string().array().optional(),\n description: z.string().optional(),\n group: z.string().optional(),\n hidden: z.boolean().optional(),\n hideBreadcrumbs: z.boolean().optional(),\n hideFromSearch: z.boolean().optional(),\n hidePageLinks: z.boolean().optional(),\n hideSideNav: z.boolean().optional(),\n hideToc: z.boolean().optional(),\n id: z.string().optional(),\n restricted: z.boolean().optional(),\n sideNavTitle: z.string().optional(),\n title: z.string(),\n updatedBy: z.string().optional(),\n updatedOn: z.string().optional(),\n })\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {MdxJsxAttribute} from \"mdast-util-mdx-jsx\"\n\nexport function extractNamesFromAttribute(attr: MdxJsxAttribute): string[] {\n if (!attr.value) {\n return []\n }\n\n if (typeof attr.value === \"string\") {\n return [attr.value]\n }\n\n if (attr.value.type === \"mdxJsxAttributeValueExpression\") {\n const estree = attr.value.data?.estree\n if (!estree?.body?.[0] || estree.body[0].type !== \"ExpressionStatement\") {\n return []\n }\n\n const expression = estree.body[0].expression\n\n if (expression.type === \"ArrayExpression\") {\n const names: string[] = []\n for (const element of expression.elements) {\n if (element?.type === \"Literal\" && typeof element.value === \"string\") {\n names.push(element.value)\n }\n }\n return names\n }\n\n // Handle single string expression\n if (expression.type === \"Literal\" && typeof expression.value === \"string\") {\n return [expression.value]\n }\n }\n\n return []\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport remarkFrontmatter from \"remark-frontmatter\"\nimport remarkGfm from \"remark-gfm\"\nimport remarkMdx from \"remark-mdx\"\nimport remarkParse from \"remark-parse\"\nimport remarkStringify from \"remark-stringify\"\nimport {type PluggableList, type Processor, unified} from \"unified\"\n\nimport type {PageFrontmatter} from \"@qualcomm-ui/mdx-common\"\n\nimport {\n remarkAlerts,\n remarkExtractMeta,\n remarkFrontmatterInterpolation,\n remarkRemoveJsx,\n remarkRemoveMermaidCodeBlocks,\n} from \"../remark\"\n\nexport interface RemarkPipelineOptions {\n /** GitHub-style alert blocks. */\n alerts?: boolean\n /**\n * Strip :::meta::: and :::terms::: blocks, storing extracted data in the provided\n * object.\n */\n extractMeta?: Record<string, string | string[]>\n /** Include remarkFrontmatter for YAML front matter. */\n frontmatter?: boolean\n /** Include remarkGfm for GitHub Flavored Markdown. */\n gfm?: boolean\n /** Interpolate {frontmatter.*} expressions in the content. */\n interpolateFrontmatter?: PageFrontmatter\n /** Include remarkMdx for MDX parsing. */\n mdx?: boolean\n /**\n * \"md\" appends remarkStringify; \"none\" (default) leaves serialization to the\n * caller.\n */\n output?: \"md\" | \"none\"\n /** Additional remark plugins appended after built-in transforms. */\n plugins?: PluggableList\n /** Strip JSX/MDX elements from the AST. */\n removeJsx?: boolean\n /** Remove mermaid code blocks. */\n removeMermaidCodeBlocks?: boolean\n}\n\n/**\n * Creates a configured unified remark processor. The caller can further extend\n * the returned processor with `.use()` (e.g. to add remarkRehype for HTML output).\n */\nexport function createRemarkProcessor(\n options: RemarkPipelineOptions = {},\n): Processor<any> {\n const processor = unified().use(remarkParse)\n\n if (options.mdx) {\n processor.use(remarkMdx)\n }\n if (options.frontmatter) {\n processor.use(remarkFrontmatter, [\"yaml\"])\n }\n\n // Transform plugins \u2014 order matters\n if (options.removeJsx) {\n processor.use(remarkRemoveJsx)\n }\n if (options.removeMermaidCodeBlocks) {\n processor.use(remarkRemoveMermaidCodeBlocks)\n }\n if (options.gfm) {\n processor.use(remarkGfm)\n }\n if (options.alerts) {\n processor.use(remarkAlerts)\n }\n if (options.interpolateFrontmatter) {\n processor.use(\n remarkFrontmatterInterpolation,\n options.interpolateFrontmatter,\n )\n }\n if (options.extractMeta) {\n processor.use(remarkExtractMeta, options.extractMeta)\n }\n\n if (options.plugins) {\n for (const plugin of options.plugins) {\n if (Array.isArray(plugin)) {\n processor.use(...plugin)\n } else {\n // @ts-expect-error mdast types\n processor.use(plugin)\n }\n }\n }\n\n if (options.output === \"md\") {\n processor.use(remarkStringify)\n }\n\n return processor\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {PhrasingContent, Root} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nconst alertLegacyRegex = /^\\[!(NOTE|TIP|SUCCESS|WARNING|CAUTION)(\\/.*)?\\]/i\n\n/**\n * Alerts are a Markdown extension based on the blockquote syntax that you can use\n * to emphasize critical information. On GitHub, they are displayed with distinctive\n * colors and icons to indicate the significance of the content.\n * https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#alerts\n */\nexport const remarkAlerts: Plugin<[], Root> = () => {\n return (tree) => {\n visit(tree, \"blockquote\", (node) => {\n let alertType = \"\"\n let title = \"\"\n let isNext = true\n const child = node.children.map((item) => {\n if (isNext && item.type === \"paragraph\") {\n const firstNode = item.children[0]\n const text = firstNode.type === \"text\" ? firstNode.value : \"\"\n const reg = alertLegacyRegex\n const match = text.match(reg)\n if (match) {\n isNext = false\n alertType = match[1].toLocaleLowerCase()\n title = match[2] || alertType.toLocaleUpperCase()\n if (text.includes(\"\\n\")) {\n item.children[0] = {\n type: \"text\",\n value: text.replace(reg, \"\").replace(/^\\n+/, \"\"),\n }\n }\n\n if (!text.includes(\"\\n\")) {\n const itemChild: PhrasingContent[] = []\n item.children.forEach((item: any, idx: number) => {\n if (idx === 0) {\n return\n }\n if (idx === 1 && item.type === \"break\") {\n return\n }\n itemChild.push(item)\n })\n item.children = [...itemChild]\n }\n }\n }\n return item\n })\n\n title = title.replace(/^\\//, \"\")\n\n if (!!alertType) {\n node.data = {\n hName: \"div\",\n hProperties: {\n class: `qui-notification__root`,\n \"data-emphasis\":\n alertToEmphasis[alertType as IconType] || \"neutral\",\n \"data-orientation\": \"vertical\",\n dir: \"auto\",\n },\n }\n node.children = [\n {\n children: [getAlertIcon(alertType as IconType)],\n data: {\n hProperties: {\n class: \"qui-notification__icon\",\n \"data-part\": \"status-icon\",\n \"data-scope\": \"inline-notification\",\n },\n },\n type: \"paragraph\",\n },\n {\n children: [\n {\n type: \"text\",\n value: title,\n },\n ],\n data: {\n hProperties: {\n class: \"qui-notification__label\",\n dir: \"auto\",\n },\n },\n type: \"paragraph\",\n },\n {\n children: child,\n data: {\n hName: \"div\",\n hProperties: {\n class: `qui-notification__description`,\n dir: \"auto\",\n },\n },\n type: \"blockquote\",\n },\n ]\n }\n })\n }\n}\n\nexport function getAlertIcon(type: IconType): PhrasingContent {\n const svgChildren = svgData[type] ?? []\n return {\n children: svgChildren,\n data: {\n hName: \"svg\",\n hProperties: {\n ariaHidden: \"true\",\n class: \"lucide\",\n fill: \"transparent\",\n height: \"20\",\n stroke: \"currentColor\",\n strokeLinecap: \"round\",\n strokeLinejoin: \"round\",\n strokeWidth: \"2\",\n viewBox: \"0 0 24 24\",\n width: \"20\",\n },\n },\n type: \"emphasis\",\n }\n}\n\ntype IconType = \"note\" | \"tip\" | \"success\" | \"warning\" | \"caution\"\n\n/**\n * These SVG children correspond to the lucide icons matching our\n * {@link https://react.qui.qualcomm.com/components/inline-alert | Alert} component.\n */\nconst svgData: Record<IconType, PhrasingContent[]> = {\n caution: [\n {\n children: [],\n data: {\n hName: \"polygon\",\n hProperties: {\n points:\n \"7.86 2 16.14 2 22 7.86 22 16.14 16.14 22 7.86 22 2 16.14 2 7.86 7.86 2\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"line\",\n hProperties: {\n x1: \"12\",\n x2: \"12\",\n y1: \"8\",\n y2: \"12\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"line\",\n hProperties: {\n x1: \"12\",\n x2: \"12.01\",\n y1: \"16\",\n y2: \"16\",\n },\n },\n type: \"emphasis\",\n },\n ],\n note: [\n {\n children: [],\n data: {\n hName: \"circle\",\n hProperties: {\n cx: \"12\",\n cy: \"12\",\n r: \"10\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M12 16v-4\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M12 8h.01\",\n },\n },\n type: \"emphasis\",\n },\n ],\n success: [\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M20 6 9 17l-5-5\",\n },\n },\n type: \"emphasis\",\n },\n ],\n tip: [\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M9 18h6\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M10 22h4\",\n },\n },\n type: \"emphasis\",\n },\n ],\n warning: [\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M12 9v4\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M12 17h.01\",\n },\n },\n type: \"emphasis\",\n },\n ],\n}\n\nconst alertToEmphasis: Record<IconType, string> = {\n caution: \"danger\",\n note: \"neutral\",\n success: \"success\",\n tip: \"info\",\n warning: \"warning\",\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Code, Parent, Root} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\ninterface Tab {\n index: number\n label: string\n meta: string | undefined\n tabsGroup: string\n}\n\nfunction parseTabAttributes(meta: string): {\n label: string | null\n remainingMeta: string\n tabsGroup: string | null\n} {\n if (!meta) {\n return {label: null, remainingMeta: \"\", tabsGroup: null}\n }\n\n const tabsMatch = meta.match(/tabs=[\"']([^\"']+)[\"']|tabs=(\\S+)/)\n const labelMatch = meta.match(/label=[\"']([^\"']+)[\"']|label=(\\S+)/)\n\n const tabsGroup = tabsMatch ? tabsMatch[1] || tabsMatch[2] : null\n const label = labelMatch ? labelMatch[1] || labelMatch[2] : null\n\n // Remove both tabs and label attributes from meta\n const remainingMeta = meta\n .replace(/\\s*tabs=[\"']([^\"']+)[\"']/g, \"\")\n .replace(/\\s*tabs=(\\S+)/g, \"\")\n .replace(/\\s*label=[\"']([^\"']+)[\"']/g, \"\")\n .replace(/\\s*label=(\\S+)/g, \"\")\n .trim()\n\n return {label, remainingMeta, tabsGroup}\n}\n\nfunction findConsecutiveTabs(\n startIndex: number,\n parent: Parent,\n targetTabsGroup: string,\n): Tab[] {\n const tabs: Tab[] = []\n let currentIndex = startIndex\n\n while (currentIndex < parent.children.length) {\n const currentNode = parent.children[currentIndex]\n\n if (!currentNode || currentNode.type !== \"code\") {\n break\n }\n\n const codeNode = currentNode\n\n if (!codeNode.meta) {\n break\n }\n\n const {label, remainingMeta, tabsGroup} = parseTabAttributes(codeNode.meta)\n\n // Only include if it matches the target tabs group and has a label\n if (!tabsGroup || !label || tabsGroup !== targetTabsGroup) {\n break\n }\n\n // Clean the original node's meta NOW\n codeNode.meta = remainingMeta || undefined\n\n tabs.push({\n index: currentIndex,\n label,\n meta: remainingMeta || undefined,\n tabsGroup,\n })\n\n if (remainingMeta && remainingMeta.includes(\"end\")) {\n break\n }\n\n currentIndex++\n }\n\n return tabs\n}\n\nfunction renderTabs(tabs: Tab[], parent: Parent): any[] {\n const tabsContainer = {\n attributes: [],\n children: [] as any[],\n name: \"CodeTabs\",\n type: \"mdxJsxFlowElement\",\n }\n\n tabs.forEach((tab) => {\n const codeNode = parent.children[tab.index] as Code\n\n const tabAttributes = [\n {\n name: \"label\",\n type: \"mdxJsxAttribute\",\n value: tab.label,\n },\n ]\n\n // Add meta to JSX element if it exists\n if (tab.meta) {\n tabAttributes.push({\n name: \"meta\",\n type: \"mdxJsxAttribute\",\n value: tab.meta,\n })\n }\n\n const tabElement = {\n attributes: tabAttributes,\n children: [\n {\n lang: codeNode.lang,\n meta: codeNode.meta, // This is now clean\n type: \"code\",\n value: codeNode.value,\n },\n ],\n name: \"CodeTab\",\n type: \"mdxJsxFlowElement\",\n }\n\n tabsContainer.children.push(tabElement)\n })\n\n return [tabsContainer]\n}\n\n/**\n * Very cool. TODO: document this https://docs.qui.qualcomm.com/guide/markdown\n *\n * @example\n * ```angular-html tabs=\"demo\" label=\"HTML\"\n * <div class=\"w-72\" q-text-input [invalid]=\"!value()\" [(ngModel)]=\"value\">\n * <label q-text-input-label>Label</label>\n * <input placeholder=\"Enter a value\" q-text-input-input />\n * <div q-text-input-error-text>You must enter a value</div>\n * </div>\n * ```\n *\n * ```angular-ts tabs=\"demo\" label=\"TS\"\n * @Component()\n * export class DemoComponent {\n * readonly value = signal(\"\")\n * }\n * ```\n */\nexport const remarkCodeTabs: Plugin<[], Root> = () => {\n return (tree) => {\n const transformations: Array<{\n endIndex: number\n parent: Parent\n replacement: any[]\n startIndex: number\n }> = []\n\n visit(\n tree,\n \"code\",\n (node: Code, index: number | undefined, parent: Parent | undefined) => {\n if (!node.meta || !parent || index === undefined) {\n return\n }\n\n const {label, tabsGroup} = parseTabAttributes(node.meta)\n if (!tabsGroup || !label) {\n return\n }\n\n const alreadyProcessed = transformations.some(\n (t) =>\n t.parent === parent && index >= t.startIndex && index < t.endIndex,\n )\n\n if (alreadyProcessed) {\n return\n }\n\n const tabs = findConsecutiveTabs(index, parent, tabsGroup)\n\n if (tabs.length > 1) {\n const startIndex = tabs[0].index\n const endIndex = tabs[tabs.length - 1].index + 1\n const newChildren = renderTabs(tabs, parent)\n\n transformations.push({\n endIndex,\n parent,\n replacement: newChildren,\n startIndex,\n })\n }\n },\n )\n\n transformations\n .sort((a, b) => b.startIndex - a.startIndex)\n .forEach((transformation) => {\n transformation.parent.children.splice(\n transformation.startIndex,\n transformation.endIndex - transformation.startIndex,\n ...transformation.replacement,\n )\n })\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Parent, Root} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {SKIP, visit} from \"unist-util-visit\"\n\nexport type MetadataValue = Record<string, string | string[]>\n\n/**\n * Parses a YAML-like value, handling arrays and strings.\n */\nfunction parseValue(value: string): string | string[] {\n const trimmed = value.trim()\n\n // Handle array syntax: [item1, item2, item3]\n if (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\")) {\n const inner = trimmed.slice(1, -1)\n return inner\n .split(\",\")\n .map((item) => item.trim())\n .filter(Boolean)\n }\n\n return trimmed\n}\n\n/**\n * Parses the content of a meta block into key-value pairs.\n */\nfunction parseMetaContent(content: string): MetadataValue {\n const result: MetadataValue = {}\n const lines = content.split(\"\\n\")\n\n for (const line of lines) {\n const trimmed = line.trim()\n if (!trimmed || trimmed === \":::\") {\n continue\n }\n\n const colonIndex = trimmed.indexOf(\":\")\n if (colonIndex === -1) {\n continue\n }\n\n const key = trimmed.slice(0, colonIndex).trim()\n const value = trimmed.slice(colonIndex + 1).trim()\n\n if (key && value) {\n result[key] = parseValue(value)\n }\n }\n\n return result\n}\n\n/**\n * Parses the content of a terms block into a terms array.\n * Terms are a flat list, one per line.\n */\nfunction parseTermsContent(content: string): string[] {\n return content\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line && line !== \":::\")\n}\n\n/**\n * Extracts metadata from MDX files and removes it from the MDX content.\n *\n * Supports two formats:\n *\n * @example `::: meta` - YAML-like key-value pairs\n * ```\n * ::: meta\n * component: NumberInput\n * :::\n *\n * result: {component: \"NumberInput\"}\n * ```\n *\n * @example `::: terms` - flat list of terms\n * ```\n * ::: terms\n * forms\n * input\n * data entry\n * :::\n *\n * result: {terms: [\"forms\", \"input\", \"data entry\"]}\n * ```\n */\nexport const remarkExtractMeta: Plugin<[MetadataValue], Root> = (\n metadata = {},\n) => {\n return (tree) => {\n const nodesToRemove: Array<{index: number; parent: Parent}> = []\n\n visit(tree, \"paragraph\", (node, index, parent) => {\n if (!parent || index === undefined) {\n return\n }\n\n const firstChild = node.children[0]\n if (firstChild?.type !== \"text\") {\n return\n }\n\n const text = firstChild.value\n const metaMatch = text.match(/^:::\\s*meta\\s*/)\n const termsMatch = text.match(/^:::\\s*terms\\s*/)\n\n if (!metaMatch && !termsMatch) {\n return\n }\n\n const openMatch = metaMatch || termsMatch\n const isTermsBlock = !!termsMatch\n\n // Check if the entire block is in this single paragraph\n // (common when markdown parser keeps it together)\n if (\n text.includes(\":::\") &&\n text.lastIndexOf(\":::\") > openMatch![0].length\n ) {\n // Extract content between opening ::: and closing :::\n const afterOpen = text.slice(openMatch![0].length)\n const closeIndex = afterOpen.lastIndexOf(\":::\")\n const content = afterOpen.slice(0, closeIndex)\n\n if (isTermsBlock) {\n const terms = parseTermsContent(content)\n if (terms.length > 0) {\n const existing = metadata.terms\n metadata.terms = Array.isArray(existing)\n ? [...existing, ...terms]\n : terms\n }\n } else {\n const parsed = parseMetaContent(content)\n Object.assign(metadata, parsed)\n }\n\n nodesToRemove.push({index, parent})\n return SKIP\n }\n\n // Multi-paragraph case: collect text from multiple nodes\n // The block might span multiple text children\n let fullText = text\n for (let i = 1; i < node.children.length; i++) {\n const child = node.children[i]\n if (child.type === \"text\") {\n fullText += child.value\n }\n }\n\n // Check for closing ::: in the combined text\n const afterOpenFull = fullText.slice(openMatch![0].length)\n const closeIndexFull = afterOpenFull.lastIndexOf(\":::\")\n\n if (closeIndexFull !== -1) {\n const content = afterOpenFull.slice(0, closeIndexFull)\n\n if (isTermsBlock) {\n const terms = parseTermsContent(content)\n if (terms.length > 0) {\n const existing = metadata.terms\n metadata.terms = Array.isArray(existing)\n ? [...existing, ...terms]\n : terms\n }\n } else {\n const parsed = parseMetaContent(content)\n Object.assign(metadata, parsed)\n }\n\n nodesToRemove.push({index, parent})\n return SKIP\n }\n })\n\n // Remove blocks from AST (in reverse order to preserve indices)\n for (let i = nodesToRemove.length - 1; i >= 0; i--) {\n const {index, parent} = nodesToRemove[i]\n parent.children.splice(index, 1)\n }\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Parent, Root} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\ninterface MdxFlowExpression {\n type: \"mdxFlowExpression\"\n value: string\n}\n\n/**\n * Wraps standalone `{frontmatter.description}` expressions in a\n * `<p class=\"mdx\">` element for styling purposes.\n */\nexport const remarkFrontmatterDescription: Plugin<[], Root> = () => {\n return (tree) => {\n visit(\n tree,\n \"mdxFlowExpression\",\n (\n node: MdxFlowExpression,\n index: number | undefined,\n parent: Parent | undefined,\n ) => {\n if (\n node.value.trim() !== \"frontmatter.description\" ||\n index === undefined ||\n !parent\n ) {\n return\n }\n\n const wrappedNode = {\n attributes: [\n {\n name: \"className\",\n type: \"mdxJsxAttribute\",\n value: \"mdx qui-docs__page-description\",\n },\n ],\n children: [node],\n name: \"p\",\n type: \"mdxJsxFlowElement\",\n }\n\n parent.children[index] = wrappedNode as any\n },\n )\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Parent, Root, Text} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nimport type {PageFrontmatter} from \"@qualcomm-ui/mdx-common\"\n\ninterface MdxExpression {\n type: \"mdxFlowExpression\" | \"mdxTextExpression\"\n value: string\n}\n\nconst FRONTMATTER_PATTERN = /^\\s*frontmatter\\.(\\w+)\\s*$/\n\nfunction isMdxExpression(node: unknown): node is MdxExpression {\n const n = node as {type?: string; value?: unknown}\n return (\n (n.type === \"mdxFlowExpression\" || n.type === \"mdxTextExpression\") &&\n typeof n.value === \"string\"\n )\n}\n\n/**\n * Replaces `{frontmatter.*}` expressions with their actual values from the\n * frontmatter object. This is safer than string replacement as it operates\n * on the AST and won't accidentally match text in code blocks or examples.\n */\nexport const remarkFrontmatterInterpolation: Plugin<[PageFrontmatter], Root> = (\n frontmatter,\n) => {\n return (tree) => {\n visit(tree, (node, index, parent) => {\n if (!isMdxExpression(node) || index === undefined || !parent) {\n return\n }\n\n const match = node.value.match(FRONTMATTER_PATTERN)\n if (!match) {\n return\n }\n\n const key = match[1] as keyof PageFrontmatter\n const value = frontmatter[key]\n\n if (typeof value === \"string\" || typeof value === \"number\") {\n const textNode: Text = {\n type: \"text\",\n value: String(value),\n }\n ;(parent as Parent).children[index] = textNode\n }\n })\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Heading, Parent, Root} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\ninterface MdxTextExpression {\n type: \"mdxTextExpression\"\n value: string\n}\n\nfunction isMdxTextExpression(node: unknown): node is MdxTextExpression {\n const n = node as {type?: string; value?: unknown}\n return n.type === \"mdxTextExpression\" && typeof n.value === \"string\"\n}\n\n/**\n * Apply data-page-title attribute to heading elements containing\n * `{frontmatter.title}`. We use this attribute to prevent the main title from\n * rendering twice, as it's organized into a separate page heading for layout\n * purposes.\n */\nexport const remarkFrontmatterTitle: Plugin<[], Root> = () => {\n return (tree) => {\n visit(\n tree,\n \"heading\",\n (node: Heading, index, parent: Parent | undefined) => {\n if (index === undefined || !parent) {\n return\n }\n\n const hasFrontmatterTitle = node.children.some(\n (child) =>\n isMdxTextExpression(child) &&\n child.value.trim() === \"frontmatter.title\",\n )\n\n if (!hasFrontmatterTitle) {\n return\n }\n\n const wrappedNode = {\n attributes: [\n {\n name: \"data-page-title\",\n type: \"mdxJsxAttribute\",\n value: \"\",\n },\n ],\n children: node.children,\n name: `h${node.depth}`,\n type: \"mdxJsxFlowElement\",\n }\n\n parent.children[index] = wrappedNode as (typeof parent.children)[number]\n },\n )\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Plugin} from \"unified\"\nimport {remove} from \"unist-util-remove\"\n\nexport const remarkRemoveMermaidCodeBlocks: Plugin = () => {\n return (tree, _file, done) => {\n remove(tree, (node: any) => node.type === \"code\" && node.lang === \"mermaid\")\n done()\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Plugin} from \"unified\"\nimport {remove} from \"unist-util-remove\"\n\nexport const remarkRemoveJsx: Plugin = () => {\n return (tree, _file, done) => {\n remove(tree, \"mdxjsEsm\")\n remove(tree, \"mdxJsxFlowElement\")\n remove(tree, \"mdxJsxTextElement\")\n done()\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Heading, Link, Root} from \"mdast\"\nimport {toString} from \"mdast-util-to-string\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nexport interface RemarkSelfLinkOptions {\n /**\n * @default [2, 3, 4]\n */\n allowedLevels?: number[]\n prefix?: string\n}\n\nconst emptyOptions: RemarkSelfLinkOptions = {}\n\nexport function remarkSelfLinkHeadings(\n baseUrl: string = \"\",\n options?: RemarkSelfLinkOptions | null,\n): Plugin<[], Root> {\n if (!baseUrl) {\n return () => {}\n }\n return () => {\n const settings = options || emptyOptions\n const prefix = settings.prefix || \"\"\n const allowedLevels = new Set<number>(settings.allowedLevels || [2, 3, 4])\n const seenIds = new Map<string, number>()\n\n function createSlug(text: string): string {\n const cleaned = text\n .replace(/[<>]/g, \"\")\n .replace(/[^\\w\\s-]/g, \"\")\n .trim()\n\n let slug: string\n if (cleaned.includes(\" \")) {\n slug = cleaned\n .toLowerCase()\n .replace(/\\s+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n } else if ((cleaned.match(/[A-Z]/g) || []).length >= 2) {\n slug = cleaned\n .replace(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1-$2\")\n .toLowerCase()\n } else {\n slug = cleaned.toLowerCase()\n }\n\n const count = seenIds.get(slug) || 0\n seenIds.set(slug, count + 1)\n return count > 0 ? `${slug}-${count}` : slug\n }\n\n return (tree) => {\n seenIds.clear()\n visit(tree, \"heading\", (node: Heading) => {\n if (allowedLevels.has(node.depth)) {\n const text = toString(node)\n const slug = prefix + createSlug(text)\n\n const linkNode: Link = {\n children: node.children,\n type: \"link\",\n url: `${baseUrl}#${slug}`,\n }\n\n node.children = [linkNode]\n }\n })\n }\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {BlockContent, Root} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\ninterface SpoilerOptions {\n defaultSummary?: string\n detailsClassName?: string[]\n summaryClassName?: string[]\n}\n\nfunction getSpoilerStartMatch(text: string) {\n return text.match(/^:::\\s*spoiler\\s*(.*)$/)\n}\n\nfunction getSpoilerEndMatch(text: string) {\n return text.trim() === \":::\"\n}\n\nexport function isSpoilerBlock(text: string) {\n return !!getSpoilerStartMatch(text) || getSpoilerEndMatch(text)\n}\n\n/**\n * Transforms spoiler blocks into MDX components.\n *\n * @example\n * ```\n * ::: spoiler Title\n *\n * Content\n *\n * :::\n * ```\n *\n * result:\n *\n * ```jsx\n * <SpoilerRoot>\n * <SpoilerTrigger><p>Title</p></SpoilerTrigger>\n * <SpoilerContent>Content</SpoilerContent>\n * </SpoilerRoot>\n * ```\n */\nexport const remarkSpoilers: Plugin<[SpoilerOptions?], Root> = (\n options = {},\n) => {\n const {\n defaultSummary = \"Open spoiler\",\n detailsClassName = [],\n summaryClassName = [],\n } = options\n\n return (tree) => {\n visit(tree, \"paragraph\", (node, index, parent) => {\n if (!parent || index === undefined) {\n return\n }\n\n const firstChild = node.children[0]\n if (firstChild?.type !== \"text\") {\n return\n }\n\n const match = getSpoilerStartMatch(firstChild.value)\n if (!match) {\n return\n }\n\n const summary = match[1].trim() || defaultSummary\n let endIndex = index + 1\n const contentNodes: BlockContent[] = []\n\n while (endIndex < parent.children.length) {\n const child = parent.children[endIndex]\n\n if (child.type === \"paragraph\") {\n const firstText = child.children[0]\n if (\n firstText?.type === \"text\" &&\n getSpoilerEndMatch(firstText.value.trim())\n ) {\n break\n }\n }\n\n contentNodes.push(child as BlockContent)\n endIndex++\n }\n\n if (endIndex >= parent.children.length) {\n return\n }\n\n const summaryNode: BlockContent = {\n attributes: summaryClassName.length\n ? [\n {\n name: \"className\",\n type: \"mdxJsxAttribute\",\n value: summaryClassName.join(\" \"),\n },\n ]\n : [],\n children: [\n {\n children: [{type: \"text\", value: summary}],\n type: \"paragraph\",\n },\n ],\n name: \"SpoilerSummary\",\n type: \"mdxJsxFlowElement\",\n }\n\n const contentNode: BlockContent = {\n attributes: [],\n children: contentNodes,\n name: \"SpoilerContent\",\n type: \"mdxJsxFlowElement\",\n }\n\n const detailsNode: BlockContent = {\n attributes: detailsClassName.length\n ? [\n {\n name: \"className\",\n type: \"mdxJsxAttribute\",\n value: detailsClassName.join(\" \"),\n },\n ]\n : [],\n children: [summaryNode, contentNode],\n name: \"SpoilerRoot\",\n type: \"mdxJsxFlowElement\",\n }\n\n parent.children.splice(index, endIndex - index + 1, detailsNode)\n })\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {BlockContent, Heading, Root} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nconst defaultAllowedHeadings = new Set([2, 3, 4])\n\n/**\n * Parses a heading specifier into a Set of depths.\n * Supports a single level (`h2`) or a range (`h2-h5`).\n * Returns `undefined` for invalid input.\n */\nfunction parseHeadingRange(value: string): Set<number> | undefined {\n const match = value.match(/^h([1-6])(?:-h([1-6]))?$/)\n if (!match) {\n return undefined\n }\n\n const start = Number(match[1])\n const end = match[2] ? Number(match[2]) : start\n if (start > end) {\n return undefined\n }\n\n const depths = new Set<number>()\n for (let i = start; i <= end; i++) {\n depths.add(i)\n }\n return depths\n}\n\nfunction isHeading(node: {type: string}): node is Heading {\n return node.type === \"heading\"\n}\n\nfunction getStepStartMatch(text: string) {\n return text.match(/^:::\\s*steps(?:\\s+(h[1-6](?:-h[1-6])?))?\\s*$/)\n}\n\nfunction getStepEndMatch(text: string) {\n return text.match(/^:::\\s*\\/steps\\s*$/)\n}\n\nexport function isStepBlock(text: string) {\n return !!(getStepStartMatch(text) || getStepEndMatch(text))\n}\n\n/**\n * Transforms `:::steps` blocks into a styled `<div>` wrapper.\n *\n * Accepts an optional heading specifier to control which headings receive\n * step numbering. Supports a single level (`h3`) or a range (`h2-h5`).\n * Defaults to `h2-h4`.\n *\n * @example\n * ```\n * :::steps\n *\n * ## Step 1\n *\n * Content for step 1.\n *\n * ## Step 2\n *\n * Content for step 2.\n *\n * :::/steps\n * ```\n *\n * With a single heading level:\n *\n * ```\n * :::steps h3\n *\n * ### Step 1\n *\n * :::/steps\n * ```\n *\n * With a custom heading range:\n *\n * ```\n * :::steps h2-h5\n *\n * ## Step 1\n *\n * :::/steps\n * ```\n *\n * result:\n *\n * ```jsx\n * <div className=\"qui-docs__steps\">\n * <h2 data-step>Step 1</h2>\n * <p>Content for step 1.</p>\n * <h2 data-step>Step 2</h2>\n * <p>Content for step 2.</p>\n * </div>\n * ```\n */\nexport const remarkSteps: Plugin<[], Root> = () => {\n return (tree) => {\n visit(tree, \"paragraph\", (node, index, parent) => {\n if (!parent || index === undefined) {\n return\n }\n\n const firstChild = node.children[0]\n if (firstChild?.type !== \"text\") {\n return\n }\n\n const match = getStepStartMatch(firstChild.value)\n if (!match) {\n return\n }\n\n const allowedHeadings = match[1]\n ? (parseHeadingRange(match[1]) ?? defaultAllowedHeadings)\n : defaultAllowedHeadings\n\n let endIndex = index + 1\n const contentNodes: BlockContent[] = []\n\n while (endIndex < parent.children.length) {\n const child = parent.children[endIndex]\n\n if (child.type === \"paragraph\") {\n const firstText = child.children[0]\n if (firstText?.type === \"text\" && getStepEndMatch(firstText.value)) {\n break\n }\n }\n\n if (isHeading(child) && allowedHeadings.has(child.depth)) {\n child.data = {\n ...child.data,\n hProperties: {\n ...(child.data as {hProperties?: Record<string, unknown>})\n ?.hProperties,\n \"data-step\": \"\",\n },\n }\n }\n\n contentNodes.push(child as BlockContent)\n endIndex++\n }\n\n if (endIndex >= parent.children.length) {\n return\n }\n\n const stepsNode: BlockContent = {\n attributes: [],\n children: contentNodes,\n name: \"HeadingSteps\",\n type: \"mdxJsxFlowElement\",\n }\n\n parent.children.splice(index, endIndex - index + 1, stepsNode)\n })\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Link, Parent, Root} from \"mdast\"\nimport {minimatch} from \"minimatch\"\nimport {readdir, stat} from \"node:fs/promises\"\nimport {join, relative} from \"node:path\"\nimport {visit} from \"unist-util-visit\"\n\nimport type {\n KnowledgePageData,\n KnowledgePages,\n KnowledgeSections,\n PageEntry,\n SectionEntry,\n} from \"@qualcomm-ui/mdx-common\"\n\nimport type {\n KnowledgeExtraFile,\n KnowledgeFrontmatterConfig,\n PagesExportConfig,\n SectionExportConfig,\n} from \"../../config\"\nimport {\n getPathnameFromPathSegments,\n getPathSegmentsFromFileName,\n} from \"../../nav-builder\"\nimport type {MdxFileReader} from \"../markdown-file-reader\"\nimport {createRemarkProcessor} from \"../remark-pipeline\"\n\nimport {filterFrontmatter} from \"./filter-frontmatter\"\nimport {\n filterTextDirectives,\n formatDemos,\n formatNpmInstallTabs,\n formatThemeNodes,\n PropFormatter,\n} from \"./plugins\"\nimport {SectionExtractor} from \"./section-extractor\"\nimport type {MdxFlowExpression, ProcessedPage} from \"./types\"\nimport {computeMd5} from \"./utils\"\n\nexport interface KnowledgeExporterConfig {\n baseUrl?: string\n docPropsPath?: string\n exclude?: string[]\n extraFiles?: KnowledgeExtraFile[]\n frontmatter?: KnowledgeFrontmatterConfig\n pageIdPrefix?: string\n pages?: PagesExportConfig\n routeDir: string\n sections?: SectionExportConfig\n verbose?: boolean\n}\n\n/**\n * Processes MDX documentation pages into structured JSON data (sections + pages).\n * Does not write files \u2014 the caller handles persistence.\n */\nexport class KnowledgeExporter {\n private readonly config: KnowledgeExporterConfig\n private readonly fileReader: MdxFileReader\n private readonly propFormatter: PropFormatter\n\n constructor(config: KnowledgeExporterConfig, fileReader: MdxFileReader) {\n this.config = config\n this.fileReader = fileReader\n this.propFormatter = new PropFormatter({\n docPropsPath: config.docPropsPath,\n routeDir: config.routeDir,\n verbose: config.verbose,\n })\n }\n\n async generate(): Promise<{\n pages: KnowledgePages\n sections: KnowledgeSections\n }> {\n if (this.config.verbose) {\n console.log(`Scanning pages in: ${this.config.routeDir}`)\n if (this.config.exclude?.length) {\n console.log(`Excluding patterns: ${this.config.exclude.join(\", \")}`)\n }\n }\n\n const [pageInfos] = await Promise.all([\n this.scanPages(),\n this.propFormatter.loadDocProps(),\n ])\n\n if (pageInfos.length === 0) {\n console.log(\"No pages found.\")\n } else if (this.config.verbose) {\n console.log(`Found ${pageInfos.length} page(s)`)\n }\n\n const processedPages: ProcessedPage[] = []\n for (const page of pageInfos) {\n try {\n if (this.config.verbose) {\n console.log(`Processing page: ${page.name}`)\n }\n const processed = await this.processMdxPage(page)\n processedPages.push(processed)\n } catch (error) {\n console.error(`Failed to process page: ${page.name}`)\n throw error\n }\n }\n\n const sectionsConfig = this.config.sections ?? {}\n const extractor = new SectionExtractor({\n depths: sectionsConfig.depths,\n minContentLength: sectionsConfig.minContentLength,\n pageIdPrefix: this.config.pageIdPrefix,\n })\n\n const allSections: SectionEntry[] = []\n const allPages: PageEntry[] = []\n\n for (let i = 0; i < processedPages.length; i++) {\n const processed = processedPages[i]\n const page = pageInfos[i]\n\n const filteredFrontmatter = filterFrontmatter(\n processed.frontmatter,\n this.config.frontmatter,\n )\n\n const pageInfo = {\n frontmatter: filteredFrontmatter,\n id: page.id,\n pathname: page.pathname,\n title: processed.title,\n url: processed.url,\n }\n\n const {sections: pageSections} = extractor.extract(\n processed.sectionAst,\n pageInfo,\n )\n allSections.push(...pageSections)\n\n const pageEntry = extractor.extractPage(processed.sectionAst, pageInfo)\n if (pageEntry) {\n pageEntry.content = `# ${processed.title}\\n\\n${pageEntry.content}`\n allPages.push(pageEntry)\n }\n }\n\n // Process extra files\n if (this.config.extraFiles?.length) {\n await this.processExtraFiles(\n this.config.extraFiles,\n extractor,\n allSections,\n allPages,\n )\n }\n\n const sectionsHash = computeMd5(JSON.stringify(allSections))\n const pagesHash = computeMd5(JSON.stringify(allPages))\n\n return {\n pages: {\n generatedAt: new Date().toISOString(),\n hash: pagesHash,\n pages: allPages,\n totalPages: allPages.length,\n version: 1,\n },\n sections: {\n generatedAt: new Date().toISOString(),\n hash: sectionsHash,\n sections: allSections,\n totalSections: allSections.length,\n version: 1,\n },\n }\n }\n\n private async scanPages(): Promise<KnowledgePageData[]> {\n const components: KnowledgePageData[] = []\n const excludePatterns = this.config.exclude ?? []\n\n const shouldExclude = (absolutePath: string): boolean => {\n if (excludePatterns.length === 0) {\n return false\n }\n const relativePath = relative(this.config.routeDir, absolutePath)\n return excludePatterns.some((pattern) =>\n minimatch(relativePath, pattern, {matchBase: true}),\n )\n }\n\n const scanDirectory = async (dirPath: string): Promise<void> => {\n if (shouldExclude(dirPath)) {\n if (this.config.verbose) {\n console.log(\n `Excluding directory: ${relative(this.config.routeDir, dirPath)}`,\n )\n }\n return\n }\n\n const entries = await readdir(dirPath, {withFileTypes: true})\n const mdxFiles =\n entries.filter(\n (f) =>\n f.name.endsWith(\".mdx\") && !shouldExclude(join(dirPath, f.name)),\n ) ?? []\n\n for (const mdxFile of mdxFiles) {\n const demosFolder = entries.find((f) => f.name === \"demos\")\n const demosFolderPath = demosFolder\n ? join(dirPath, demosFolder.name)\n : undefined\n\n const segments = getPathSegmentsFromFileName(\n join(dirPath, mdxFile.name),\n this.config.routeDir,\n )\n const url = getPathnameFromPathSegments(segments)\n\n components.push({\n demosFolder: demosFolderPath,\n filePath: dirPath,\n id: segments.join(\"-\").trim(),\n mdxFile: join(dirPath, mdxFile.name),\n name: segments.at(-1)!,\n pathname: url,\n url: this.config.baseUrl\n ? new URL(url, this.config.baseUrl).toString()\n : undefined,\n })\n\n if (this.config.verbose) {\n console.log(`Found file: ${segments.at(-1)}`)\n console.log(` Demos folder: ${demosFolderPath || \"NOT FOUND\"}`)\n }\n }\n\n for (const entry of entries) {\n const fullPath = join(dirPath, entry.name)\n const stats = await stat(fullPath)\n if (stats.isDirectory()) {\n await scanDirectory(fullPath)\n }\n }\n }\n\n await scanDirectory(this.config.routeDir)\n return components\n }\n\n private formatFrontmatterExpressions(frontmatter: Record<string, any>) {\n return () => (tree: Root) => {\n visit(\n tree,\n \"mdxFlowExpression\",\n (\n node: MdxFlowExpression,\n index: number | undefined,\n parent: Parent | undefined,\n ) => {\n if (\n node.value.trim() !== \"frontmatter.description\" ||\n index === undefined ||\n !parent\n ) {\n return\n }\n\n if (frontmatter.description) {\n parent.children.splice(index, 1, {\n children: [{type: \"text\", value: frontmatter.description}],\n type: \"paragraph\",\n })\n } else {\n parent.children.splice(index, 1)\n }\n },\n )\n\n const root = tree as Parent\n const h1Index = root.children.findIndex((node: any) => {\n if (node.type !== \"heading\" || node.depth !== 1) {\n return false\n }\n return node.children?.some(\n (child: any) =>\n child.type === \"mdxTextExpression\" &&\n child.value?.includes(\"frontmatter\"),\n )\n })\n if (h1Index >= 0) {\n root.children.splice(h1Index, 1)\n }\n }\n }\n\n private transformRelativeUrls() {\n const baseUrl = this.config.baseUrl\n return () => (tree: Root) => {\n if (!baseUrl) {\n return\n }\n visit(tree, \"link\", (node: Link) => {\n if (node.url.startsWith(\"/\")) {\n node.url = `${baseUrl}${node.url}`\n }\n })\n }\n }\n\n private async processMdxContent(\n mdxContent: string,\n pageInfo: KnowledgePageData,\n frontmatter: Record<string, any>,\n ): Promise<Root> {\n const processor = createRemarkProcessor({\n frontmatter: true,\n gfm: true,\n mdx: true,\n plugins: [\n formatNpmInstallTabs,\n this.propFormatter.propsToMarkdownList(),\n this.formatFrontmatterExpressions(frontmatter),\n await formatThemeNodes(),\n formatDemos(pageInfo.demosFolder, this.config.verbose),\n filterTextDirectives,\n this.transformRelativeUrls(),\n ],\n })\n\n return (await processor.run(processor.parse(mdxContent))) as Root\n }\n\n private async processMdxPage(\n pageInfo: KnowledgePageData,\n ): Promise<ProcessedPage> {\n const {fileContents, frontmatter} = this.fileReader.readFileSync(\n pageInfo.mdxFile,\n )\n const ast = await this.processMdxContent(\n fileContents,\n pageInfo,\n frontmatter,\n )\n\n const jsxAndMetaProcessor = createRemarkProcessor({\n extractMeta: {},\n frontmatter: true,\n gfm: true,\n mdx: true,\n output: \"md\",\n removeJsx: true,\n })\n const sectionAst = jsxAndMetaProcessor.runSync(ast) as Root\n const processed = String(jsxAndMetaProcessor.stringify(sectionAst))\n const rawContent = processed\n .replace(/^---\\r?\\n[\\s\\S]*?\\r?\\n---\\r?\\n?/, \"\")\n .replace(/(^#{1,6} .*\\\\<[^>]+)>/gm, \"$1\\\\>\")\n\n // Strip meta blocks from raw content for the prose-only field\n const stripMetaProcessor = createRemarkProcessor({\n extractMeta: {},\n output: \"md\",\n })\n const strippedContent = String(await stripMetaProcessor.process(rawContent))\n\n const title = frontmatter.title || pageInfo.name\n\n return {\n content: strippedContent.trim(),\n frontmatter: frontmatter as unknown as Record<string, unknown>,\n rawContent: rawContent.trim(),\n sectionAst,\n title,\n url: pageInfo.url,\n }\n }\n\n private async processExtraFiles(\n extraFiles: KnowledgeExtraFile[],\n extractor: SectionExtractor,\n allSections: SectionEntry[],\n allPages: PageEntry[],\n ): Promise<void> {\n await Promise.all(\n extraFiles.map(async (extraFile) => {\n let contents = extraFile.contents\n if (extraFile.processAsMdx) {\n const removeJsxProcessor = createRemarkProcessor({\n frontmatter: true,\n gfm: true,\n mdx: true,\n output: \"md\",\n plugins: [this.transformRelativeUrls()],\n removeJsx: true,\n })\n\n contents = String(await removeJsxProcessor.process(contents))\n }\n\n const lines: string[] = []\n if (extraFile.title) {\n lines.push(`# ${extraFile.title}`)\n lines.push(\"\")\n }\n lines.push(contents)\n const content = lines.join(\"\\n\")\n\n const processor = createRemarkProcessor({gfm: true, output: \"md\"})\n const tree = processor.parse(content)\n\n const pageInfo = {\n frontmatter: {},\n id: extraFile.id,\n pathname: `/${extraFile.id}`,\n title: extraFile.title || extraFile.id,\n }\n\n const {sections: pageSections} = extractor.extract(tree, pageInfo)\n allSections.push(...pageSections)\n\n const pageEntry = extractor.extractPage(tree, pageInfo)\n if (pageEntry) {\n allPages.push(pageEntry)\n }\n }),\n )\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {RouteMetaEntryInternal, RouteMetaInternal} from \"./types\"\n\n/**\n * Retrieves the route metadata for a given path based on its path segments.\n */\nexport function getRouteMeta(\n pathSegments: string[],\n metaJson: RouteMetaInternal,\n): RouteMetaEntryInternal | undefined | null {\n const routeMeta = metaJson[pathSegments[0]]\n if (!routeMeta) {\n // backup, fetch using id if provided\n return undefined\n }\n\n if (pathSegments.length === 1) {\n return routeMeta\n }\n\n return pathSegments\n .slice(1)\n .reduce((acc: RouteMetaEntryInternal | undefined | null, segment) => {\n return acc?.children?.[segment]\n }, routeMeta)\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {sortBy} from \"lodash-es\"\nimport {v4 as uuidv4} from \"uuid\"\n\nimport type {\n NavItem,\n PageFrontmatter,\n PageSection,\n} from \"@qualcomm-ui/mdx-common\"\nimport {capitalCase} from \"@qualcomm-ui/utils/change-case\"\nimport {defined} from \"@qualcomm-ui/utils/guard\"\n\nimport {getRouteMeta} from \"./get-route-meta\"\nimport type {NavMeta, RouteMetaEntryInternal, RouteMetaInternal} from \"./types\"\n\ninterface InitialRoute {\n pageFrontmatter: Partial<PageFrontmatter>\n pageSection: PageSection\n routeMeta?: RouteMetaEntryInternal\n}\n\n/**\n * Given a flat remix route structure, computes nested navigation items for the QUI\n * side nav.\n */\nexport class NavBuilder {\n private initialRoutes: InitialRoute[] = []\n private flatNavItems: NavItem[] = []\n\n get navItems(): NavItem[] {\n return this._navItems\n }\n private _navItems: NavItem[] = []\n\n private readonly metaJson: RouteMetaInternal\n private readonly navMeta: Record<number, NavMeta>\n\n constructor(metaJson: RouteMetaInternal, navMeta: Record<number, NavMeta>) {\n this.navMeta = navMeta\n this.metaJson = metaJson\n }\n\n add(\n pageSection: PageSection,\n pageFrontmatter: Partial<PageFrontmatter>,\n routeMeta?: RouteMetaEntryInternal,\n ): void {\n this.initialRoutes.push({pageFrontmatter, pageSection, routeMeta})\n }\n\n reset(): void {\n this.initialRoutes = []\n this.flatNavItems = []\n this._navItems = []\n }\n\n /**\n * Sorts nav items. Nav items with an order defined take precedence over nav items\n * without an order. Nav items with the same order are sorted alphabetically by\n * title.\n */\n private navItemSort(a: NavItem, b: NavItem, groupOrder?: string[]) {\n if (a.depth !== b.depth) {\n return a.depth - b.depth\n }\n\n if (a.order && !b.order) {\n return -1\n }\n if (!a.order && b.order) {\n return 1\n } else if (a.order && b.order && a.order !== b.order) {\n return a.order - b.order\n }\n\n if (groupOrder && a.group && b.group) {\n const aIndex = a.group ? groupOrder.indexOf(a.group) : -1\n const bIndex = b.group ? groupOrder.indexOf(b.group) : -1\n\n if (aIndex === bIndex) {\n // continue\n } else if (aIndex !== -1 && bIndex !== -1) {\n return aIndex - bIndex\n } else if (aIndex !== -1) {\n return -1\n } else if (bIndex !== -1) {\n return 1\n }\n }\n\n // group items with the same group\n if (a.group !== b.group) {\n if (!a.group && b.group) {\n return -1\n }\n if (a.group && !b.group) {\n return 1\n }\n if (a.group && b.group) {\n return a.group.localeCompare(b.group)\n }\n }\n\n return a.title.localeCompare(b.title)\n }\n\n resolveSideNavTitle(\n frontmatter: Partial<PageFrontmatter>,\n routeMeta: Partial<RouteMetaEntryInternal>,\n fallback: string,\n ): string {\n return (\n (defined(routeMeta.sideNavTitle)\n ? routeMeta.sideNavTitle || \"\"\n : frontmatter.sideNavTitle || \"\") || fallback\n )\n }\n\n /**\n * Builds a flat list of nav items from the MDX pages and _meta.json. If a page\n * does not exist, it is not added to the side nav (even if it has an entry in\n * _meta.json).\n */\n private buildNavItem({\n pageFrontmatter,\n pageSection: {pathname, pathSegments, title},\n routeMeta: routeMetaParam,\n }: InitialRoute) {\n const id = pageFrontmatter?.id || \"\"\n\n // handle home page (this route does not have path segments)\n if (!pathSegments.length && pathname === \"/\") {\n const routeMeta =\n routeMetaParam || getRouteMeta(id ? [id] : [], this.metaJson)\n if (!routeMeta) {\n return\n }\n\n this.flatNavItems.push({\n depth: 1,\n expanded: routeMeta?.expanded || false,\n id: `/`,\n order: routeMeta?.order,\n pathname,\n pathSegments: [],\n title: this.resolveSideNavTitle(\n pageFrontmatter,\n routeMeta,\n routeMeta?.title || title,\n ),\n })\n }\n\n pathSegments.forEach((segment, index) => {\n const depth = index + 1\n\n // we only add an item if it doesn't already exist, which we determine by\n // comparing the path segments iteratively.\n const navItem = this.flatNavItems.find((item) =>\n pathSegments\n .slice(0, depth)\n .every((value, i) => value === item.pathSegments[i]),\n )\n\n if (!navItem) {\n const isPage = index === pathSegments.length - 1\n const adjustedSegments = pathSegments.slice(0, depth)\n\n const routeMeta =\n getRouteMeta(\n isPage ? pathSegments : adjustedSegments,\n this.metaJson,\n ) ?? {}\n\n this.flatNavItems.push({\n depth,\n expanded: routeMeta?.expanded || false,\n group: isPage\n ? routeMeta.group || pageFrontmatter.group\n : routeMeta.group,\n id: `/${adjustedSegments.join(\"/\")}`,\n items: [],\n order: routeMeta?.order,\n pathname: isPage ? pathname : undefined,\n pathSegments: adjustedSegments,\n title: this.resolveSideNavTitle(\n isPage ? pageFrontmatter : {},\n routeMeta,\n routeMeta?.title\n ? routeMeta.title\n : isPage\n ? title\n : capitalCase(segment),\n ),\n })\n }\n })\n }\n\n /**\n * Iterates through a nav item's path segments and ensures that all of its parent\n * elements exist in the recursive structure.\n */\n private ensureParent(navItem: NavItem) {\n const segments = navItem.pathSegments\n let items: NavItem[] = this.navItems\n let item: NavItem | undefined\n let prevItem: NavItem | undefined = undefined\n\n for (let i = 0; i < segments.length - 1; i++) {\n const segment = segments[i]\n item = items?.find((entry) => entry.pathSegments[i] === segment)\n if (item) {\n // point to the found item's children and keep iterating\n items = item.items ?? []\n prevItem = item\n continue\n }\n if (prevItem) {\n const pathSegments = segments.slice(0, i + 1)\n const routeMeta = getRouteMeta(pathSegments, this.metaJson)\n\n items = []\n const base = {\n depth: pathSegments.length,\n id: `/routes/${pathSegments.join(\"/\")}`,\n items,\n pathSegments,\n title: segment,\n }\n const newItem = routeMeta\n ? {\n ...base,\n expanded: routeMeta.expanded,\n order: routeMeta.order,\n restricted: routeMeta.restricted,\n title: routeMeta.title ?? segment,\n }\n : base\n prevItem.items = prevItem.items\n ? [...prevItem.items, newItem]\n : [newItem]\n }\n prevItem = item\n }\n }\n\n /**\n * Deeply inserts a nav item into the array, iterating through parent routes\n * (based on the pathSegments) and adding them if they don't exist.\n *\n * For example, given a leaf node 4 path segments deep, this function will create\n * all parent nav items as nested children of the top-most nav item.\n */\n private nestedInsert(\n item: NavItem,\n pathSegments: string[],\n items: NavItem[],\n ) {\n const segment = pathSegments[0]\n const parentItem = items.find(\n (parent) =>\n parent.pathSegments[parent.pathSegments.length - 1] === segment,\n )\n if (parentItem) {\n this.nestedInsert(item, pathSegments.slice(1), parentItem.items ?? [])\n } else if (pathSegments.length === 1) {\n items.push(item)\n }\n }\n\n private buildNestedNavItems() {\n for (let i = 0; i < this.flatNavItems.length; i++) {\n const navItem = this.flatNavItems[i]\n if (navItem.depth === 1) {\n this.navItems.push(navItem)\n continue\n }\n\n this.ensureParent(navItem)\n this.nestedInsert(navItem, navItem.pathSegments, this.navItems)\n }\n }\n\n private sortNestedNavItems(items: NavItem[], groupOrder?: string[]) {\n items.sort((a, b) => this.navItemSort(a, b, groupOrder))\n items.forEach((item) => {\n if (item.items?.length) {\n const meta = getRouteMeta(item.pathSegments, this.metaJson)\n this.sortNestedNavItems(item.items, meta?.groupOrder)\n }\n })\n }\n\n /**\n * To be called after every mdx page route has been added through the {@link add}\n * function.\n */\n build(): NavItem[] {\n // We need to process parent items first, so we sort by path segment. Routes\n // with shorter path segments will be processed first.\n sortBy(\n this.initialRoutes,\n (item) => item.pageSection.pathSegments.length,\n ).map((r) => this.buildNavItem(r))\n\n this.buildNestedNavItems()\n\n const rootMeta = getRouteMeta([], this.metaJson)\n this.sortNestedNavItems(this.navItems, rootMeta?.groupOrder)\n\n if (this.navMeta) {\n Object.entries(this.navMeta).forEach(([index, value]) => {\n this._navItems.splice(parseInt(index), 0, {\n depth: 1,\n id: uuidv4(),\n pathSegments: [],\n sectionTitle: value.sectionTitle,\n separator: value.separator,\n title: \"\",\n })\n })\n }\n\n this._navItems = this.groupNavItems(this.navItems)\n this._navItems = this.buildSearchMeta(this.navItems, [])\n return this.navItems\n }\n\n private groupNavItems(items: NavItem[]): NavItem[] {\n const result: NavItem[] = []\n const seenGroups = new Set<string>()\n\n for (const item of items) {\n if (item.group && !seenGroups.has(item.group)) {\n seenGroups.add(item.group)\n result.push({\n depth: item.depth,\n group: item.group,\n id: uuidv4(),\n pathSegments: [],\n sectionTitle: item.group,\n title: \"\",\n })\n }\n\n result.push({\n ...item,\n items: item.items ? this.groupNavItems(item.items) : undefined,\n })\n }\n\n return result\n }\n\n /**\n * Walks over the tree and builds search metadata using the nearest sectionTitle.\n */\n private buildSearchMeta(items: NavItem[], meta: string[]): NavItem[] {\n let sectionTitle = \"\"\n const results: NavItem[] = []\n\n for (const ogItem of items) {\n const item = {...ogItem}\n\n if (item.sectionTitle) {\n sectionTitle = item.sectionTitle\n } else if (item.separator) {\n sectionTitle = \"\"\n }\n\n if (!item.separator) {\n const currentMeta = sectionTitle ? [...meta, sectionTitle] : [...meta]\n const nextMeta = [...(item.searchMeta || []), ...currentMeta]\n if (nextMeta.length) {\n item.searchMeta = [...nextMeta]\n }\n\n if (item.items) {\n item.items = this.buildSearchMeta(item.items, currentMeta)\n }\n }\n\n results.push(item)\n }\n\n return results\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {join} from \"node:path\"\n\nimport {capitalCase} from \"@qualcomm-ui/utils/change-case\"\n\nimport type {RoutingStrategy} from \"../config\"\n\nimport {getRouteMeta} from \"./get-route-meta\"\nimport type {RouteMetaInternal} from \"./types\"\n\nexport function getPathnameFromPathSegments(segments: string[]) {\n return `/${segments.join(\"/\")}`\n}\n\nexport function getCategoriesFromPathSegments(\n segments: string[],\n metaJson: RouteMetaInternal,\n // the frontmatter title only applies to the last segment.\n frontmatterTitle: string,\n): string[] {\n return segments.reduce((acc: string[], segment, index) => {\n const pathSegments = segments.slice(0, index + 1)\n if (index === segments.length - 1) {\n acc.push(frontmatterTitle)\n return acc\n }\n const meta = getRouteMeta(pathSegments, metaJson)\n if (meta?.title) {\n acc.push(meta.title)\n } else {\n acc.push(pathSegmentToCategory(segment))\n }\n return acc\n }, [])\n}\n\n// fallback for unmatched path segments\nexport function pathSegmentToCategory(segment: string): string {\n // we don't transform words like `a`, `or`, and `and`\n return segment\n .split(\"-\")\n .map((segment) =>\n /\\b(a|an|and|but|or|in|on|at)\\b/.test(segment)\n ? segment\n : capitalCase(segment),\n )\n .join(\" \")\n}\n\nfunction getGeneroutedPathSegments(filePath: string): string[] {\n const extension = filePath.endsWith(\"mdx\") ? \"mdx\" : \"tsx\"\n\n const segments = filePath\n .substring(0, filePath.lastIndexOf(`.${extension}`))\n .split(\"/\")\n\n if (segments[segments.length - 1] === \"index\") {\n return segments.slice(0, segments.length - 1)\n }\n return segments\n}\n\nconst pathSeparatorRegex = /[\\/\\\\.]/\nfunction isPathSeparator(char: string) {\n return pathSeparatorRegex.test(char)\n}\n\nconst indexRouteRegex =\n /((^|[.]|[+]\\/)(index|_index))(\\/[^\\/]+)?$|(\\/_?index\\/)/\n\nfunction getRemixFlatRoutesSegments(\n name: string,\n index: boolean,\n paramPrefixChar: string = \"$\",\n) {\n let routeSegments: string[] = []\n let i = 0\n let routeSegment = \"\"\n let state = \"START\"\n let subState = \"NORMAL\"\n let hasPlus = false\n\n // ignore layout routes\n if (name.endsWith(\"_layout\")) {\n return []\n }\n\n /*\n * name has already been normalized to use / as path separator.\n * replace `+/_.` with `_+/`\n * this supports the ability to specify parent folder will not be a layout.\n * _public+/_.about.tsx => _public_.about.tsx\n */\n if (/\\+\\/_\\./.test(name)) {\n name = name.replace(/\\+\\/_\\./g, \"_+/\")\n }\n\n /*\n * replace `+/` with `.`\n * this supports folders for organizing flat-files convention.\n * _public+/about.tsx => _public.about.tsx\n */\n if (/\\+\\//.test(name)) {\n name = name.replace(/\\+\\//g, \".\")\n hasPlus = true\n }\n const hasFolder = /\\//.test(name)\n // if name has plus folder, but we still have regular folders\n // then treat ending route as flat-folders\n if (\n ((hasPlus && hasFolder) || !hasPlus) &&\n !(name.endsWith(\".route\") || name.endsWith(\".index\"))\n ) {\n // Do not remove segments ending in .route\n // since these would be part of the route directory name\n // docs/readme.route.tsx => docs/readme\n // Remove last segment since this should just be the route filename, and we only\n // want the directory name docs/_layout.tsx => docs\n const last = name.lastIndexOf(\"/\")\n if (last >= 0) {\n name = name.substring(0, last)\n }\n }\n\n const pushRouteSegment = (routeSegment: string) => {\n if (routeSegment) {\n routeSegments.push(routeSegment)\n }\n }\n\n while (i < name.length) {\n const char = name[i]\n switch (state) {\n case \"START\":\n // process existing segment\n if (\n routeSegment.includes(paramPrefixChar) &&\n !(\n routeSegment.startsWith(paramPrefixChar) ||\n routeSegment.startsWith(`(${paramPrefixChar}`)\n )\n ) {\n throw new Error(\n `Route params must start with prefix char ${paramPrefixChar}: ${routeSegment}`,\n )\n }\n if (\n routeSegment.includes(\"(\") &&\n !routeSegment.startsWith(\"(\") &&\n !routeSegment.endsWith(\")\")\n ) {\n throw new Error(\n `Optional routes must start and end with parentheses: ${routeSegment}`,\n )\n }\n pushRouteSegment(routeSegment)\n routeSegment = \"\"\n state = \"PATH\"\n continue // restart without advancing index\n case \"PATH\":\n if (isPathSeparator(char) && subState === \"NORMAL\") {\n state = \"START\"\n break\n } else if (char === \"[\") {\n subState = \"ESCAPE\"\n break\n } else if (char === \"]\") {\n subState = \"NORMAL\"\n break\n }\n routeSegment += char\n break\n }\n i++ // advance to next character\n }\n // process remaining segment\n pushRouteSegment(routeSegment)\n // strip trailing .route segment\n if (\n routeSegments.at(-1) === \"route\" ||\n routeSegments.at(-1) === \"index\" ||\n routeSegments.at(-1) === \"_index\" ||\n routeSegments.at(-1) === \"_route\"\n ) {\n routeSegments = routeSegments.slice(0, -1)\n }\n // if hasPlus, we need to strip the trailing segment if it starts with _\n // and route is not an index route\n // this is to handle layouts in flat-files\n // _public+/_layout.tsx => _public.tsx\n // _public+/index.tsx => _public.index.tsx\n if (!index && hasPlus && routeSegments.at(-1)?.startsWith(\"_\")) {\n routeSegments = routeSegments.slice(0, -1)\n }\n return routeSegments\n}\n\nfunction getRemixHybridRoutesPathSegments(filePath: string): string[] {\n const routeWithoutExtension = filePath.substring(0, filePath.lastIndexOf(\".\"))\n\n return getRemixFlatRoutesSegments(\n routeWithoutExtension,\n indexRouteRegex.test(routeWithoutExtension),\n )\n}\n\nexport function getPathSegmentsFromFileName(\n filePath: string,\n pageDirectory: string,\n strategy?: RoutingStrategy,\n): string[] {\n const filePathWithoutPageDirectory = filePath.substring(\n filePath.indexOf(pageDirectory) + pageDirectory.length + 1,\n )\n if (typeof strategy === \"function\") {\n return strategy(filePathWithoutPageDirectory)\n }\n switch (strategy) {\n case \"vite-generouted\":\n return getGeneroutedPathSegments(filePathWithoutPageDirectory)\n default:\n return getRemixHybridRoutesPathSegments(filePathWithoutPageDirectory)\n }\n}\n\nexport function filterFileGlob(\n fileGlob: string[],\n ext: string,\n srcDir: string,\n router?: RoutingStrategy,\n): string[] {\n if (typeof router === \"string\" && router === \"vite-generouted\") {\n // vite-generouted: filter routes\n const restrictedPattern = /(\\(.*\\))|(\\[.*\\])/\n // pull out the full path before filtering to avoid potential issues with\n // parent directories.\n const relativeGlobs = fileGlob.map((file) => file.replace(srcDir, \"\"))\n return (\n relativeGlobs\n .filter(\n (file) =>\n file.endsWith(`.${ext}`) &&\n !file.includes(\"/_\") &&\n !file.includes(\"/+\"),\n )\n // filter pathless segments\n .map((file) =>\n file\n .split(\"/\")\n .filter((segment) => !restrictedPattern.test(segment))\n .join(\"/\"),\n )\n // restore full path\n .map((file) => join(srcDir, file))\n )\n }\n return fileGlob.filter((file) => file.endsWith(ext) && !file.includes(\"$\"))\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {NavConfig, NavMeta, RouteMeta, RouteMetaInternal} from \"./types\"\n\nexport function transformRouteMetaArray(\n meta: NavConfig[],\n routeMetaNav: Record<string, NavMeta>,\n): RouteMetaInternal {\n let ignoringOrder = 0\n return meta.reduce((acc: RouteMetaInternal, item, index) => {\n // strip the nav meta and populate a separate record. This will be used for\n // lookup while building the nav items.\n if (!(\"id\" in item)) {\n if (\"separator\" in item || \"sectionTitle\" in item) {\n // offset the navMeta index by the number of items that will be sorted to\n // the back of the nav order.\n routeMetaNav[index - ignoringOrder] = item\n }\n return acc\n }\n const current = item as RouteMeta\n if (current.ignoreRouteMetaOrder || current.hidden) {\n // items with ignored order are always sorted to the back of the nav order. We\n // need to account for this when splicing in the navMeta entries.\n ignoringOrder++\n }\n acc[current.id] = {\n children: current.children\n ? transformRouteMetaArray(current.children, routeMetaNav)\n : undefined,\n expanded: current.expanded,\n group: current.group,\n groupOrder: current.groupOrder,\n hidden: current.hidden,\n hideBreadcrumbs: current.hideBreadcrumbs,\n hideFromSearch: current.hideFromSearch,\n hidePageLinks: current.hidePageLinks,\n hideSideNav: current.hideSideNav,\n hideToc: current.hideToc,\n order: current.ignoreRouteMetaOrder ? undefined : index + 1,\n restricted: current.restricted,\n title: current.title,\n }\n return acc\n }, {})\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {minimatch} from \"minimatch\"\n\nimport type {KnowledgeFrontmatterConfig} from \"../../config\"\n\nexport function filterFrontmatter(\n frontmatter: Record<string, unknown>,\n config: KnowledgeFrontmatterConfig | undefined,\n): Record<string, unknown> {\n if (!config?.include?.length) {\n return frontmatter\n }\n\n const includePatterns = config.include\n const excludePatterns = config.exclude ?? []\n const filtered: Record<string, unknown> = {}\n\n for (const [field, value] of Object.entries(frontmatter)) {\n if (value === undefined) {\n continue\n }\n const isIncluded = includePatterns.some((pattern) =>\n minimatch(field, pattern),\n )\n const isExcluded = excludePatterns.some((pattern) =>\n minimatch(field, pattern),\n )\n if (isIncluded && !isExcluded) {\n filtered[field] = value\n }\n }\n\n return filtered\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Code, Parent} from \"mdast\"\nimport type {MdxJsxAttribute, MdxJsxFlowElement} from \"mdast-util-mdx-jsx\"\nimport {readFile} from \"node:fs/promises\"\nimport {basename, extname, join} from \"node:path\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nimport {kebabCase} from \"@qualcomm-ui/utils/change-case\"\n\nimport type {ImportedModule} from \"../types\"\nimport {\n exists,\n extractRelativeImports,\n removePreviewLines,\n resolveModulePath,\n} from \"../utils\"\n\nasync function collectDemoImports(\n demoCode: string,\n demoFilePath: string,\n visited: Set<string> = new Set(),\n verbose?: boolean,\n): Promise<ImportedModule[]> {\n const modules: ImportedModule[] = []\n const relativeImports = extractRelativeImports(demoCode)\n\n for (const importPath of relativeImports) {\n const resolvedPath = await resolveModulePath(importPath, demoFilePath)\n if (!resolvedPath || visited.has(resolvedPath)) {\n continue\n }\n visited.add(resolvedPath)\n\n try {\n const importContent = await readFile(resolvedPath, \"utf-8\")\n modules.push({\n content: importContent,\n path: resolvedPath,\n })\n const nestedModules = await collectDemoImports(\n importContent,\n resolvedPath,\n visited,\n verbose,\n )\n modules.push(...nestedModules)\n } catch {\n if (verbose) {\n console.log(` Could not read import: ${resolvedPath}`)\n }\n }\n }\n\n return modules\n}\n\n/**\n * Creates a remark plugin that replaces demo JSX elements (QdsDemo, CodeDemo,\n * Demo) with code blocks containing the demo source code from the demos folder.\n * Imported files are added as sibling code blocks immediately after the demo.\n */\nexport function formatDemos(\n demosFolder: string | undefined,\n verbose?: boolean,\n): Plugin {\n return () => async (tree) => {\n const promises: Promise<void>[] = []\n\n visit(\n tree,\n \"mdxJsxFlowElement\",\n (\n node: MdxJsxFlowElement,\n index: number | undefined,\n parent: Parent | undefined,\n ) => {\n if (\n !node?.name ||\n ![\"QdsDemo\", \"CodeDemo\", \"Demo\"].includes(node.name)\n ) {\n return\n }\n\n const nameAttr = node.attributes?.find(\n (attr): attr is MdxJsxAttribute =>\n attr.type === \"mdxJsxAttribute\" && attr.name === \"name\",\n )\n\n const nodeAttr = node.attributes?.find(\n (attr): attr is MdxJsxAttribute =>\n attr.type === \"mdxJsxAttribute\" && attr.name === \"node\",\n )\n\n let demoName: string | undefined\n\n if (nameAttr && typeof nameAttr.value === \"string\") {\n demoName = nameAttr.value\n } else if (nodeAttr?.value && typeof nodeAttr.value !== \"string\") {\n const estree = nodeAttr.value.data?.estree\n if (estree?.body?.[0]?.type === \"ExpressionStatement\") {\n const expression = estree.body[0].expression\n if (\n expression.type === \"MemberExpression\" &&\n expression.object.type === \"Identifier\" &&\n expression.object.name === \"Demo\" &&\n expression.property.type === \"Identifier\"\n ) {\n demoName = expression.property.name\n }\n }\n }\n\n if (!demoName) {\n if (parent && index !== undefined) {\n parent.children.splice(index, 1)\n }\n return\n }\n\n promises.push(\n (async () => {\n const kebabName = kebabCase(demoName)\n let filePath = `${kebabName}.tsx`\n\n if (!demosFolder) {\n if (verbose) {\n console.log(` No demos folder for ${demoName}`)\n }\n if (parent && index !== undefined) {\n parent.children.splice(index, 1)\n }\n return\n }\n\n let demoFilePath = join(demosFolder, filePath)\n let isAngularDemo = false\n\n if (!(await exists(demoFilePath))) {\n demoFilePath = join(demosFolder, `${kebabName}.ts`)\n if (await exists(demoFilePath)) {\n isAngularDemo = true\n filePath = `${kebabCase(demoName).replace(\"-component\", \".component\")}.ts`\n demoFilePath = join(demosFolder, filePath)\n } else {\n console.log(` Demo not found ${demoName}`)\n if (parent && index !== undefined) {\n parent.children.splice(index, 1)\n }\n return\n }\n }\n\n try {\n const demoCode = await readFile(demoFilePath, \"utf-8\")\n const cleanedCode = removePreviewLines(demoCode)\n\n if (verbose) {\n console.log(` Replaced demo ${demoName} with source code`)\n }\n\n const demoCodeBlock: Code = {\n lang: isAngularDemo ? \"angular-ts\" : \"tsx\",\n meta: null,\n type: \"code\",\n value: cleanedCode,\n }\n\n const importedModules = await collectDemoImports(\n demoCode,\n demoFilePath,\n new Set(),\n verbose,\n )\n\n if (\n importedModules.length === 0 ||\n !parent ||\n index === undefined\n ) {\n Object.assign(node, demoCodeBlock)\n } else {\n const nodesToInsert: Code[] = [demoCodeBlock]\n\n for (const importedModule of importedModules) {\n const ext = extname(importedModule.path).slice(1)\n const filename = basename(importedModule.path)\n nodesToInsert.push({\n lang: ext,\n meta: `title=\"${filename}\"`,\n type: \"code\",\n value: importedModule.content,\n })\n }\n\n parent.children.splice(index, 1, ...nodesToInsert)\n\n if (verbose) {\n console.log(\n ` Added ${importedModules.length} imported file(s) after demo`,\n )\n }\n }\n } catch (error) {\n if (verbose) {\n console.log(`Error reading demo ${demoName}`, error)\n }\n if (parent && index !== undefined) {\n parent.children.splice(index, 1)\n }\n }\n })(),\n )\n },\n )\n\n await Promise.all(promises)\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {createHash} from \"node:crypto\"\nimport {access, readFile} from \"node:fs/promises\"\nimport {dirname, join, resolve} from \"node:path\"\nimport ts from \"typescript\"\n\nimport type {ImportedModule} from \"./types\"\n\nexport async function exists(dirPath: string): Promise<boolean> {\n return access(dirPath)\n .then(() => true)\n .catch(() => false)\n}\n\nexport function computeMd5(content: string): string {\n return createHash(\"md5\").update(content).digest(\"hex\")\n}\n\nexport function isPreviewLine(trimmedLine: string): boolean {\n return (\n trimmedLine === \"// preview\" ||\n /^\\{\\s*\\/\\*\\s*preview\\s*\\*\\/\\s*\\}$/.test(trimmedLine) ||\n /^<!--\\s*preview\\s*-->$/.test(trimmedLine)\n )\n}\n\nexport function removePreviewLines(code: string): string {\n return code\n .split(\"\\n\")\n .filter((line) => !isPreviewLine(line.trim()))\n .join(\"\\n\")\n}\n\nexport function getIntroLines(projectName?: string, description?: string) {\n const lines: string[] = []\n\n if (projectName) {\n lines.push(`# ${projectName}`)\n }\n\n if (description) {\n lines.push(\"\")\n lines.push(`> ${description}`)\n }\n\n return lines.join(\"\\n\")\n}\n\nexport function extractRelativeImports(content: string): string[] {\n const sourceFile = ts.createSourceFile(\n \"temp.ts\",\n content,\n ts.ScriptTarget.Latest,\n false,\n ts.ScriptKind.TSX,\n )\n\n const imports: string[] = []\n\n for (const statement of sourceFile.statements) {\n if (\n ts.isImportDeclaration(statement) &&\n ts.isStringLiteral(statement.moduleSpecifier)\n ) {\n const path = statement.moduleSpecifier.text\n if (path.startsWith(\".\")) {\n imports.push(path)\n }\n }\n }\n\n return imports\n}\n\nexport async function resolveModulePath(\n importPath: string,\n fromFile: string,\n): Promise<string | null> {\n const fromDir = dirname(fromFile)\n const baseResolved = resolve(fromDir, importPath)\n const extensions = [\".ts\", \".tsx\", \".js\", \".jsx\", \"\"]\n for (const ext of extensions) {\n const fullPath = baseResolved + ext\n if (await exists(fullPath)) {\n return fullPath\n }\n }\n if (await exists(baseResolved)) {\n const indexPath = join(baseResolved, \"index.ts\")\n if (await exists(indexPath)) {\n return indexPath\n }\n }\n return null\n}\n\nexport function extractMetadata(\n metadata: Record<string, string> | undefined,\n): [string, string][] {\n return Object.entries(metadata ?? {})\n}\n\nexport async function collectRelativeImports(\n filePath: string,\n visited: Set<string> = new Set(),\n verbose?: boolean,\n): Promise<ImportedModule[]> {\n const normalizedPath = resolve(filePath)\n if (visited.has(normalizedPath)) {\n return []\n }\n visited.add(normalizedPath)\n const modules: ImportedModule[] = []\n try {\n const content = await readFile(normalizedPath, \"utf-8\")\n const relativeImports = extractRelativeImports(content)\n for (const importPath of relativeImports) {\n const resolvedPath = await resolveModulePath(importPath, normalizedPath)\n if (!resolvedPath) {\n if (verbose) {\n console.log(\n ` Could not resolve import: ${importPath} from ${normalizedPath}`,\n )\n }\n continue\n }\n const importContent = await readFile(resolvedPath, \"utf-8\")\n modules.push({\n content: importContent,\n path: resolvedPath,\n })\n const nestedModules = await collectRelativeImports(\n resolvedPath,\n visited,\n verbose,\n )\n modules.push(...nestedModules)\n }\n } catch (error) {\n if (verbose) {\n console.log(`Error processing ${normalizedPath}`, error)\n }\n }\n return modules\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Parent} from \"mdast\"\nimport type {MdxJsxAttribute, MdxJsxFlowElement} from \"mdast-util-mdx-jsx\"\nimport {readFile} from \"node:fs/promises\"\nimport {dirname, join, resolve} from \"node:path\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nimport type {SimplifiedProp} from \"@qualcomm-ui/mdx-common\"\nimport type {\n QuiComment,\n QuiCommentDisplayPart,\n} from \"@qualcomm-ui/typedoc-common\"\n\nimport {extractNamesFromAttribute} from \"../../mdx-utils\"\nimport type {ComponentProps, DocProps, PropInfo} from \"../types\"\nimport {exists} from \"../utils\"\n\nfunction extractBestType(propInfo: PropInfo): string {\n const type = propInfo.resolvedType?.prettyType || propInfo.type\n\n return cleanType(type.startsWith(\"| \") ? type.substring(2) : type)\n}\n\nfunction extractRequired(propInfo: PropInfo, isPartial: boolean): boolean {\n return Boolean(propInfo.resolvedType?.required && !isPartial)\n}\n\nfunction cleanType(type: string): string {\n return type.replace(/\\n/g, \" \").replace(/\\s+/g, \" \").trim()\n}\n\nfunction cleanDefaultValue(defaultValue: string): string {\n return defaultValue.replace(/^\\n+/, \"\").replace(/\\n+$/, \"\").trim()\n}\n\nfunction escapeText(value: string): string {\n return value.replace(/\\n/g, \" \")\n}\n\nfunction propsToDefinitionList(props: SimplifiedProp[]): string {\n if (props.length === 0) {\n return \"\"\n }\n\n return props\n .map((prop) => {\n const parts = [`- **${prop.name}** (\\`${escapeText(prop.type)}\\``]\n\n if (prop.defaultValue) {\n parts.push(`, default: \\`${escapeText(prop.defaultValue)}\\``)\n }\n if (prop.required) {\n parts.push(\", required\")\n }\n\n parts.push(\")\")\n\n if (prop.description) {\n parts.push(` - ${escapeText(prop.description)}`)\n }\n\n return parts.join(\"\")\n })\n .join(\"\\n\")\n}\n\nexport interface PropFormatterOptions {\n docPropsPath?: string\n routeDir: string\n verbose?: boolean\n}\n\nexport class PropFormatter {\n private docProps: DocProps | null = null\n private readonly docPropsPath?: string\n private readonly routeDir: string\n private readonly verbose: boolean\n\n constructor(options: PropFormatterOptions) {\n this.docPropsPath = options.docPropsPath\n this.routeDir = options.routeDir\n this.verbose = options.verbose ?? false\n }\n\n async loadDocProps(): Promise<DocProps | null> {\n if (this.docProps) {\n return this.docProps\n }\n const resolvedDocPropsPath = this.docPropsPath\n ? (await exists(this.docPropsPath))\n ? this.docPropsPath\n : resolve(process.cwd(), this.docPropsPath)\n : join(dirname(this.routeDir), \"doc-props.json\")\n\n if (!(await exists(resolvedDocPropsPath))) {\n if (this.verbose) {\n console.log(`Doc props file not found at: ${resolvedDocPropsPath}`)\n }\n return null\n }\n\n try {\n const content = await readFile(resolvedDocPropsPath, \"utf-8\")\n const docProps = JSON.parse(content) as DocProps\n if (this.verbose) {\n console.log(`Loaded doc props from: ${resolvedDocPropsPath}`)\n console.log(\n `Found ${Object.keys(docProps.props).length} component types`,\n )\n }\n this.docProps = docProps\n return docProps\n } catch (error) {\n if (this.verbose) {\n console.log(\"Error loading doc props\", error)\n }\n return null\n }\n }\n\n private formatCommentParts(parts: QuiCommentDisplayPart[]): string {\n return parts\n .map((part) => {\n switch (part.kind) {\n case \"text\":\n return part.text\n case \"code\":\n const codeText = part.text\n .replace(/```\\w*\\n?/g, \"\") // Remove opening code blocks with optional language\n .replace(/\\n?```/g, \"\") // Remove closing code blocks\n .trim()\n\n if (codeText.includes(\"\\n\")) {\n return `\\`\\`\\`\\n${codeText}\\n\\`\\`\\``\n } else {\n return codeText\n }\n default:\n if (\n \"tag\" in part &&\n part.tag === \"@link\" &&\n typeof part.target === \"string\"\n ) {\n if (part.text === \"Learn more\") {\n return \"\"\n }\n }\n return part.text\n }\n })\n .join(\"\")\n .replace(/\\n/g, \" \")\n .replace(/\\s+/g, \" \")\n .trim()\n }\n\n private formatComment(comment: QuiComment | null): string {\n if (!comment) {\n return \"\"\n }\n\n const parts: string[] = []\n\n if (comment.summary && comment.summary.length > 0) {\n const summaryText = this.formatCommentParts(comment.summary)\n if (summaryText.trim()) {\n parts.push(summaryText.trim())\n }\n }\n\n if (comment.blockTags && comment.blockTags.length > 0) {\n for (const blockTag of comment.blockTags) {\n const tagContent = this.formatCommentParts(blockTag.content)\n if (tagContent.trim()) {\n const tagName = blockTag.tag.replace(\"@\", \"\")\n\n if (tagName === \"default\" || tagName === \"defaultValue\") {\n continue\n }\n\n if (tagName === \"example\") {\n parts.push(`**Example:**\\n\\`\\`\\`\\n${tagContent.trim()}\\n\\`\\`\\``)\n } else {\n parts.push(`**${tagName}:** ${tagContent.trim()}`)\n }\n }\n }\n }\n\n return parts.join(\"\\n\\n\")\n }\n\n extractProps(props: ComponentProps, isPartial: boolean): SimplifiedProp[] {\n const propsInfo: SimplifiedProp[] = []\n\n if (props.props?.length) {\n propsInfo.push(\n ...props.props.map((prop) => this.convertPropInfo(prop, isPartial)),\n )\n }\n if (props.input?.length) {\n propsInfo.push(\n ...props.input.map((prop) =>\n this.convertPropInfo(prop, isPartial, \"input\"),\n ),\n )\n }\n if (props.output?.length) {\n propsInfo.push(\n ...props.output.map((prop) =>\n this.convertPropInfo(prop, isPartial, \"output\"),\n ),\n )\n }\n\n return propsInfo\n }\n\n private convertPropInfo(\n propInfo: PropInfo,\n isPartial: boolean,\n propType: \"input\" | \"output\" | undefined = undefined,\n ): SimplifiedProp {\n return {\n name: propInfo.name,\n type: extractBestType(propInfo),\n ...(propInfo.defaultValue && {\n defaultValue: cleanDefaultValue(propInfo.defaultValue),\n }),\n description: this.formatComment(propInfo.comment || null),\n propType,\n required: extractRequired(propInfo, isPartial) || undefined,\n }\n }\n\n /**\n * Creates a remark plugin that replaces TypeDocProps JSX elements with\n * Markdown tables containing component prop documentation.\n */\n propsToMarkdownList(): Plugin {\n return () => (tree, _file, done) => {\n visit(\n tree,\n \"mdxJsxFlowElement\",\n (\n node: MdxJsxFlowElement,\n index: number | undefined,\n parent: Parent | undefined,\n ) => {\n if (node?.name !== \"TypeDocProps\") {\n return\n }\n const nameAttr = node.attributes?.find(\n (attr): attr is MdxJsxAttribute =>\n attr.type === \"mdxJsxAttribute\" && attr.name === \"name\",\n )\n const isPartial = node.attributes?.some(\n (attr): attr is MdxJsxAttribute =>\n attr.type === \"mdxJsxAttribute\" && attr.name === \"partial\",\n )\n if (!this.docProps || !nameAttr) {\n if (parent && index !== undefined) {\n parent.children.splice(index, 1)\n }\n return\n }\n const propsNames = extractNamesFromAttribute(nameAttr)\n if (propsNames.length === 0) {\n if (parent && index !== undefined) {\n parent.children.splice(index, 1)\n }\n return\n }\n const propsName = propsNames[0]\n const componentProps = this.docProps.props[propsName]\n if (!componentProps) {\n if (this.verbose) {\n console.log(` TypeDocProps not found: ${propsName}`)\n }\n if (parent && index !== undefined) {\n parent.children.splice(index, 1)\n }\n return\n }\n const propTypes = this.extractProps(\n componentProps,\n Boolean(isPartial),\n )\n if (this.verbose) {\n console.log(\n ` Replaced TypeDocProps ${propsName} with API documentation`,\n )\n }\n\n const regularProps = propTypes.filter((p) => p.propType === undefined)\n const inputs = propTypes.filter((p) => p.propType === \"input\")\n const outputs = propTypes.filter((p) => p.propType === \"output\")\n\n const sections: string[] = []\n\n if (regularProps.length > 0) {\n sections.push(propsToDefinitionList(regularProps))\n }\n\n if (inputs.length > 0) {\n sections.push(`**Inputs**\\n\\n${propsToDefinitionList(inputs)}`)\n }\n\n if (outputs.length > 0) {\n sections.push(`**Outputs**\\n\\n${propsToDefinitionList(outputs)}`)\n }\n\n const markdownContent = sections.join(\"\\n\\n\")\n\n if (!markdownContent) {\n if (parent && index !== undefined) {\n parent.children.splice(index, 1)\n }\n return\n }\n\n Object.assign(node, {\n data: {typeDocProps: {name: propsName, props: propTypes}},\n lang: null,\n meta: null,\n type: \"code\",\n value: markdownContent,\n })\n },\n )\n done()\n }\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Text} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nimport {isSpoilerBlock, isStepBlock} from \"../../../remark\"\n\nexport const filterTextDirectives: Plugin = () => {\n return (tree, _file, done) => {\n visit(tree, \"text\", (node: Text) => {\n const value = node.value?.trim?.()\n if (value && (isStepBlock(value) || isSpoilerBlock(value))) {\n Object.assign(node, {\n value: ``,\n })\n }\n })\n done()\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Parent} from \"mdast\"\nimport type {MdxJsxAttribute, MdxJsxFlowElement} from \"mdast-util-mdx-jsx\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nimport {extractNamesFromAttribute} from \"../../mdx-utils\"\n\nexport const formatNpmInstallTabs: Plugin = () => {\n return (tree, _file, done) => {\n visit(\n tree,\n \"mdxJsxFlowElement\",\n (\n node: MdxJsxFlowElement,\n index: number | undefined,\n parent: Parent | undefined,\n ) => {\n if (node?.name === \"NpmInstallTabs\") {\n const packages = node.attributes?.find(\n (attr): attr is MdxJsxAttribute =>\n attr.type === \"mdxJsxAttribute\" && attr.name === \"packages\",\n )\n const packageNames = packages\n ? extractNamesFromAttribute(packages)\n : []\n\n if (packageNames.length === 0) {\n if (parent && index !== undefined) {\n parent.children.splice(index, 1)\n }\n return\n }\n\n Object.assign(node, {\n lang: \"shell\",\n meta: null,\n type: \"code\",\n value: `npm install ${packageNames.join(\" \")}`,\n })\n }\n },\n )\n done()\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {MdxJsxAttribute, MdxJsxFlowElement} from \"mdast-util-mdx-jsx\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nfunction themeDataToJson(data: unknown, cssPropertyName?: string): string {\n if (!data || typeof data !== \"object\") {\n return \"\"\n }\n\n if (cssPropertyName) {\n return JSON.stringify({cssProperty: cssPropertyName, data}, null, 2)\n }\n\n return JSON.stringify(data, null, 2)\n}\n\nfunction getPath(obj: Record<string, unknown>, path: string): unknown {\n return path\n .split(\".\")\n .reduce<unknown>(\n (acc, key) =>\n acc && typeof acc === \"object\"\n ? (acc as Record<string, unknown>)[key]\n : undefined,\n obj,\n )\n}\n\nfunction getAttrExpression(\n node: MdxJsxFlowElement,\n name: string,\n): string | null {\n const attr = node.attributes?.find(\n (a): a is MdxJsxAttribute =>\n a.type === \"mdxJsxAttribute\" && a.name === name,\n )\n if (!attr?.value) {\n return null\n }\n if (typeof attr.value === \"string\") {\n return attr.value\n } else if (typeof attr.value === \"object\" && \"value\" in attr.value) {\n return attr.value.value\n }\n return null\n}\n\n/**\n * Creates a remark plugin that replaces theme JSX elements with\n * markdown tables containing theme data from.\n */\nexport async function formatThemeNodes(): Promise<Plugin> {\n let themes: any | null = null\n try {\n // may not be available since this is an optional dependency\n themes = await import(\"@qualcomm-ui/tailwind-plugin/theme\")\n } catch {\n return () => {}\n }\n\n const handlers: Record<string, (node: MdxJsxFlowElement) => unknown> = {\n ColorTable: (node) => {\n const path = getAttrExpression(node, \"data\")\n return path && getPath(themes, path)\n },\n FontTable: (node) => {\n const path = getAttrExpression(node, \"data\")\n return path && getPath(themes, path)\n },\n SpacingTable: (node) => {\n const path = getAttrExpression(node, \"data\")\n return path && getPath(themes, path)\n },\n ThemePropertyTable: (node) => {\n const path = getAttrExpression(node, \"data\")\n const property = getAttrExpression(node, \"cssProperty\")\n const data = path && getPath(themes, path)\n return path && property ? {cssPropertyName: property, data} : undefined\n },\n }\n\n return () => (tree, _file, done) => {\n visit(tree, \"mdxJsxFlowElement\", (node: MdxJsxFlowElement) => {\n const handler = node.name && handlers[node.name]\n if (!handler) {\n return\n }\n\n const data = handler(node)\n if (!data) {\n console.warn(`No theme data for ${node.name}`)\n return\n }\n\n let markdownTable: string\n if (\n typeof data === \"object\" &&\n data !== null &&\n \"cssPropertyName\" in data &&\n \"data\" in data\n ) {\n const {cssPropertyName, data: themeData} = data as {\n cssPropertyName: string\n data: unknown\n }\n markdownTable = themeDataToJson(themeData, cssPropertyName)\n } else {\n markdownTable = themeDataToJson(data)\n }\n\n if (!markdownTable) {\n return\n }\n\n Object.assign(node, {\n lang: \"json\",\n meta: null,\n type: \"code\",\n value: markdownTable,\n })\n })\n done()\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Code, Link, Parent, Root, RootContent, Text} from \"mdast\"\nimport {toString} from \"mdast-util-to-string\"\nimport remarkGfm from \"remark-gfm\"\nimport remarkStringify from \"remark-stringify\"\nimport {type Plugin, unified} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nimport type {\n CodeExample,\n PageEntry,\n PageHeading,\n SectionEntry,\n SectionTypes,\n SimplifiedProp,\n} from \"@qualcomm-ui/mdx-common\"\n\nimport {isSpoilerBlock, isStepBlock} from \"../../remark\"\nimport {SlugGenerator, slugify} from \"../create-slug\"\n\nimport {computeMd5} from \"./utils\"\n\nexport interface SectionExtractorOptions {\n /**\n * Header depths that define section boundaries.\n * @default [1, 2, 3, 4]\n */\n depths?: number[]\n\n /**\n * Minimum content length to create a section entry.\n * @default 0\n */\n minContentLength?: number\n\n /**\n * Prefix to use for page IDs.\n */\n pageIdPrefix?: string\n}\n\nexport interface PageInfo {\n frontmatter: Record<string, unknown>\n id: string\n pathname: string\n title: string\n url?: string\n}\n\ninterface HeaderInfo {\n depth: number\n text: string\n}\n\ninterface PendingSection {\n anchorId?: string\n headerPath: string[]\n headingLevel: number\n nodes: RootContent[]\n startIndex: number\n}\n\nexport interface ExtractionResult {\n sections: SectionEntry[]\n toc: PageHeading[]\n}\n\n/**\n * Extracts sections from processed markdown content, organized by headers.\n */\nexport class SectionExtractor {\n private readonly depths: Set<number>\n private readonly minContentLength: number\n private readonly pageIdPrefix: string\n\n constructor(options?: SectionExtractorOptions) {\n const defaultDepths = [1, 2, 3, 4]\n this.depths = new Set(options?.depths ?? defaultDepths)\n this.minContentLength = options?.minContentLength ?? 0\n this.pageIdPrefix = options?.pageIdPrefix ?? \"\"\n }\n\n /**\n * Extracts sections from a parsed AST and generates a table of contents.\n */\n extract(tree: Root, pageInfo: PageInfo): ExtractionResult {\n const sections: SectionEntry[] = []\n const toc: PageHeading[] = []\n const headerStack: HeaderInfo[] = [{depth: 1, text: pageInfo.title}]\n const slugGenerator = new SlugGenerator()\n\n let pendingSection: PendingSection | null = null\n\n const finalizeSection = () => {\n if (!pendingSection || pendingSection.nodes.length === 0) {\n return\n }\n\n const entry = this.buildSectionEntry(pendingSection, pageInfo)\n if (entry && entry.content.length >= this.minContentLength) {\n sections.push(entry)\n }\n }\n\n for (let i = 0; i < tree.children.length; i++) {\n const node = tree.children[i]\n\n if (node.type === \"yaml\") {\n continue\n }\n\n if (node.type === \"heading\") {\n const heading = node\n\n if (!this.depths.has(heading.depth)) {\n if (pendingSection) {\n pendingSection.nodes.push(node)\n } else {\n pendingSection = {\n headerPath: headerStack.map((h) => h.text),\n headingLevel: headerStack[headerStack.length - 1]?.depth ?? 1,\n nodes: [],\n startIndex: i,\n }\n }\n continue\n }\n\n finalizeSection()\n\n while (\n headerStack.length > 0 &&\n headerStack[headerStack.length - 1].depth >= heading.depth\n ) {\n headerStack.pop()\n }\n\n const headingText = toString(heading)\n headerStack.push({depth: heading.depth, text: headingText})\n\n let anchorId: string | undefined\n // h1 headings are page titles \u2014 don't include in ToC\n if (heading.depth > 1) {\n anchorId = slugGenerator.createSlug(headingText)\n toc.push({\n headingLevel: heading.depth,\n id: anchorId,\n tagName: `h${heading.depth}`,\n textContent: headingText,\n })\n }\n\n pendingSection = {\n anchorId,\n headerPath: headerStack.map((h) => h.text),\n headingLevel: heading.depth,\n nodes: [],\n startIndex: i,\n }\n } else if (pendingSection) {\n pendingSection.nodes.push(node)\n } else {\n pendingSection = {\n headerPath: headerStack.map((h) => h.text),\n headingLevel: headerStack[headerStack.length - 1]?.depth ?? 1,\n nodes: [node],\n startIndex: i,\n }\n }\n }\n\n finalizeSection()\n\n return {sections, toc}\n }\n\n /**\n * Extracts the entire page as a single entry with full raw markdown content.\n */\n extractPage(tree: Root, pageInfo: PageInfo): PageEntry | null {\n const nodes = tree.children.filter((node) => node.type !== \"yaml\")\n\n if (nodes.length === 0) {\n return null\n }\n\n const content = this.nodesToRawContent(nodes).trim()\n\n if (!content) {\n return null\n }\n\n const hashData = {\n content,\n pageId: `${this.pageIdPrefix}${pageInfo.id}`,\n pathname: pageInfo.pathname,\n }\n const hash = computeMd5(JSON.stringify(hashData))\n\n return {\n content,\n hash,\n pageId: `${this.pageIdPrefix}${pageInfo.id}`,\n pathname: pageInfo.pathname,\n title: pageInfo.title,\n }\n }\n\n private buildSectionEntry(\n section: PendingSection,\n pageInfo: PageInfo,\n ): SectionEntry | null {\n const {nodes, terms} = this.extractTerms(section.nodes)\n\n const contentNodes: RootContent[] = []\n const codeExamples: CodeExample[] = []\n\n const sectionTypes: SectionTypes[] = []\n for (const node of nodes) {\n if (node.type === \"code\") {\n const codeNode = node as Code & {\n data?: {typeDocProps?: {name: string; props: SimplifiedProp[]}}\n }\n\n if (codeNode.data?.typeDocProps) {\n const {name, props} = codeNode.data.typeDocProps\n sectionTypes.push({props, type: name})\n }\n\n codeExamples.push({\n code: codeNode.value,\n language: codeNode.lang ?? \"\",\n })\n } else if (\n node.type === \"text\" &&\n (isStepBlock(node.value.trim()) || isSpoilerBlock(node.value.trim()))\n ) {\n // continue\n } else {\n contentNodes.push(node)\n }\n }\n\n const rawContent = this.nodesToRawContent(nodes)\n const content = this.nodesToContent(contentNodes)\n\n const sectionId = this.generateSectionId(section.headerPath)\n const url =\n pageInfo.url && section.anchorId\n ? `${pageInfo.url}#${section.anchorId}`\n : undefined\n\n const hashData = {\n headerPath: section.headerPath,\n pageFrontmatter: Object.keys(pageInfo.frontmatter).length\n ? pageInfo.frontmatter\n : undefined,\n pageId: `${this.pageIdPrefix}${pageInfo.id}`,\n rawContent: rawContent.trim(),\n terms: terms.length ? terms : undefined,\n types: sectionTypes.length ? sectionTypes : undefined,\n url,\n }\n const sectionHash = computeMd5(JSON.stringify(hashData))\n\n return {\n ...hashData,\n codeExamples: codeExamples.length ? codeExamples : undefined,\n content: content.trim(),\n hash: sectionHash,\n headingLevel: section.headingLevel,\n sectionId,\n }\n }\n\n private extractTerms(nodes: RootContent[]): {\n nodes: RootContent[]\n terms: string[]\n } {\n const filteredNodes: RootContent[] = []\n const terms: string[] = []\n\n for (const node of nodes) {\n if (node.type === \"paragraph\") {\n const children = (node as Parent).children ?? []\n const firstChild = children[0]\n if (firstChild?.type === \"text\") {\n const firstText = firstChild.value\n const termsMatch = firstText.match(/^:::\\s*terms\\s*/)\n\n if (termsMatch) {\n // Collect text from all children (handles soft breaks in multiline\n // blocks)\n let fullText = firstText\n for (let i = 1; i < children.length; i++) {\n const child = children[i] as {type: string; value?: string}\n if (child.type === \"text\") {\n fullText += child.value\n } else if (child.type === \"softBreak\") {\n fullText += \"\\n\"\n }\n }\n\n const parsedTerms = this.parseTermsBlock(fullText)\n terms.push(...parsedTerms)\n continue\n }\n }\n }\n filteredNodes.push(node)\n }\n\n return {nodes: filteredNodes, terms}\n }\n\n private parseTermsBlock(text: string): string[] {\n const afterOpen = text.replace(/^:::\\s*terms\\s*/, \"\")\n const closeIndex = afterOpen.lastIndexOf(\":::\")\n const content =\n closeIndex !== -1 ? afterOpen.slice(0, closeIndex) : afterOpen\n\n return content\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line && line !== \":::\")\n }\n\n /**\n * Convert links to inline code. URLs are not relevant for text embeddings\n * and will muddy the vector storage.\n */\n private transformLinks(): Plugin {\n return () => (tree) => {\n visit(tree, \"link\", (node: Link) => {\n let text = \"\"\n visit(node, \"text\", (textNode: Text) => {\n text += textNode.value\n })\n\n Object.assign(node, {\n children: undefined,\n type: \"inlineCode\",\n url: undefined,\n value: text,\n })\n })\n }\n }\n\n private nodesToRawContent(nodes: RootContent[]): string {\n const tree: Root = {children: nodes, type: \"root\"}\n const processor = unified().use(remarkGfm).use(remarkStringify)\n return processor.stringify(tree)\n }\n\n private nodesToContent(nodes: RootContent[]): string {\n const tree: Root = {children: structuredClone(nodes), type: \"root\"}\n const processor = unified()\n .use(remarkGfm)\n .use(this.transformLinks())\n .use(remarkStringify)\n const transformed = processor.runSync(tree) as Root\n return processor.stringify(transformed)\n }\n\n private generateSectionId(headerPath: string[]): string {\n return headerPath.map((h) => slugify(h)).join(\"-\")\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport chalk from \"chalk\"\nimport type {Root} from \"mdast\"\n\nimport type {\n NavItem,\n PageFrontmatter,\n PageMap,\n PageSection,\n SectionEntry,\n} from \"@qualcomm-ui/mdx-common\"\nimport type {QuiPropTypes} from \"@qualcomm-ui/typedoc-common\"\nimport {defined} from \"@qualcomm-ui/utils/guard\"\n\nimport type {SearchIndexerOptions} from \"./config\"\nimport {DocPropsIndexer} from \"./doc-props\"\nimport {\n buildGitMetadataMap,\n type CompiledMdxFile,\n type CompiledMdxFileMetadata,\n createRemarkProcessor,\n type IndexedPage,\n type IndexedSection,\n MdxFileReader,\n} from \"./markdown\"\nimport {\n type PageInfo,\n SectionExtractor,\n} from \"./markdown/knowledge/section-extractor\"\nimport {\n filterFileGlob,\n getCategoriesFromPathSegments,\n getPathnameFromPathSegments,\n getPathSegmentsFromFileName,\n getRouteMeta,\n NavBuilder,\n transformRouteMetaArray,\n} from \"./nav-builder\"\nimport type {RouteMetaInternal, RouteMetaNavInternal} from \"./nav-builder/types\"\nimport {fixPath} from \"./path-utils\"\n\nexport class SearchIndexer {\n private readonly docPropsIndexer: DocPropsIndexer\n private readonly sectionExtractor: SectionExtractor\n private readonly navBuilder: NavBuilder\n private readonly mdxFileReader: MdxFileReader\n private readonly allowedHeadings: Set<string>\n private readonly metaJson: RouteMetaInternal\n private readonly routeMetaNav: Record<string, RouteMetaNavInternal> = {}\n readonly config: SearchIndexerOptions\n logWarnings: boolean\n\n get cachedFileCount(): number {\n return this.mdxFileReader.cachedFileCount\n }\n\n get pageDocProps(): Record<string, Record<string, QuiPropTypes>> {\n return this._pageDocProps\n }\n private _pageDocProps: Record<string, Record<string, QuiPropTypes>> = {}\n\n get mdxFileCount(): number {\n return this._mdxFileCount\n }\n private _mdxFileCount: number = 0\n\n get navItems(): NavItem[] {\n return this.navBuilder.navItems\n }\n\n get pageMap(): PageMap {\n return this._pageMap\n }\n private _pageMap: PageMap = {}\n\n get searchIndex(): PageSection[] {\n return this._searchIndex\n }\n private _searchIndex: PageSection[] = []\n\n reset(): void {\n this.mdxFileReader.reset()\n this._pageMap = {}\n this._searchIndex = []\n }\n\n constructor(\n config: SearchIndexerOptions,\n logWarnings = true,\n // enable composition by making these classes replaceable\n addons: {\n docPropsIndexer?: DocPropsIndexer\n mdxFileReader?: MdxFileReader\n navBuilder?: NavBuilder\n sectionExtractor?: SectionExtractor\n } = {},\n ) {\n this.config = config\n this.logWarnings = logWarnings\n this.allowedHeadings = new Set<string>(\n Array.from(config?.headings || [\"h2\", \"h3\", \"h4\"]),\n )\n this.metaJson = transformRouteMetaArray(\n this.config.navConfig ?? [],\n this.routeMetaNav,\n )\n\n const headingDepths = Array.from(this.allowedHeadings).map((h) =>\n parseInt(h.charAt(1)),\n )\n this.sectionExtractor =\n addons.sectionExtractor ||\n new SectionExtractor({depths: [1, ...headingDepths]})\n this.navBuilder =\n addons.navBuilder || new NavBuilder(this.metaJson, this.routeMetaNav)\n this.docPropsIndexer =\n addons.docPropsIndexer ||\n new DocPropsIndexer(this.config.typeDocProps ?? {})\n this.mdxFileReader =\n addons.mdxFileReader ||\n new MdxFileReader(\n process.env.NODE_ENV === \"development\" && !this.config.disableCache,\n this.config.pageTimestampMetadata,\n )\n }\n\n /**\n * Resolves a page's properties from the combined frontmatter and RouteMeta.\n * RouteMeta properties take precedence.\n */\n private getPageEntry(\n filepath: string,\n frontmatter: Partial<PageFrontmatter>,\n ): PageSection {\n const pagePath = filepath.replace(this.config.srcDir, \"\")\n\n const pathSegments = getPathSegmentsFromFileName(\n pagePath,\n this.config.pageDirectory,\n this.config.routingStrategy,\n )\n\n const pathname = getPathnameFromPathSegments(pathSegments)\n\n const routeMeta =\n getRouteMeta(\n pathSegments.length === 0\n ? frontmatter.id\n ? [frontmatter.id]\n : [\"_index\"]\n : pathSegments,\n this.metaJson,\n ) ?? {}\n\n return {\n categories:\n frontmatter.categories ??\n getCategoriesFromPathSegments(\n pathSegments,\n this.metaJson,\n routeMeta?.title || frontmatter.title || \"\",\n ),\n description: frontmatter.description,\n hidden: defined(routeMeta.hidden) ? routeMeta.hidden : frontmatter.hidden,\n hideBreadcrumbs: defined(routeMeta.hideBreadcrumbs)\n ? routeMeta.hideBreadcrumbs\n : frontmatter.hideBreadcrumbs,\n hideFromSearch: defined(routeMeta.hideFromSearch)\n ? routeMeta.hideFromSearch\n : frontmatter.hideFromSearch,\n hidePageLinks: defined(routeMeta.hidePageLinks)\n ? routeMeta.hidePageLinks\n : frontmatter.hidePageLinks,\n hideSideNav: defined(routeMeta.hideSideNav)\n ? routeMeta.hideSideNav\n : frontmatter.hideSideNav,\n hideToc: defined(routeMeta.hideToc)\n ? routeMeta.hideToc\n : frontmatter.hideToc,\n id: pagePath,\n pathname,\n pathSegments,\n restricted: defined(routeMeta.restricted)\n ? routeMeta.restricted\n : frontmatter.restricted,\n title: defined(routeMeta.title)\n ? routeMeta.title || \"\"\n : frontmatter.title || \"\",\n updatedBy: frontmatter.updatedBy,\n updatedOn: frontmatter.updatedOn,\n }\n }\n\n /**\n * Parses an MDX file to extract the site data for the nav items, doc props,\n * breadcrumbs, and search index.\n */\n private compileMdxFile(filePath: string): CompiledMdxFile {\n const {cached, fileContents, frontmatter} =\n this.mdxFileReader.readFileSync(filePath)\n\n const metadata: CompiledMdxFileMetadata = {\n changed: {},\n filePath,\n }\n\n let previousPage: IndexedPage | undefined = undefined\n\n if (!cached) {\n const previousData = this.mdxFileReader.readCache(filePath)\n if (previousData) {\n const cachedFm = JSON.stringify(previousData.frontmatter)\n const currentFm = JSON.stringify(frontmatter)\n previousPage = previousData.page\n if (cachedFm !== currentFm) {\n metadata.changed.frontmatter = true\n }\n }\n }\n\n this.docPropsIndexer.reset()\n\n const defaultSection: PageSection = this.getPageEntry(filePath, frontmatter)\n if (!defaultSection.categories.length && defaultSection.title) {\n defaultSection.categories = [defaultSection.title]\n }\n\n if (!defaultSection.hidden) {\n this.navBuilder.add(defaultSection, frontmatter)\n }\n\n this._pageMap[defaultSection.pathname] = defaultSection\n\n let indexedPage: IndexedPage\n\n try {\n if (cached?.page) {\n indexedPage = cached.page\n } else {\n const processor = createRemarkProcessor({\n alerts: true,\n extractMeta: {},\n frontmatter: true,\n gfm: true,\n interpolateFrontmatter: frontmatter,\n mdx: true,\n removeJsx: true,\n removeMermaidCodeBlocks: true,\n })\n const tree = processor.runSync(processor.parse(fileContents)) as Root\n const pageInfo: PageInfo = {\n frontmatter: frontmatter as unknown as Record<string, unknown>,\n id: defaultSection.id,\n pathname: defaultSection.pathname,\n title: defaultSection.title,\n url: defaultSection.pathname,\n }\n const {sections, toc} = this.sectionExtractor.extract(tree, pageInfo)\n indexedPage = {sections, toc}\n }\n } catch (error: any) {\n console.debug(\n `${chalk.yellowBright.bold(\n \"Failed to parse mdx page content.\",\n )} ${chalk.blueBright.bold(filePath)}`,\n )\n\n if (this.config.throwOnError) {\n throw new Error(error)\n }\n\n return {metadata, pageSections: [defaultSection]}\n }\n\n const {sections, toc} = indexedPage\n\n if (previousPage) {\n for (let i = 0; i < toc.length; i++) {\n const previousHeading = previousPage.toc[i]\n const currentHeading = toc[i]\n if (previousHeading?.id !== currentHeading.id) {\n metadata.changed.toc = true\n break\n }\n }\n }\n\n if (toc.length) {\n this._pageMap[defaultSection.pathname].toc = toc\n }\n\n let docPropSections: IndexedSection[] = []\n let docProps: Record<string, QuiPropTypes> = {}\n\n if (this.config.typeDocProps) {\n docPropSections =\n cached?.pageDocPropSections ||\n (this.docPropsIndexer.build(fileContents, toc) ?? [])\n docProps = cached?.pageDocProps || this.docPropsIndexer.getDocProps()\n }\n\n if (docPropSections.length) {\n this._pageDocProps[defaultSection.pathname] = docProps\n }\n\n if (!cached) {\n this.mdxFileReader.updateCache(filePath, fileContents, {\n frontmatter,\n page: indexedPage,\n pageDocProps: docProps,\n pageDocPropSections: docPropSections,\n })\n }\n\n // omit entries from pages that are explicitly omitted from the index.\n if (frontmatter.hideFromSearch) {\n return {metadata, pageSections: [defaultSection]}\n }\n\n if (!sections.length && !docPropSections.length) {\n return {metadata, pageSections: [defaultSection]}\n }\n\n const sectionReturn: PageSection[] = [\n ...this.formatContentSections(sections, defaultSection),\n ]\n\n if (this.config.typeDocPropsOptions?.includeInSearchIndex) {\n sectionReturn.push(\n ...this.formatDocPropSections(docPropSections, defaultSection),\n )\n }\n\n return {metadata, pageSections: sectionReturn}\n }\n\n private formatContentSections(\n sections: SectionEntry[],\n {toc: _toc, ...defaultSection}: PageSection,\n ): PageSection[] {\n return sections.map((section, index): PageSection => {\n const heading = section.headerPath.at(-1) ?? defaultSection.title\n return {\n ...defaultSection,\n content: section.content || undefined,\n heading,\n headingLevel: section.headingLevel,\n href: section.url ?? defaultSection.pathname,\n id: `${defaultSection.id}-${index}`,\n }\n })\n }\n\n private formatDocPropSections(\n sections: IndexedSection[],\n {toc: _toc, ...defaultSection}: PageSection,\n ): PageSection[] {\n return sections.map((section, index): PageSection => {\n const content = section.content.map((c) => c.text.join(\" \")).join(\" \")\n return {\n ...defaultSection,\n content: content || undefined,\n heading: section.heading?.textContent ?? defaultSection.title,\n headingLevel: section.heading?.headingLevel,\n href: section.heading\n ? `${defaultSection.pathname}#${section.heading.id}`\n : defaultSection.pathname,\n id: `${defaultSection.id}-${index}-prop`,\n isDocProp: true,\n }\n })\n }\n\n private compileTsxFile(filepath: string) {\n const entry = this.getPageEntry(filepath, {})\n\n const routeMeta = getRouteMeta(\n entry.pathSegments.length === 0 ? [\"_index\"] : entry.pathSegments,\n this.metaJson,\n )\n\n if (!routeMeta) {\n return null\n }\n\n if (!entry.hidden) {\n this.navBuilder.add(entry, {}, routeMeta)\n }\n\n this._pageMap[entry.pathname] = entry\n\n return entry\n }\n\n buildIndex(\n inputFileGlob: string[],\n logWarnings: boolean = true,\n ): CompiledMdxFile[] {\n this.logWarnings = logWarnings\n this.mdxFileReader.logWarnings = logWarnings\n // Windows path fix\n const fileGlob = inputFileGlob.map(fixPath)\n this.navBuilder.reset()\n this.reset()\n\n const mdxFileGlob = filterFileGlob(\n fileGlob,\n \"mdx\",\n this.config.srcDir,\n this.config.routingStrategy,\n )\n\n this._mdxFileCount = mdxFileGlob.length\n this.mdxFileReader.gitMetadataMap = buildGitMetadataMap(\n this.config.srcDir,\n this.mdxFileReader.pageTimestampMetadata,\n )\n const compiledFiles = mdxFileGlob.map((file) => this.compileMdxFile(file))\n\n const mdxIndex = compiledFiles\n .map((fileData) => fileData.pageSections)\n .flat()\n\n filterFileGlob(\n fileGlob,\n \"tsx\",\n this.config.srcDir,\n this.config.routingStrategy,\n ).map((file) => this.compileTsxFile(file))\n\n this._searchIndex.push(...mdxIndex.filter((entry) => !entry.hideFromSearch))\n\n this.navBuilder.build()\n\n return compiledFiles\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {MdxJsxAttribute} from \"mdast-util-mdx-jsx\"\nimport remarkMdx from \"remark-mdx\"\nimport remarkParse from \"remark-parse\"\nimport remarkStringify from \"remark-stringify\"\nimport {type Plugin, unified} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nimport {\n type PageDocProps,\n type PageHeading,\n type PagePropType,\n UniqueIdService,\n} from \"@qualcomm-ui/mdx-common\"\nimport type {\n QuiPropDeclaration,\n QuiPropTypes,\n} from \"@qualcomm-ui/typedoc-common\"\n\nimport {extractNamesFromAttribute, type IndexedSection} from \"../markdown\"\n\nfunction extractPickPropsRecord(\n node: MdxJsxAttribute,\n): Record<string, string[]> | null {\n if (\n node.name !== \"unionWithPick\" ||\n !node.value ||\n typeof node.value === \"string\"\n ) {\n return null\n }\n\n const estree = node.value.data?.estree\n if (!estree?.body?.[0] || estree.body[0].type !== \"ExpressionStatement\") {\n return null\n }\n\n const expression = estree.body[0].expression\n if (expression.type !== \"ObjectExpression\") {\n return null\n }\n\n const result: Record<string, string[]> = {}\n\n for (const property of expression.properties) {\n if (property.type !== \"Property\" || property.key.type !== \"Identifier\") {\n continue\n }\n\n if (property.value.type !== \"ArrayExpression\") {\n continue\n }\n\n const key = property.key.name\n const values: string[] = []\n\n for (const element of property.value.elements) {\n if (element?.type === \"Literal\" && typeof element.value === \"string\") {\n values.push(element.value)\n }\n }\n\n result[key] = values\n }\n\n return result\n}\n\nconst targetMdxElements: string[] = [\n \"TypeDocProps\",\n \"TypeDocAttributes\",\n \"TypeDocAngularAttributes\",\n]\n\ninterface DocPropEntry {\n name: string\n omitFrom?: string[]\n}\n\nexport class DocPropsIndexer {\n docPropsEntries: DocPropEntry[] = []\n idService: UniqueIdService = new UniqueIdService()\n private readonly props: Record<string, QuiPropTypes>\n private pageDocProps: PageDocProps = {}\n\n constructor(props: Record<string, QuiPropTypes>) {\n this.props = props\n }\n\n reset(): void {\n this.idService.reset()\n this.docPropsEntries = []\n }\n\n /**\n * Finds all JSX `<TypeDocProps />` nodes on the current page and adds their names\n * to an array. Once all nodes have been collected, we process them into\n * `PageSection` entries for the search index.\n */\n getTypeDocPropsNodes: Plugin = () => {\n return (tree, _file, done) => {\n visit(tree, \"mdxJsxFlowElement\", (node: any) => {\n if (node && \"name\" in node && targetMdxElements.includes(node.name)) {\n const nameAttr = node.attributes?.find(\n (attr: MdxJsxAttribute) => attr.name === \"name\",\n )\n const omitFromAttr = node.attributes?.find(\n (attr: MdxJsxAttribute) => attr.name === \"omitFrom\",\n )\n const omitFrom = omitFromAttr\n ? extractNamesFromAttribute(omitFromAttr)\n : undefined\n\n if (nameAttr) {\n const names = extractNamesFromAttribute(nameAttr)\n for (const name of names) {\n this.docPropsEntries.push({name, omitFrom})\n if (name.endsWith(\"Props\")) {\n // also index the corresponding component for lookup on this page.\n this.docPropsEntries.push({name: name.slice(0, -5), omitFrom})\n }\n }\n }\n\n const unionWithPickAttr: MdxJsxAttribute = node.attributes?.find(\n (attr: MdxJsxAttribute) => attr.name === \"unionWithPick\",\n )\n if (unionWithPickAttr) {\n try {\n const unionWithPick = extractPickPropsRecord(unionWithPickAttr)\n if (unionWithPick) {\n this.docPropsEntries.push(\n ...Object.keys(unionWithPick).map((entry) => ({\n name: entry,\n omitFrom,\n })),\n )\n }\n } catch (e) {}\n }\n }\n })\n done()\n }\n }\n\n build(fileContents: string, toc: PageHeading[]): IndexedSection[] | null {\n // parse the Markdown into an AST\n unified()\n .use(remarkMdx)\n // find the TypeDocProp nodes\n .use(this.getTypeDocPropsNodes)\n .use(remarkParse)\n .use(remarkStringify)\n .processSync(fileContents)\n\n if (!this.docPropsEntries.length) {\n return null\n }\n\n for (const item of toc) {\n this.idService.add(item.id)\n }\n\n return this.docPropsEntries\n .map((entry): IndexedSection[] => {\n const propTypes = this.props[entry.name]\n if (!propTypes) {\n return []\n }\n\n const omittedProps = new Set<string>(\n (entry.omitFrom ?? [])\n .map((entry) => {\n const propTypes = this.props[entry]\n if (!propTypes) {\n return []\n }\n return [\n propTypes.props,\n propTypes.input,\n propTypes.output,\n propTypes.publicMethods,\n ].reduce((acc: string[], current) => {\n if (current) {\n acc.push(...current.map((prop) => prop.name))\n }\n return acc\n }, [])\n })\n .flat(1)\n .filter(Boolean),\n )\n\n const sections: IndexedSection[] = []\n\n const assembleProps = (\n propsInput: QuiPropDeclaration[] | undefined,\n ): PagePropType[] | undefined => {\n if (!propsInput) {\n return undefined\n }\n const props: PagePropType[] = []\n for (const prop of propsInput) {\n if (omittedProps.has(prop.name)) {\n continue\n }\n const id = this.idService.add(prop.name)\n props.push({...prop, id})\n sections.push(this.assembleProp(prop, id))\n }\n return props\n }\n\n this.pageDocProps[entry.name] = {\n ...this.props[entry.name],\n input: assembleProps(propTypes.input),\n output: assembleProps(propTypes.output),\n props: assembleProps(propTypes.props),\n publicMethods: assembleProps(propTypes.publicMethods),\n }\n return sections\n })\n .flat()\n }\n\n getDocProps(): PageDocProps {\n return this.docPropsEntries.reduce((acc: PageDocProps, entry) => {\n const propTypes = this.pageDocProps[entry.name]\n // TODO: convert code comments to HTML using rehype. Remove markdown-to-jsx\n // in @qualcomm-ui/react-mdx library.\n if (propTypes) {\n acc[entry.name] = propTypes\n }\n return acc\n }, {})\n }\n\n private assembleProp(prop: QuiPropDeclaration, id: string): IndexedSection {\n const name = prop.name\n\n const heading: PageHeading = {\n headingLevel: 4,\n id,\n tagName: \"a\",\n textContent: name,\n }\n\n const comment = prop.comment\n if (!comment) {\n return {content: [], heading}\n }\n\n const content = {\n tagName: \"p\",\n text: [\n comment.summary\n .map((entry) => entry.text.replaceAll(\"\\n\", \" \"))\n .join(\"\"),\n ],\n }\n return {content: [content], heading}\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport rehypeShiki, {type RehypeShikiOptions} from \"@shikijs/rehype\"\nimport {\n transformerNotationDiff,\n transformerNotationErrorLevel,\n transformerNotationFocus,\n transformerNotationHighlight,\n transformerNotationWordHighlight,\n transformerRemoveNotationEscape,\n transformerRenderIndentGuides,\n} from \"@shikijs/transformers\"\nimport {merge} from \"lodash-es\"\nimport type {ShikiTransformer} from \"shiki\"\nimport type {PluggableList} from \"unified\"\n\nimport {quiCustomDarkTheme} from \"@qualcomm-ui/mdx-common\"\n\nimport {\n rehypeMdxCodeProps,\n remarkFrontmatter,\n remarkGfm,\n remarkMdxFrontmatter,\n} from \"../exports\"\n\nimport {ConfigLoader, type ConfigLoaderOptions} from \"./config\"\nimport {rehypeSectionize, rehypeSlug, type RehypeSlugOptions} from \"./rehype\"\nimport {\n remarkAlerts,\n remarkCodeTabs,\n remarkFrontmatterDescription,\n remarkFrontmatterTitle,\n remarkSpoilers,\n remarkSteps,\n} from \"./remark\"\nimport {remarkExtractMeta} from \"./remark/remark-extract-meta\"\nimport {transformerCodeAttribute, transformerNotationHidden} from \"./shiki\"\n\nexport interface QuiRehypePluginOptions extends ConfigLoaderOptions {\n rehypeShikiOptions?: Partial<RehypeShikiOptions>\n}\n\nexport function getShikiTransformers(): ShikiTransformer[] {\n return [\n transformerNotationDiff(),\n transformerNotationFocus(),\n transformerNotationHighlight(),\n transformerNotationWordHighlight(),\n transformerNotationErrorLevel(),\n transformerNotationHidden(),\n transformerRenderIndentGuides(),\n transformerRemoveNotationEscape(),\n ]\n}\n\n/**\n * Used to retrieve all the rehype plugins required for QUI Docs MDX.\n * These should be passed to the `mdx` vite plugin from\n */\nexport function getRehypePlugins(\n options: QuiRehypePluginOptions = {},\n): PluggableList {\n const config = new ConfigLoader(options).loadConfig()\n return [\n [rehypeMdxCodeProps, {enforce: \"pre\"}],\n [\n rehypeSlug,\n {allowedHeadings: config.headings} satisfies RehypeSlugOptions,\n ],\n rehypeSectionize,\n [\n rehypeShiki,\n merge(\n {\n defaultColor: \"light-dark()\",\n fallbackLanguage: \"text\",\n themes: {\n dark: quiCustomDarkTheme,\n light: \"github-light-high-contrast\",\n },\n transformers: [...getShikiTransformers(), transformerCodeAttribute()],\n } satisfies RehypeShikiOptions,\n options.rehypeShikiOptions,\n ),\n ],\n ]\n}\n\n/**\n * @returns every remark plugin needed for QUI Docs MDX.\n *\n * @example\n * ```ts\n * // in your vite config\n * plugins: [\n * mdx({\n * providerImportSource: \"@mdx-js/react\",\n * rehypePlugins: [...getRehypePlugins()],\n * remarkPlugins: [...getRemarkPlugins()],\n * }),\n * quiDocsPlugin(),\n * // ... the rest of your plugins\n * ]\n * ```\n */\nexport function getRemarkPlugins(): PluggableList {\n return [\n remarkFrontmatter,\n remarkMdxFrontmatter,\n remarkGfm,\n remarkAlerts,\n remarkCodeTabs,\n remarkFrontmatterTitle,\n remarkFrontmatterDescription,\n remarkSpoilers,\n remarkSteps,\n remarkExtractMeta,\n ]\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport rehypeMdxCodeProps from \"rehype-mdx-code-props\"\nimport remarkFrontmatter from \"remark-frontmatter\"\nimport remarkGfm from \"remark-gfm\"\nimport remarkMdxFrontmatter from \"remark-mdx-frontmatter\"\n\nimport {rehypeSlug} from \"./docs-plugin/rehype/rehype-slug\"\n\n// Re-export these peerDependencies for more convenient imports.\n// Some of these are not included in the bundled JS, so the user must install them\n// separately.\nexport {\n remarkFrontmatter,\n remarkGfm,\n remarkMdxFrontmatter,\n rehypeMdxCodeProps,\n rehypeSlug,\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Root} from \"hast\"\nimport {headingRank} from \"hast-util-heading-rank\"\nimport {toString} from \"hast-util-to-string\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nimport {SlugGenerator} from \"../markdown/create-slug\"\n\nexport interface RehypeSlugOptions {\n /**\n * @default ['h2', 'h3', 'h4']\n */\n allowedHeadings?: string[]\n prefix?: string\n}\n\nconst emptyOptions: RehypeSlugOptions = {}\n\n/**\n * Converts heading text to URL-friendly slugs. Converts multi-word and PascalCase\n * text to kebab-case. Lowercases single sentence-case words. Appends counter for\n * duplicate slugs.\n */\nexport const rehypeSlug: Plugin<[RehypeSlugOptions?], Root> = (\n options: RehypeSlugOptions | null | undefined,\n) => {\n const settings = options || emptyOptions\n const prefix = settings.prefix || \"\"\n const allowedHeadings = new Set<string>(\n settings.allowedHeadings || [\"h2\", \"h3\", \"h4\"],\n )\n const slugGenerator = new SlugGenerator()\n\n return (tree) => {\n slugGenerator.reset()\n visit(tree, \"element\", function (node) {\n if (\n headingRank(node) &&\n !node.properties.id &&\n allowedHeadings.has(node.tagName)\n ) {\n node.properties.id = prefix + slugGenerator.createSlug(toString(node))\n }\n })\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Element, Root, RootContent} from \"hast\"\nimport {heading} from \"hast-util-heading\"\nimport {headingRank} from \"hast-util-heading-rank\"\nimport type {Properties} from \"hastscript\"\nimport type {Plugin} from \"unified\"\n\nexport type RehypeSectionizeOptions = {\n enableRootSection?: boolean | undefined\n idPropertyName?: string | undefined\n properties?: Properties | undefined\n rankPropertyName?: string | undefined\n}\n\nconst defaultOptions: Required<RehypeSectionizeOptions> = {\n enableRootSection: false,\n idPropertyName: \"ariaLabelledby\",\n properties: {},\n rankPropertyName: \"dataHeadingRank\",\n}\n\nconst wrappingRank = (\n rootContent: RootContent | undefined,\n rankPropertyName: RehypeSectionizeOptions[\"rankPropertyName\"],\n) => {\n if (\n rootContent == null ||\n rankPropertyName == null ||\n !(\"properties\" in rootContent)\n ) {\n throw new Error(\"rootContent and rankPropertyName must have value\")\n }\n\n const rank = rootContent.properties?.[rankPropertyName]\n if (typeof rank !== \"number\") {\n throw new Error(`rankPropertyName(${rankPropertyName}) must be number`)\n }\n\n return rank\n}\n\nconst createElement = (\n rank: number,\n options: Pick<\n RehypeSectionizeOptions,\n \"properties\" | \"rankPropertyName\" | \"idPropertyName\"\n >,\n children: Element[] = [],\n) => {\n const {idPropertyName, properties, rankPropertyName} = options\n\n if (\n properties != null &&\n rankPropertyName != null &&\n rankPropertyName in properties\n ) {\n throw new Error(\n `rankPropertyName(${rankPropertyName}) dataHeadingRank must exist`,\n )\n }\n\n const id = children.at(0)?.properties?.id\n const element: Element = {\n children,\n properties: {\n className: [\"heading\"],\n ...(rankPropertyName ? {[rankPropertyName]: rank} : {}),\n ...(idPropertyName && typeof id === \"string\"\n ? {[idPropertyName]: id}\n : {}),\n ...(properties ? properties : {}),\n },\n tagName: \"section\",\n type: \"element\",\n }\n\n return element\n}\n\nexport const rehypeSectionize: Plugin<[RehypeSectionizeOptions?], Root> = (\n options = defaultOptions,\n) => {\n const {enableRootSection, ...rest} = {\n enableRootSection:\n options.enableRootSection ?? defaultOptions.enableRootSection,\n idPropertyName: options.idPropertyName ?? defaultOptions.idPropertyName,\n properties: options.properties ?? defaultOptions.properties,\n rankPropertyName:\n options.rankPropertyName ?? defaultOptions.rankPropertyName,\n }\n\n return (root) => {\n const rootWrapper = createElement(0, rest)\n\n const wrapperStack: RootContent[] = []\n wrapperStack.push(rootWrapper)\n\n const lastStackItem = () => {\n const last = wrapperStack.at(-1)\n if (last == null || last.type !== \"element\") {\n throw new Error(\"lastStackItem must be Element\")\n }\n return wrapperStack.at(-1) as Element\n }\n\n for (const rootContent of root.children) {\n if (heading(rootContent)) {\n const rank = headingRank(rootContent)\n if (rank == null) {\n throw new Error(\"heading or headingRank is not working\")\n }\n\n if (rank > wrappingRank(lastStackItem(), rest.rankPropertyName)) {\n const childWrapper = createElement(rank, rest, [rootContent])\n lastStackItem().children.push(childWrapper)\n wrapperStack.push(childWrapper)\n } else if (\n rank <= wrappingRank(lastStackItem(), rest.rankPropertyName)\n ) {\n while (rank <= wrappingRank(lastStackItem(), rest.rankPropertyName)) {\n wrapperStack.pop()\n }\n const siblingWrapper = createElement(rank, rest, [rootContent])\n\n lastStackItem().children.push(siblingWrapper)\n wrapperStack.push(siblingWrapper)\n }\n } else {\n if (rootContent.type === \"doctype\") {\n throw new Error(\"must be used in a fragment\")\n }\n lastStackItem().children.push(rootContent as any)\n }\n }\n\n return {\n ...root,\n children: enableRootSection ? [rootWrapper] : rootWrapper.children,\n }\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nexport function removeCodeAnnotations(code: string): string {\n const hideAnnotationRegex = /\\/\\/\\s*\\[!code\\s+hide(?::\\d+)?\\]/\n const lineAnnotationRegex = /\\/\\/\\s*\\[!code\\s*(?:\\S.*)?\\]/\n const jsxBlockAnnotationRegex = /\\{\\s*\\/\\*\\s*\\[!code(?:\\s+\\S+)?\\]\\s*\\*\\/\\s*\\}/\n const htmlAnnotationRegex = /<!--\\s*\\[!code(?:\\s+\\S+)?\\]\\s*-->/\n const blockAnnotationRegex = /\\/\\*\\s*\\[!code(?:\\s+\\S+)?\\]\\s*\\*\\/\\s*/\n const inlineIncrementRegex = /(?:\\/\\/\\s*)?\\[!code \\+\\+\\]/\n\n function stripAnnotations(line: string): {\n hasHideAnnotation: boolean\n processed: string\n touched: boolean\n } {\n let processed = line\n let touched = false\n const hasHideAnnotation = hideAnnotationRegex.test(line)\n\n const patterns = [\n inlineIncrementRegex,\n jsxBlockAnnotationRegex,\n htmlAnnotationRegex,\n blockAnnotationRegex,\n lineAnnotationRegex,\n ]\n\n for (const pattern of patterns) {\n const next = processed.replace(pattern, \"\")\n if (next !== processed) {\n touched = true\n processed = next\n }\n }\n\n return {hasHideAnnotation, processed, touched}\n }\n\n return code\n .split(\"\\n\")\n .map(stripAnnotations)\n .filter(({hasHideAnnotation, processed, touched}) => {\n if (hasHideAnnotation) {\n return false\n }\n\n const processedIsBlank = !processed.trim()\n if (touched && processedIsBlank) {\n return false\n }\n\n return true\n })\n .map(({processed}) => processed)\n .join(\"\\n\")\n}\n\nexport function extractPreviewFromHighlightedHtml(\n highlightedHtml: string,\n): string | null {\n const preMatch = highlightedHtml.match(/<pre((?:\\s+[\\w-]+=\"[^\"]*\")*)>/)\n const codeMatch = highlightedHtml.match(/<code([^>]*)>(.*?)<\\/code>/s)\n\n if (!preMatch || !codeMatch) {\n return null\n }\n const codeContent = codeMatch[2]\n const parts = codeContent.split(/<span class=\"line/)\n const previewLineParts = parts\n .slice(1)\n .filter((part) => part.includes('data-preview-line=\"true\"'))\n\n // strip indentation\n const indents = previewLineParts.map((part) => {\n const indentMatches =\n part.match(/<span class=\"indent\">(.+?)<\\/span>/g) || []\n let total = 0\n for (const match of indentMatches) {\n const content = match.match(/<span class=\"indent\">(.+?)<\\/span>/)\n if (content) {\n total += content[1].length\n } else {\n break\n }\n }\n return total\n })\n\n const minIndent = Math.min(...indents.filter((n) => n > 0))\n const previewLines = previewLineParts.map((part) => {\n let processed = `<span class=\"line${part}`\n let remaining = minIndent\n while (remaining > 0 && processed.includes('<span class=\"indent\">')) {\n const before = processed\n processed = processed.replace(\n /<span class=\"indent\">(.+?)<\\/span>/,\n (match, spaces) => {\n if (spaces.length <= remaining) {\n remaining -= spaces.length\n return \"\"\n } else {\n const kept = spaces.substring(remaining)\n remaining = 0\n return `<span class=\"indent\">${kept}</span>`\n }\n },\n )\n if (before === processed) {\n break\n }\n }\n return processed\n })\n return `<pre${preMatch[1]}><code${codeMatch[1]}>${previewLines.join(\"\")}</code></pre>`\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {ShikiTransformer} from \"shiki\"\n\nimport {removeCodeAnnotations} from \"./utils\"\n\nexport interface TransformerCodeAttributeOptions {\n /**\n * The name of the attribute to add to the pre element. Supply as `null` to\n * disable.\n *\n * @default 'data-code'\n */\n attributeName?: string | null\n\n /**\n * Custom formatter for the source code.\n */\n formatter?: (code: string) => string\n\n /**\n * Callback fired when file processing is complete.\n */\n onComplete?: (codeWithoutSnippets: string) => void\n}\n\n/**\n * Adds a `data-code` attribute to the `<pre>` element with the code contents,\n * removing any code annotations and unused lines from transformers like\n * `transformerNotationDiff`.\n */\nexport function transformerCodeAttribute(\n opts: TransformerCodeAttributeOptions = {attributeName: \"data-code\"},\n): ShikiTransformer {\n return {\n enforce: \"post\",\n name: \"shiki-transformer-code-attribute\",\n pre(node) {\n const strippedSource = removeCodeAnnotations(this.source)\n const formattedSource = opts.formatter?.(strippedSource) ?? strippedSource\n if (opts.attributeName !== null) {\n node.properties[opts.attributeName ?? \"data-code\"] = formattedSource\n }\n opts.onComplete?.(formattedSource)\n },\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {ShikiTransformer} from \"shiki\"\n\n/**\n * Use `[!code hide]` notation in code to mark lines as hidden.\n */\nexport function transformerNotationHidden(): ShikiTransformer {\n return {\n name: \"shiki-transformer-notation-hidden\",\n preprocess(code) {\n const lines = code.split(\"\\n\")\n const resultLines: string[] = []\n let hideNextCount = 0\n\n for (const rawLine of lines) {\n const line = rawLine\n const match = line.match(/\\[!code\\s+hide(?::(\\d+))?\\]/)\n\n if (match) {\n const before = line.slice(0, match.index ?? 0)\n const after = line.slice((match.index ?? 0) + match[0].length)\n\n const count = match[1] ? Number(match[1]) : 1\n const validCount = Number.isFinite(count) && count > 0 ? count : 0\n\n const beforeIsOnlyCommentOrWhitespace =\n before.trim() === \"\" || /^[\\s/]*$/.test(before)\n const afterIsEmpty = after.trim() === \"\"\n\n const markerIsStandalone =\n beforeIsOnlyCommentOrWhitespace && afterIsEmpty\n\n if (markerIsStandalone) {\n hideNextCount += validCount\n continue\n }\n\n // inline marker \u2192 hide this line only\n continue\n }\n\n if (hideNextCount > 0) {\n hideNextCount -= 1\n continue\n }\n\n resultLines.push(line)\n }\n\n return resultLines.join(\"\\n\").trim()\n },\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {ShikiTransformer} from \"shiki\"\n\nimport {dedent} from \"@qualcomm-ui/utils/dedent\"\n\nimport {removeCodeAnnotations} from \"./utils\"\n\nexport type PreviewDisplayMode = \"only-preview\" | \"full-code\"\n\nexport interface PreviewBlockTransformerOptions {\n /**\n * The name of the attribute to add to the pre element. Supply as `null` to\n * disable.\n *\n * @default 'data-preview'\n */\n attributeName?: string | null\n\n /**\n * @option 'full-code': keep the full code (with preview markers removed) as the rendered snippet.\n * @option 'preview-only': render only the extracted preview block as the snippet\n *\n * In all cases the preview block is extracted and attached to `data-preview`.\n *\n * @default 'full-code'\n */\n displayMode?: PreviewDisplayMode\n\n /**\n * Callback fired when file processing is complete.\n */\n onComplete?: (extractedPreview: string | null) => void\n}\n\nexport function isPreviewLine(trimmedLine: string): boolean {\n return (\n trimmedLine === \"// preview\" ||\n /^\\{\\s*\\/\\*\\s*preview\\s*\\*\\/\\s*\\}$/.test(trimmedLine) ||\n /^<!--\\s*preview\\s*-->$/.test(trimmedLine)\n )\n}\n\nexport function transformerPreviewBlock(\n options: PreviewBlockTransformerOptions = {\n displayMode: \"full-code\",\n },\n): ShikiTransformer {\n let previewContent: string | null = null\n let previewStartLine = -1\n let previewEndLine = -1\n let currentLine = 0\n\n return {\n enforce: \"post\",\n line(node) {\n if (currentLine >= previewStartLine && currentLine <= previewEndLine) {\n node.properties[\"data-preview-line\"] = \"true\"\n }\n currentLine++\n },\n name: \"transformer-preview-block\",\n pre(node) {\n const content = previewContent\n ? removeCodeAnnotations(previewContent)\n : null\n if (content && options.attributeName != null) {\n node.properties[options.attributeName] = content\n }\n options.onComplete?.(content || null)\n },\n preprocess(code) {\n previewContent = null\n currentLine = 0\n previewStartLine = -1\n previewEndLine = -1\n\n const lines = code.split(\"\\n\")\n const resultLines: string[] = []\n const previewLines: string[] = []\n let inPreview = false\n let foundPreview = false\n let outputLineIndex = 0\n\n for (const line of lines) {\n const trimmed = line.trim()\n if (isPreviewLine(trimmed)) {\n if (!inPreview) {\n inPreview = true\n foundPreview = true\n previewStartLine = outputLineIndex\n } else {\n inPreview = false\n previewEndLine = outputLineIndex - 1\n }\n continue\n }\n resultLines.push(line)\n if (inPreview) {\n previewLines.push(line)\n }\n outputLineIndex++\n }\n\n if (foundPreview) {\n previewContent = dedent(previewLines.join(\"\\n\").trim())\n if (options.displayMode === \"only-preview\") {\n return previewContent\n }\n }\n return resultLines.join(\"\\n\").trim()\n },\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Element, Root, Text} from \"hast\"\nimport {fromHtml} from \"hast-util-from-html\"\nimport {toHtml} from \"hast-util-to-html\"\nimport {readFile} from \"node:fs/promises\"\nimport postcss, {type Rule} from \"postcss\"\nimport selectorParser from \"postcss-selector-parser\"\nimport type {ShikiTransformer} from \"shiki\"\nimport {compile} from \"tailwindcss\"\nimport {visit} from \"unist-util-visit\"\n\nimport {camelCase} from \"@qualcomm-ui/utils/change-case\"\n\ndeclare const createRequire: NodeRequire\n\nasync function loadStylesheetContent(id: string): Promise<string> {\n const resolveId = id === \"tailwindcss\" ? \"tailwindcss/index.css\" : id\n\n let resolvedPath: string\n if (typeof createRequire !== \"undefined\") {\n resolvedPath = createRequire(import.meta.url).resolve(resolveId)\n } else {\n const createRequire = await import(\"node:module\").then(\n (module) => module.createRequire,\n )\n resolvedPath = createRequire(import.meta.url).resolve(resolveId)\n }\n return readFile(resolvedPath, \"utf-8\")\n}\n\nfunction getClassValue(node: Element): string | null {\n const val = node.properties?.className ?? node.properties?.class\n if (!val) {\n return null\n }\n return Array.isArray(val) ? val.join(\" \") : String(val)\n}\n\n/**\n * Extract class names from the text content of a HAST tree.\n * Looks for string literals that could be Tailwind class names.\n */\nexport function extractClassesFromHast(tree: Root): string[] {\n const classes = new Set<string>()\n const stringLiteralPattern = /[\"'`]([^\"'`]+)[\"'`]/g\n\n visit(tree, \"text\", (node: Text) => {\n const text = node.value\n let match\n while ((match = stringLiteralPattern.exec(text)) !== null) {\n const content = match[1]\n const tokens = content.split(/\\s+/).filter(Boolean)\n for (const token of tokens) {\n classes.add(token)\n }\n }\n })\n\n return [...classes]\n}\n\nexport function extractClasses(source: string): string[] {\n const tree = fromHtml(source, {fragment: true})\n const classes = new Set<string>()\n\n visit(tree, \"element\", (node: Element) => {\n const value = getClassValue(node)\n if (value) {\n classes.add(value)\n }\n })\n\n return classes\n .values()\n .toArray()\n .map((value) => value.split(\" \"))\n .flat()\n}\n\n/**\n * Create a fresh Tailwind compiler for each transformation.\n * Note: Tailwind v4's compiler.build() is incremental and accumulates\n * all candidates across calls. We must create a fresh compiler each time\n * to avoid CSS from one demo leaking into another.\n */\nasync function createCompiler(styles: string) {\n return compile(styles, {\n loadStylesheet: async (id: string, base: string) => {\n const content = await loadStylesheetContent(id)\n return {\n base,\n content,\n path: `virtual:${id}`,\n }\n },\n })\n}\n\n/**\n * Extract CSS custom property definitions from compiled CSS.\n * Looks in :root and :host selectors within @layer theme.\n */\nfunction extractCssVariables(css: string): Map<string, string> {\n const variables = new Map<string, string>()\n const root = postcss.parse(css)\n\n root.walkAtRules(\"layer\", (atRule) => {\n if (atRule.params !== \"theme\") {\n return\n }\n\n atRule.walkRules(\":root, :host\", (rule) => {\n rule.walkDecls((decl) => {\n if (decl.prop.startsWith(\"--\")) {\n variables.set(decl.prop, decl.value)\n }\n })\n })\n })\n\n return variables\n}\n\n/**\n * Evaluate a calc() expression with resolved numeric values.\n * Handles expressions like \"0.25rem * 4\" -> \"1rem\" or \"1.25 / 0.875\" -> \"1.4286\"\n */\nfunction evaluateCalc(expression: string): string | null {\n const expr = expression.trim()\n\n // Pattern 1: number+unit operator number (e.g., \"0.25rem * 4\")\n const withUnitFirst = expr.match(\n /^([\\d.]+)(rem|px|em|%|vh|vw)\\s*([*/+-])\\s*([\\d.]+)$/,\n )\n if (withUnitFirst) {\n const [, num1, unit, op, num2] = withUnitFirst\n const result = evaluateOperation(parseFloat(num1), op, parseFloat(num2))\n if (!Number.isFinite(result)) {\n return null\n }\n return formatNumber(result) + unit\n }\n\n // Pattern 2: number operator number+unit (e.g., \"4 * 0.25rem\")\n const withUnitSecond = expr.match(\n /^([\\d.]+)\\s*([*/+-])\\s*([\\d.]+)(rem|px|em|%|vh|vw)$/,\n )\n if (withUnitSecond) {\n const [, num1, op, num2, unit] = withUnitSecond\n const result = evaluateOperation(parseFloat(num1), op, parseFloat(num2))\n if (!Number.isFinite(result)) {\n return null\n }\n return formatNumber(result) + unit\n }\n\n // Pattern 3: unitless (e.g., \"1.25 / 0.875\")\n const unitless = expr.match(/^([\\d.]+)\\s*([*/+-])\\s*([\\d.]+)$/)\n if (unitless) {\n const [, num1, op, num2] = unitless\n const result = evaluateOperation(parseFloat(num1), op, parseFloat(num2))\n if (!Number.isFinite(result)) {\n return null\n }\n return formatNumber(result)\n }\n\n return null\n}\n\nfunction evaluateOperation(a: number, op: string, b: number): number {\n switch (op) {\n case \"*\":\n return a * b\n case \"/\":\n return a / b\n case \"+\":\n return a + b\n case \"-\":\n return a - b\n default:\n return NaN\n }\n}\n\nfunction formatNumber(num: number): string {\n // Avoid floating point artifacts like 0.30000000000000004\n const rounded = Math.round(num * 10000) / 10000\n return String(rounded)\n}\n\n/**\n * Convert rem values to pixels (assuming 1rem = 16px).\n */\nfunction remToPx(value: string): string {\n return value.replace(/([\\d.]+)rem/g, (_, num) => {\n const px = parseFloat(num) * 16\n return `${formatNumber(px)}px`\n })\n}\n\n/**\n * Find the matching closing parenthesis for a var() call.\n * Handles nested parentheses in fallback values.\n */\nfunction findVarEnd(str: string, start: number): number {\n let depth = 0\n for (let i = start; i < str.length; i++) {\n if (str[i] === \"(\") {\n depth++\n } else if (str[i] === \")\") {\n depth--\n if (depth === 0) {\n return i\n }\n }\n }\n return -1\n}\n\n/**\n * Parse a var() expression and return its parts.\n */\nfunction parseVar(\n str: string,\n startIndex: number,\n): {end: number; fallback: string | null; varName: string} | null {\n // Find \"var(\" starting position\n const varStart = str.indexOf(\"var(\", startIndex)\n if (varStart === -1) {\n return null\n }\n\n const contentStart = varStart + 4 // After \"var(\"\n const end = findVarEnd(str, varStart)\n if (end === -1) {\n return null\n }\n\n const content = str.slice(contentStart, end)\n\n // Find comma separating variable name from fallback\n let commaIndex = -1\n let depth = 0\n for (let i = 0; i < content.length; i++) {\n if (content[i] === \"(\") {\n depth++\n } else if (content[i] === \")\") {\n depth--\n } else if (content[i] === \",\" && depth === 0) {\n commaIndex = i\n break\n }\n }\n\n if (commaIndex === -1) {\n return {\n end,\n fallback: null,\n varName: content.trim(),\n }\n }\n\n return {\n end,\n fallback: content.slice(commaIndex + 1).trim(),\n varName: content.slice(0, commaIndex).trim(),\n }\n}\n\n/**\n * Resolve CSS var() references and evaluate calc() expressions.\n * Recursively resolves nested var() calls.\n */\nfunction resolveCssValue(\n value: string,\n variables: Map<string, string>,\n depth = 0,\n): string {\n if (depth > 10) {\n return value // Prevent infinite recursion\n }\n\n let resolved = value\n let searchStart = 0\n\n // Process var() calls iteratively to handle nested var() in fallbacks\n while (true) {\n const parsed = parseVar(resolved, searchStart)\n if (!parsed) {\n break\n }\n\n const {end, fallback, varName} = parsed\n const varStart = resolved.indexOf(\"var(\", searchStart)\n\n let replacement: string\n const varValue = variables.get(varName)\n if (varValue !== undefined) {\n replacement = resolveCssValue(varValue, variables, depth + 1)\n } else if (fallback) {\n replacement = resolveCssValue(fallback, variables, depth + 1)\n } else {\n // Keep original if unresolved, move past it\n searchStart = end + 1\n continue\n }\n\n resolved =\n resolved.slice(0, varStart) + replacement + resolved.slice(end + 1)\n }\n\n // Evaluate calc() expressions after var() resolution\n resolved = resolved.replace(\n /calc\\(([^)]+)\\)/g,\n (match, expression: string) => {\n const evaluated = evaluateCalc(expression)\n return evaluated ?? match\n },\n )\n\n // Convert rem to px (1rem = 16px)\n resolved = remToPx(resolved)\n\n return resolved\n}\n\ninterface SelectorAnalysis {\n /** The class name if it's a simple class selector */\n className: string | null\n /** Whether this selector can be inlined (single class, no pseudo/combinators) */\n inlineable: boolean\n}\n\n/**\n * Analyze a CSS selector using postcss-selector-parser AST.\n * Returns whether it can be inlined and extracts the class name.\n */\nfunction analyzeSelector(selector: string): SelectorAnalysis {\n let inlineable = true\n let className: string | null = null\n\n const processor = selectorParser((selectors) => {\n if (selectors.nodes.length !== 1) {\n inlineable = false\n return\n }\n\n const selectorNode = selectors.nodes[0]\n if (selectorNode.nodes.length !== 1) {\n inlineable = false\n return\n }\n\n const node = selectorNode.nodes[0]\n if (node.type !== \"class\") {\n inlineable = false\n return\n }\n\n className = node.value\n\n selectorNode.walk((n) => {\n if (\n n.type === \"pseudo\" ||\n n.type === \"combinator\" ||\n n.type === \"nesting\" ||\n n.type === \"attribute\"\n ) {\n inlineable = false\n }\n })\n })\n\n processor.processSync(selector)\n\n return {className, inlineable}\n}\n\ninterface ParsedRule {\n className: string\n declarations: string\n inlineable: boolean\n originalRule: string\n}\n\n/**\n * Parse compiled CSS and extract rules with their inlineability status.\n * CSS variables are resolved and calc() expressions are evaluated.\n */\nfunction parseCompiledCss(css: string): ParsedRule[] {\n const rules: ParsedRule[] = []\n const root = postcss.parse(css)\n const variables = extractCssVariables(css)\n\n function processRule(rule: Rule, insideAtRule: boolean) {\n const {className, inlineable} = analyzeSelector(rule.selector)\n\n if (!className) {\n return\n }\n\n let hasNestedAtRule = false\n rule.walkAtRules(() => {\n hasNestedAtRule = true\n })\n\n const declarations: string[] = []\n rule.each((node) => {\n if (node.type === \"decl\") {\n const resolvedValue = resolveCssValue(node.value, variables)\n declarations.push(`${node.prop}: ${resolvedValue}`)\n }\n })\n\n if (declarations.length === 0 && !hasNestedAtRule) {\n return\n }\n\n rules.push({\n className,\n declarations: declarations.join(\"; \"),\n inlineable: inlineable && !insideAtRule && !hasNestedAtRule,\n originalRule: rule.toString(),\n })\n }\n\n root.walkAtRules(\"layer\", (atRule) => {\n atRule.walkRules((rule) => {\n const parent = rule.parent\n const insideNestedAtRule =\n parent?.type === \"atrule\" && (parent as postcss.AtRule).name !== \"layer\"\n processRule(rule, insideNestedAtRule)\n })\n\n atRule.walkAtRules((nested) => {\n if (nested.name !== \"layer\") {\n nested.walkRules((rule) => {\n processRule(rule, true)\n })\n }\n })\n })\n\n root.walkRules((rule) => {\n if (rule.parent?.type === \"root\") {\n processRule(rule, false)\n }\n })\n\n return rules\n}\n\n/**\n * Build residual CSS from non-inlineable rules, stripping @layer wrappers.\n */\nfunction buildResidualCss(css: string, inlineableClasses: Set<string>): string {\n const root = postcss.parse(css)\n const residualRules: string[] = []\n\n function shouldKeepRule(rule: Rule): boolean {\n const {className} = analyzeSelector(rule.selector)\n return className !== null && !inlineableClasses.has(className)\n }\n\n root.walkAtRules(\"layer\", (atRule) => {\n if (atRule.params !== \"utilities\") {\n return\n }\n\n atRule.each((node) => {\n if (node.type === \"rule\") {\n const rule = node\n if (shouldKeepRule(rule)) {\n residualRules.push(rule.toString())\n }\n }\n })\n })\n\n return residualRules.join(\"\\n\\n\")\n}\n\nexport interface TransformResult {\n /** CSS for non-inlineable rules without @layer wrappers */\n css: string\n /** HTML with inline styles applied */\n html: string\n}\n\n/**\n * Transform HTML by inlining Tailwind styles where possible.\n * Non-inlineable styles (pseudo-classes, media queries, etc.) are returned as CSS.\n */\nexport async function transformWithInlineStyles(\n html: string,\n styles: string,\n): Promise<TransformResult> {\n const compiler = await createCompiler(styles)\n const allClasses = extractClasses(html)\n const compiledCss = compiler.build(allClasses)\n const parsedRules = parseCompiledCss(compiledCss)\n\n const inlineableStyles = new Map<string, string>()\n const inlineableClasses = new Set<string>()\n\n for (const rule of parsedRules) {\n if (rule.inlineable) {\n inlineableStyles.set(rule.className, rule.declarations)\n inlineableClasses.add(rule.className)\n }\n }\n\n const residualCss = buildResidualCss(compiledCss, inlineableClasses)\n const tree = fromHtml(html, {fragment: true})\n\n visit(tree, \"element\", (node: Element) => {\n const classValue = getClassValue(node)\n if (!classValue) {\n return\n }\n\n const classes = classValue.split(/\\s+/)\n const inlineStyles: string[] = []\n const remainingClasses: string[] = []\n\n for (const cls of classes) {\n const style = inlineableStyles.get(cls)\n if (style) {\n inlineStyles.push(style)\n } else {\n remainingClasses.push(cls)\n }\n }\n\n if (inlineStyles.length > 0) {\n const existingStyle = node.properties?.style as string | undefined\n const newStyle = inlineStyles.join(\"; \")\n node.properties = node.properties ?? {}\n node.properties.style = existingStyle\n ? `${existingStyle}; ${newStyle}`\n : newStyle\n }\n\n if (remainingClasses.length > 0) {\n node.properties = node.properties ?? {}\n node.properties.className = remainingClasses\n } else if (node.properties) {\n delete node.properties.className\n delete node.properties.class\n }\n })\n\n return {\n css: residualCss,\n html: toHtml(tree),\n }\n}\n\nexport interface ShikiTailwindTransformerOptions {\n /**\n * Callback invoked after transformation indicating whether any className/class\n * attributes were detected in the code. Useful for conditionally applying\n * the transformation or showing/hiding UI elements.\n */\n onClassesDetected?: (detected: boolean) => void\n /**\n * Callback invoked with CSS rules for non-inlineable classes (hover:, sm:, etc.).\n * Receives a Map where keys are class names and values are the CSS rule strings.\n * This allows for deduplication when aggregating CSS from multiple files.\n */\n onResidualCss?: (rules: Map<string, string>) => void\n /**\n * Output format for inline styles.\n * - \"html\": `style=\"display: flex\"` (HTML string syntax)\n * - \"jsx\": `style={{ display: 'flex' }}` (JSX object syntax)\n * @default \"html\"\n */\n styleFormat?: \"html\" | \"jsx\"\n /** Tailwind CSS styles to compile against */\n styles: string\n}\n\ninterface CompileClassesResult {\n inlineStyles: string[]\n remainingClasses: string[]\n residualRules: Map<string, string>\n}\n\n/**\n * Compile classes and return inline styles, remaining classes, and residual CSS\n * rules.\n */\nfunction compileClasses(\n classes: string[],\n compiler: {build(candidates: string[]): string},\n): CompileClassesResult {\n const compiledCss = compiler.build(classes)\n const parsedRules = parseCompiledCss(compiledCss)\n\n const inlineableStyles = new Map<string, string>()\n const residualRules = new Map<string, string>()\n\n for (const rule of parsedRules) {\n if (rule.inlineable) {\n inlineableStyles.set(rule.className, rule.declarations)\n } else {\n residualRules.set(rule.className, rule.originalRule)\n }\n }\n\n const inlineStyles: string[] = []\n const remainingClasses: string[] = []\n\n for (const cls of classes) {\n const style = inlineableStyles.get(cls)\n if (style) {\n inlineStyles.push(style)\n } else {\n remainingClasses.push(cls)\n }\n }\n\n return {inlineStyles, remainingClasses, residualRules}\n}\n\n/**\n * Convert CSS declarations to JSX object syntax.\n * `\"display: flex; align-items: center\"` -> `\"{ display: 'flex', alignItems:\n * 'center'}\"`\n */\nfunction cssToJsxObject(cssDeclarations: string[]): string {\n const props = cssDeclarations\n .flatMap((decl) => {\n return decl\n .split(\";\")\n .map((d) => d.trim())\n .filter(Boolean)\n })\n .map((declaration) => {\n const colonIndex = declaration.indexOf(\":\")\n if (colonIndex === -1) {\n return null\n }\n const prop = declaration.slice(0, colonIndex).trim()\n const value = declaration.slice(colonIndex + 1).trim()\n const camelProp = camelCase(prop)\n return `${camelProp}: '${value}'`\n })\n .filter(Boolean)\n\n return `{ ${props.join(\", \")} }`\n}\n\ninterface LineReplacementsResult {\n replacements: Map<string, string>\n residualRules: Map<string, string>\n}\n\n/**\n * Transform className attributes to style attributes in a line's text.\n * Returns replacements and residual CSS rules for non-inlineable classes.\n */\nfunction computeLineReplacements(\n lineText: string,\n compiler: {build(candidates: string[]): string},\n styleFormat: \"html\" | \"jsx\" = \"html\",\n): LineReplacementsResult {\n const replacements = new Map<string, string>()\n const allResidualRules = new Map<string, string>()\n const classAttrPattern = /(className|class)=([\"'`])([^\"'`]*)\\2/g\n let match\n\n while ((match = classAttrPattern.exec(lineText)) !== null) {\n const fullMatch = match[0]\n const attrName = match[1]\n const quote = match[2]\n const classValue = match[3]\n\n const classes = classValue.split(/\\s+/).filter(Boolean)\n if (classes.length === 0) {\n continue\n }\n\n const {inlineStyles, remainingClasses, residualRules} = compileClasses(\n classes,\n compiler,\n )\n\n for (const [className, rule] of residualRules) {\n allResidualRules.set(className, rule)\n }\n\n if (inlineStyles.length === 0) {\n continue\n }\n\n let replacement: string\n if (styleFormat === \"jsx\") {\n const jsxStyleObj = cssToJsxObject(inlineStyles)\n replacement = `style={${jsxStyleObj}}`\n } else {\n replacement = `style=${quote}${inlineStyles.join(\"; \")}${quote}`\n }\n\n if (remainingClasses.length > 0) {\n replacement += ` ${attrName}=${quote}${remainingClasses.join(\" \")}${quote}`\n }\n\n replacements.set(fullMatch, replacement)\n }\n\n return {replacements, residualRules: allResidualRules}\n}\n\ninterface TransformSourceResult {\n /** Whether any className/class attributes were detected in the code */\n classesDetected: boolean\n /** CSS rules for non-inlineable classes */\n residualRules: Map<string, string>\n /** Transformed source code */\n source: string\n}\n\n/**\n * Transform className/class attributes to inline styles in source code.\n * This runs BEFORE Shiki tokenization to preserve proper syntax highlighting.\n */\nfunction transformSourceCode(\n source: string,\n compiler: {build(candidates: string[]): string},\n styleFormat: \"html\" | \"jsx\" = \"html\",\n): TransformSourceResult {\n const allResidualRules = new Map<string, string>()\n let classesDetected = false\n\n const {replacements, residualRules} = computeLineReplacements(\n source,\n compiler,\n styleFormat,\n )\n\n if (replacements.size > 0 || residualRules.size > 0) {\n classesDetected = true\n }\n\n for (const [cls, rule] of residualRules) {\n allResidualRules.set(cls, rule)\n }\n\n // Apply all replacements to the source\n let transformed = source\n for (const [original, replacement] of replacements) {\n transformed = transformed.replaceAll(original, replacement)\n }\n\n return {\n classesDetected,\n residualRules: allResidualRules,\n source: transformed,\n }\n}\n\n/**\n * Create a Shiki transformer that inlines Tailwind styles.\n * Uses preprocess to transform source code BEFORE tokenization,\n * ensuring proper syntax highlighting of the transformed output.\n * Must be called with `await` before using the transformer.\n */\nexport async function createShikiTailwindTransformer(\n options: ShikiTailwindTransformerOptions,\n): Promise<ShikiTransformer> {\n const {\n onClassesDetected,\n onResidualCss,\n styleFormat = \"html\",\n styles,\n } = options\n const compiler = await createCompiler(styles)\n\n return {\n name: \"shiki-transformer-tailwind-to-inline\",\n preprocess(code) {\n const {classesDetected, residualRules, source} = transformSourceCode(\n code,\n compiler,\n styleFormat,\n )\n\n onClassesDetected?.(classesDetected)\n\n if (onResidualCss && residualRules.size > 0) {\n onResidualCss(residualRules)\n }\n\n return source\n },\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nexport const VIRTUAL_MODULE_IDS = {\n AUTO: \"\\0virtual:qui-demo-scope/auto\",\n CONFIG: \"\\0virtual:qui-demo-scope/config\",\n PAGE_PREFIX: \"\\0virtual:qui-demo-scope/page:\",\n} as const\n\nexport const LOG_PREFIX = \"@qualcomm-ui/mdx-vite/react-demo-plugin:\"\n\nexport const REACT_IMPORTS: string[] = [\n \"useState\",\n \"useEffect\",\n \"useMemo\",\n \"useCallback\",\n \"useRef\",\n \"useContext\",\n \"createContext\",\n \"forwardRef\",\n \"memo\",\n \"lazy\",\n \"Suspense\",\n \"Fragment\",\n] as const\n\nexport const NODE_BUILTINS: string[] = [\n \"fs\",\n \"path\",\n \"url\",\n \"util\",\n \"os\",\n \"crypto\",\n \"events\",\n \"stream\",\n \"buffer\",\n] as const\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport chalk from \"chalk\"\nimport {existsSync, readFileSync} from \"node:fs\"\nimport {readFile} from \"node:fs/promises\"\nimport {dirname, join, relative, resolve, sep} from \"node:path\"\nimport * as ts from \"typescript\"\n\nimport {pascalCase} from \"@qualcomm-ui/utils/change-case\"\n\nimport {LOG_PREFIX, NODE_BUILTINS} from \"./demo-plugin-constants\"\n\ninterface PathAlias {\n pattern: RegExp\n replacement: string\n}\n\nexport interface ImportSpecifier {\n source: string\n specifiers: Array<{\n imported: string\n local: string\n }>\n type: \"thirdParty\"\n}\n\nexport interface RelativeImport {\n resolvedPath: string\n source: string\n specifiers: Array<{\n imported: string\n local: string\n }>\n type: \"relative\"\n}\n\n/**\n * Demo names are created using the PascalCase format of the file name without the\n * extension.\n */\nexport function createDemoName(filePath: string): string {\n const separatorChar = filePath.includes(\"/\") ? \"/\" : \"\\\\\"\n const fileName = filePath.substring(\n filePath.lastIndexOf(separatorChar),\n filePath.lastIndexOf(\".\"),\n )\n if (!fileName) {\n throw new Error(`Failed to create demo name for ${filePath}`)\n }\n return pascalCase(fileName)\n}\n\nexport async function extractFileImports(filePath: string): Promise<{\n relativeImports: RelativeImport[]\n thirdPartyImports: ImportSpecifier[]\n} | null> {\n try {\n const content = await readFile(filePath, \"utf-8\")\n return extractImports(content, filePath)\n } catch (error) {\n console.log(\n `${chalk.magenta.bold(LOG_PREFIX)} ${chalk.yellowBright(\"Failed to parse\")} ${chalk.blueBright.bold(filePath)}:`,\n error,\n )\n return null\n }\n}\n\nfunction extractImports(\n code: string,\n fileName: string,\n): {\n relativeImports: RelativeImport[]\n thirdPartyImports: ImportSpecifier[]\n} {\n const sourceFile = ts.createSourceFile(\n fileName,\n code,\n ts.ScriptTarget.Latest,\n true,\n getScriptKind(fileName),\n )\n const thirdPartyImports: ImportSpecifier[] = []\n const relativeImports: RelativeImport[] = []\n\n function visit(node: ts.Node) {\n if (ts.isImportDeclaration(node)) {\n const importSpec = parseImportDeclaration(node, fileName)\n if (importSpec) {\n if (importSpec.type === \"relative\") {\n relativeImports.push(importSpec)\n } else {\n thirdPartyImports.push(importSpec)\n }\n }\n }\n ts.forEachChild(node, visit)\n }\n\n visit(sourceFile)\n return {relativeImports, thirdPartyImports}\n}\n\nexport function getScriptKind(fileName: string): ts.ScriptKind {\n return fileName.endsWith(\".tsx\") || fileName.endsWith(\".jsx\")\n ? ts.ScriptKind.TSX\n : ts.ScriptKind.TS\n}\n\nfunction parseImportDeclaration(\n node: ts.ImportDeclaration,\n fileName: string,\n): ImportSpecifier | RelativeImport | null {\n const moduleSpecifier = node.moduleSpecifier\n if (!ts.isStringLiteral(moduleSpecifier)) {\n return null\n }\n\n const source = moduleSpecifier.text\n if (node.importClause?.isTypeOnly) {\n return null\n }\n\n const specifiers = extractSpecifiers(node.importClause)\n if (specifiers.length === 0) {\n return null\n }\n\n if (isRelativeImport(source)) {\n const resolvedPath = resolveRelativeImport(source, fileName)\n return {\n resolvedPath,\n source,\n specifiers,\n type: \"relative\",\n }\n }\n\n if (isNodeBuiltin(source)) {\n return null\n }\n\n const pathAliases = loadTsConfigPaths(fileName)\n if (isPathAliasImport(source, pathAliases)) {\n const resolvedPath = resolvePathAlias(source, pathAliases)\n if (resolvedPath) {\n return {\n resolvedPath,\n source,\n specifiers,\n type: \"relative\",\n }\n }\n }\n\n return {\n source,\n specifiers,\n type: \"thirdParty\",\n }\n}\n\nfunction extractSpecifiers(\n importClause: ts.ImportClause | undefined,\n): Array<{imported: string; local: string}> {\n if (!importClause) {\n return []\n }\n\n const specifiers: Array<{imported: string; local: string}> = []\n\n if (importClause.name) {\n specifiers.push({imported: \"default\", local: \"default\"})\n }\n\n if (importClause.namedBindings) {\n if (ts.isNamespaceImport(importClause.namedBindings)) {\n specifiers.push({imported: \"*\", local: \"*\"})\n } else if (ts.isNamedImports(importClause.namedBindings)) {\n importClause.namedBindings.elements.forEach((element) => {\n if (!element.isTypeOnly) {\n const imported = element.propertyName\n ? element.propertyName.text\n : element.name.text\n const local = element.name.text\n specifiers.push({imported, local})\n }\n })\n }\n }\n\n return specifiers\n}\n\nfunction resolveRelativeImport(source: string, fromFile: string): string {\n const fromDir = dirname(fromFile)\n const resolved = resolve(fromDir, source)\n\n const extensions = [\".ts\", \".tsx\", \".js\", \".jsx\"]\n for (const ext of extensions) {\n const withExt = resolved + ext\n if (existsSync(withExt)) {\n return withExt\n }\n }\n\n for (const ext of extensions) {\n const indexFile = join(resolved, `index${ext}`)\n if (existsSync(indexFile)) {\n return indexFile\n }\n }\n\n return resolved\n}\n\nfunction isRelativeImport(source: string): boolean {\n return source.startsWith(\"./\") || source.startsWith(\"../\")\n}\n\nfunction isNodeBuiltin(source: string): boolean {\n return source.startsWith(\"node:\") || NODE_BUILTINS.includes(source)\n}\n\nfunction loadTsConfigPaths(fromFile: string): PathAlias[] {\n let currentDir = dirname(fromFile)\n const pathAliases: PathAlias[] = []\n\n while (currentDir !== dirname(currentDir)) {\n const tsconfigPath = join(currentDir, \"tsconfig.json\")\n if (existsSync(tsconfigPath)) {\n try {\n const configContent = ts.sys.readFile(tsconfigPath)\n if (!configContent) {\n currentDir = dirname(currentDir)\n continue\n }\n\n const parseResult = ts.parseConfigFileTextToJson(\n tsconfigPath,\n configContent,\n )\n if (parseResult.error) {\n currentDir = dirname(currentDir)\n continue\n }\n\n const paths = parseResult.config?.compilerOptions?.paths\n const baseUrl = parseResult.config?.compilerOptions?.baseUrl || \"./\"\n const resolvedBaseUrl = resolve(currentDir, baseUrl)\n\n if (paths) {\n for (const [alias, targets] of Object.entries(paths)) {\n if (Array.isArray(targets) && targets.length > 0) {\n const target = targets[0]\n const pattern = new RegExp(\n `^${alias\n .replace(\"*\", \"(.*)\")\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(\"\\\\(\\\\*\\\\)\", \"(.*)\")}$`,\n )\n const replacement = resolve(\n resolvedBaseUrl,\n target.replace(\"*\", \"$1\"),\n )\n pathAliases.push({pattern, replacement})\n }\n }\n }\n\n const extendsPath = parseResult.config?.extends\n if (extendsPath) {\n const resolvedExtends = resolve(currentDir, extendsPath)\n const extendedAliases = loadTsConfigPathsFromFile(resolvedExtends)\n pathAliases.push(...extendedAliases)\n }\n\n return pathAliases\n } catch (error) {\n currentDir = dirname(currentDir)\n continue\n }\n }\n currentDir = dirname(currentDir)\n }\n\n return pathAliases\n}\n\nfunction loadTsConfigPathsFromFile(tsconfigPath: string): PathAlias[] {\n const pathAliases: PathAlias[] = []\n const configDir = dirname(tsconfigPath)\n\n try {\n const configContent = ts.sys.readFile(tsconfigPath)\n if (!configContent) {\n return pathAliases\n }\n\n const parseResult = ts.parseConfigFileTextToJson(\n tsconfigPath,\n configContent,\n )\n if (parseResult.error) {\n return pathAliases\n }\n\n const paths = parseResult.config?.compilerOptions?.paths\n const baseUrl = parseResult.config?.compilerOptions?.baseUrl || \"./\"\n const resolvedBaseUrl = resolve(configDir, baseUrl)\n\n if (paths) {\n for (const [alias, targets] of Object.entries(paths)) {\n if (Array.isArray(targets) && targets.length > 0) {\n const target = targets[0]\n const pattern = new RegExp(\n `^${alias\n .replace(\"*\", \"(.*)\")\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(\"\\\\(\\\\*\\\\)\", \"(.*)\")}$`,\n )\n const replacement = resolve(\n resolvedBaseUrl,\n target.replace(\"*\", \"$1\"),\n )\n pathAliases.push({pattern, replacement})\n }\n }\n }\n\n const extendsPath = parseResult.config?.extends\n if (extendsPath) {\n let resolvedExtends = resolve(configDir, extendsPath)\n if (!resolvedExtends.endsWith(\".json\")) {\n resolvedExtends += \".json\"\n }\n if (existsSync(resolvedExtends)) {\n const extendedAliases = loadTsConfigPathsFromFile(resolvedExtends)\n pathAliases.push(...extendedAliases)\n }\n }\n } catch (error) {\n return pathAliases\n }\n\n return pathAliases\n}\n\nfunction isPathAliasImport(source: string, pathAliases: PathAlias[]): boolean {\n return pathAliases.some((alias) => alias.pattern.test(source))\n}\n\nfunction resolvePathAlias(\n source: string,\n pathAliases: PathAlias[],\n): string | null {\n for (const alias of pathAliases) {\n if (alias.pattern.test(source)) {\n const resolvedPath = source.replace(alias.pattern, alias.replacement)\n const extensions = [\".ts\", \".tsx\", \".js\", \".jsx\"]\n\n for (const ext of extensions) {\n const withExt = resolvedPath + ext\n if (existsSync(withExt)) {\n return withExt\n }\n }\n\n for (const ext of extensions) {\n const indexFile = join(resolvedPath, `index${ext}`)\n if (existsSync(indexFile)) {\n return indexFile\n }\n }\n\n return resolvedPath\n }\n }\n return null\n}\n\nexport function extractPageId(filePath: string, routesDir: string): string {\n const relativePath = relative(routesDir, filePath)\n const pathParts = relativePath.split(sep)\n if (pathParts.includes(\"demos\")) {\n const demosIndex = pathParts.indexOf(\"demos\")\n return pathParts.slice(0, demosIndex).join(sep)\n }\n return dirname(relativePath)\n}\n\nexport function isCssAsset(filePath: string) {\n return filePath.endsWith(\".css\")\n}\n\nexport function isDemoFile(filePath: string): boolean {\n try {\n return (\n filePath.includes(\"/demos/\") &&\n filePath.endsWith(\".tsx\") &&\n !readFileSync(filePath).includes(\"export default\")\n )\n } catch (error) {\n return false\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport chalk from \"chalk\"\nimport {glob} from \"glob\"\nimport {readFile} from \"node:fs/promises\"\nimport {basename, resolve} from \"node:path\"\nimport {createHighlighter, type Highlighter, type ShikiTransformer} from \"shiki\"\nimport * as ts from \"typescript\"\nimport type {Plugin} from \"vite\"\n\nimport {\n quiCustomDarkTheme,\n type ReactDemoData,\n type SourceCodeData,\n} from \"@qualcomm-ui/mdx-common\"\nimport {dedent} from \"@qualcomm-ui/utils/dedent\"\n\nimport {getShikiTransformers} from \"../docs-plugin\"\nimport {\n extractPreviewFromHighlightedHtml,\n transformerCodeAttribute,\n transformerPreviewBlock,\n} from \"../docs-plugin/shiki\"\nimport {createShikiTailwindTransformer} from \"../docs-plugin/shiki/internal\"\n\nimport {LOG_PREFIX, VIRTUAL_MODULE_IDS} from \"./demo-plugin-constants\"\nimport type {QuiDemoPluginOptions} from \"./demo-plugin-types\"\nimport {\n createDemoName,\n extractFileImports,\n extractPageId,\n getScriptKind,\n isCssAsset,\n isDemoFile,\n} from \"./demo-plugin-utils\"\n\ninterface HandleUpdateOptions {\n demoName?: string\n filePath: string\n}\n\ninterface HighlightCodeResult {\n full: string\n preview?: string | null\n}\n\ninterface ExtractedSourceCode {\n residualRules?: Map<string, string>\n sourceCodeData: SourceCodeData\n}\n\nlet highlighter: Highlighter | null = null\nlet initializingHighlighter = false\n\nconst demoRegistry = new Map<string, ReactDemoData>()\nconst pageFiles = new Map<string, string[]>()\nconst relativeImportDependents = new Map<string, Set<string>>()\n\n/**\n * Generates virtual modules for React demo components. Virtual modules contain\n * highlighted source code and metadata about each demo.\n */\nexport function reactDemoPlugin({\n demoPattern = \"src/routes/**/demos/*.tsx\",\n routesDir = \"src/routes\",\n theme = {\n dark: quiCustomDarkTheme,\n light: \"github-light-high-contrast\",\n },\n transformers = [],\n transformLine,\n transformTailwindStyles,\n}: QuiDemoPluginOptions = {}): Plugin {\n const defaultShikiOptions = {\n defaultColor: \"light-dark()\",\n lang: \"tsx\",\n themes: {\n dark: theme.dark,\n light: theme.light,\n },\n }\n\n return {\n apply(config, env) {\n return (\n (env.mode === \"development\" && env.command === \"serve\") ||\n (env.mode === \"production\" && env.command === \"build\")\n )\n },\n async buildStart() {\n if (!highlighter && !initializingHighlighter) {\n initializingHighlighter = true\n try {\n highlighter = await createHighlighter({\n langs: [\"tsx\", \"typescript\", \"css\"],\n themes: [theme.dark, theme.light],\n })\n console.log(\n `${chalk.magenta.bold(LOG_PREFIX)} Shiki highlighter initialized`,\n )\n } catch (error) {\n console.warn(\n `${chalk.magenta.bold(LOG_PREFIX)} Failed to initialize highlighter:`,\n error,\n )\n } finally {\n initializingHighlighter = false\n }\n }\n\n await collectReactDemos()\n },\n\n async handleHotUpdate({file, modules, server}) {\n if (isCssAsset(file)) {\n return modules\n }\n\n if (file.endsWith(\".mdx\")) {\n return []\n }\n\n if (isDemoFile(file)) {\n await handleDemoAdditionOrUpdate({filePath: file})\n } else {\n const normalizedFile = resolve(file)\n const dependentDemos = relativeImportDependents.get(normalizedFile)\n if (!dependentDemos?.size) {\n return []\n }\n for (const demoName of Array.from(dependentDemos)) {\n const demo = demoRegistry.get(demoName)\n if (demo) {\n await handleDemoAdditionOrUpdate({\n filePath: demo.filePath,\n })\n }\n }\n }\n\n const autoModule = server.moduleGraph.getModuleById(\n VIRTUAL_MODULE_IDS.AUTO,\n )\n if (autoModule) {\n server.moduleGraph.invalidateModule(autoModule)\n await server.reloadModule(autoModule)\n }\n return []\n },\n\n load(id) {\n if (id === VIRTUAL_MODULE_IDS.AUTO) {\n return generateAutoScopeModule()\n }\n },\n\n name: \"auto-demo-scope\",\n\n resolveId(id) {\n if (id === \"virtual:qui-demo-scope/auto\") {\n return VIRTUAL_MODULE_IDS.AUTO\n }\n },\n\n writeBundle() {\n console.log(\n `${chalk.blue.bold(LOG_PREFIX)} Successfully integrated ${chalk.green(demoRegistry.size)} component demos`,\n )\n },\n }\n\n async function handleDemoAdditionOrUpdate({\n filePath,\n }: HandleUpdateOptions): Promise<void> {\n const pageId = extractPageId(filePath, routesDir)\n const demoName = createDemoName(filePath)\n\n const existingFiles = pageFiles.get(pageId) ?? []\n if (!existingFiles.includes(filePath)) {\n existingFiles.push(filePath)\n pageFiles.set(pageId, existingFiles)\n }\n\n const fileData = await extractFileData(filePath)\n if (fileData) {\n demoRegistry.set(demoName, {\n ...fileData,\n demoName,\n pageId,\n })\n\n const fileImports = await extractFileImports(filePath)\n if (fileImports) {\n for (const relativeImport of fileImports.relativeImports) {\n const dependents =\n relativeImportDependents.get(relativeImport.resolvedPath) ??\n new Set()\n dependents.add(demoName)\n relativeImportDependents.set(relativeImport.resolvedPath, dependents)\n }\n }\n }\n }\n\n async function highlightCode(\n code: string,\n options: {\n extraTransformers?: ShikiTransformer[]\n onClassesDetected?: (detected: boolean) => void\n onResidualCss?: (rules: Map<string, string>) => void\n } = {},\n ): Promise<HighlightCodeResult> {\n const {extraTransformers = [], onResidualCss} = options\n\n if (!highlighter) {\n return {full: code}\n }\n let previewCode: string | null = null\n\n const tailwindTransformers: ShikiTransformer[] = []\n if (transformTailwindStyles && onResidualCss) {\n const transformer = await createShikiTailwindTransformer({\n onClassesDetected: (detected) => {\n options.onClassesDetected?.(detected)\n },\n onResidualCss,\n styleFormat: \"jsx\",\n styles: dedent`\n @layer theme, base, components, utilities;\n @import \"tailwindcss/theme.css\" layer(theme);\n @import \"tailwindcss/utilities.css\" layer(utilities);\n @import \"@qualcomm-ui/tailwind-plugin/qui-strict.css\";\n `,\n })\n tailwindTransformers.push(transformer)\n } else if (extraTransformers.length > 0) {\n tailwindTransformers.push(...extraTransformers)\n }\n\n try {\n const highlightedCode = highlighter.codeToHtml(code, {\n ...defaultShikiOptions,\n transformers: [\n ...getShikiTransformers(),\n ...transformers,\n ...tailwindTransformers,\n transformerPreviewBlock({\n attributeName: \"data-preview\",\n onComplete: (extractedPreview) => {\n previewCode = extractedPreview\n },\n }),\n transformerCodeAttribute({\n attributeName: \"data-code\",\n }),\n {\n enforce: \"post\",\n name: \"shiki-transformer-trim\",\n preprocess(code) {\n return code.trim()\n },\n },\n ...transformers,\n ],\n })\n\n return {\n full: highlightedCode,\n preview: previewCode\n ? extractPreviewFromHighlightedHtml(highlightedCode)\n : null,\n }\n } catch (error) {\n console.warn(\n `${chalk.magenta.bold(LOG_PREFIX)} Failed to highlight code:`,\n error,\n )\n return {full: code}\n }\n }\n\n async function collectReactDemos() {\n if (demoRegistry.size) {\n return\n }\n\n const demoFiles = (await glob(demoPattern)).filter(isDemoFile)\n\n for (const filePath of demoFiles) {\n const pageId = extractPageId(filePath, routesDir)\n const existingFiles = pageFiles.get(pageId) ?? []\n existingFiles.push(filePath)\n pageFiles.set(pageId, existingFiles)\n\n const fileData = await extractFileData(filePath)\n if (fileData) {\n const demoName = createDemoName(filePath)\n demoRegistry.set(demoName, {\n ...fileData,\n pageId,\n })\n }\n\n const fileImports = await extractFileImports(filePath)\n if (fileImports) {\n for (const relativeImport of fileImports.relativeImports) {\n const demoName = createDemoName(filePath)\n const dependents =\n relativeImportDependents.get(relativeImport.resolvedPath) ??\n new Set()\n dependents.add(demoName)\n relativeImportDependents.set(relativeImport.resolvedPath, dependents)\n }\n }\n }\n }\n\n function generateAutoScopeModule(): string {\n const registryCode = generateDemoRegistry(demoRegistry)\n return [\n \"// Auto-generated demo scope resolver (PROD MODE)\",\n registryCode,\n generateExportedFunctions(),\n ].join(\"\\n\\n\")\n }\n\n function transformLines(code: string): string {\n if (!transformLine) {\n return code\n }\n const result: string[] = []\n for (const line of code.split(\"\\n\")) {\n if (line.trim()) {\n const transformed = transformLine(line)\n if (transformed) {\n result.push(transformed)\n }\n } else {\n // include all empty lines\n result.push(line)\n }\n }\n return result.join(\"\\n\")\n }\n\n async function extractHighlightedCode(\n filePath: string,\n code: string,\n ): Promise<ExtractedSourceCode | null> {\n try {\n const fileName = basename(filePath)\n\n const baseResult = await highlightCode(code)\n\n let inlineResult: HighlightCodeResult | undefined\n let classesDetected: boolean = false\n let residualRules: Map<string, string> | undefined\n\n if (transformTailwindStyles) {\n inlineResult = await highlightCode(code, {\n onClassesDetected: (detected) => {\n classesDetected = detected\n },\n onResidualCss: (rules) => {\n residualRules = rules\n },\n })\n }\n\n return {\n residualRules,\n sourceCodeData: {\n fileName,\n filePath,\n highlighted: {\n full: baseResult.full,\n preview: baseResult.preview,\n },\n highlightedInline:\n classesDetected && inlineResult\n ? {\n full: inlineResult.full,\n preview: inlineResult.preview,\n }\n : undefined,\n type: \"file\",\n },\n }\n } catch {\n return null\n }\n }\n\n async function extractFileData(\n filePath: string,\n ): Promise<Omit<ReactDemoData, \"pageId\"> | null> {\n try {\n const code = await readFile(filePath, \"utf-8\").then(transformLines)\n const imports = stripImports(code, filePath)\n\n const sourceCode: SourceCodeData[] = []\n // Use Map for deduplication across all files in this demo\n const aggregatedRules = new Map<string, string>()\n\n const extractedMain = await extractHighlightedCode(filePath, code)\n\n if (extractedMain) {\n sourceCode.push(extractedMain.sourceCodeData)\n if (extractedMain.residualRules) {\n for (const [className, rule] of extractedMain.residualRules) {\n aggregatedRules.set(className, rule)\n }\n }\n }\n\n const fileImports = await extractFileImports(filePath)\n if (fileImports) {\n for (const relativeImport of fileImports.relativeImports) {\n try {\n const importedCode = await readFile(\n relativeImport.resolvedPath,\n \"utf-8\",\n ).then(transformLines)\n\n const extracted = await extractHighlightedCode(\n relativeImport.resolvedPath,\n importedCode,\n )\n\n if (extracted) {\n sourceCode.push(extracted.sourceCodeData)\n if (extracted.residualRules) {\n for (const [className, rule] of extracted.residualRules) {\n aggregatedRules.set(className, rule)\n }\n }\n }\n } catch {\n console.debug(\"Failed to process file\", relativeImport.resolvedPath)\n }\n }\n }\n\n // Convert aggregated rules to CSS string\n const aggregatedResidualCss =\n aggregatedRules.size > 0\n ? [...aggregatedRules.values()].join(\"\\n\\n\")\n : undefined\n\n if (aggregatedResidualCss) {\n sourceCode.push({\n fileName: \"styles.css\",\n highlighted: await highlightCode(aggregatedResidualCss),\n type: \"residual-css\",\n })\n }\n\n return {\n demoName: createDemoName(filePath),\n fileName: extractedMain?.sourceCodeData.fileName || basename(filePath),\n filePath,\n imports,\n sourceCode,\n }\n } catch {\n return null\n }\n }\n\n function stripImports(code: string, fileName: string): string[] {\n try {\n const sourceFile = ts.createSourceFile(\n fileName,\n code,\n ts.ScriptTarget.Latest,\n true,\n getScriptKind(fileName),\n )\n\n const importRanges: Array<{end: number; start: number}> = []\n\n function visit(node: ts.Node) {\n if (ts.isImportDeclaration(node)) {\n importRanges.push({\n end: node.getEnd(),\n start: node.getFullStart(),\n })\n }\n ts.forEachChild(node, visit)\n }\n\n visit(sourceFile)\n\n return importRanges.map((range) => {\n let endPos = range.end\n if (code[endPos] === \"\\n\") {\n endPos++\n }\n return code.slice(range.start, endPos).trim()\n })\n } catch (error) {\n return []\n }\n }\n\n function generateDemoRegistry(registry: Map<string, ReactDemoData>): string {\n const entries = Array.from(registry.entries())\n .map(([demoName, {fileName, imports, pageId, sourceCode}]) => {\n return ` [\"${demoName}\", { fileName: \"${fileName}\", imports: ${JSON.stringify(imports)}, pageId: \"${pageId}\", sourceCode: ${JSON.stringify(sourceCode)}, demoName: \"${demoName}\" }]`\n })\n .join(\",\\n\")\n return `const demoRegistry = new Map([\\n${entries}\\n])`\n }\n\n function generateExportedFunctions(): string {\n return dedent`\n export function getDemo(demoName) {\n const demo = demoRegistry.get(demoName)\n if (!demo) {\n return {\n fileName: \"\",\n imports: [],\n errorMessage: \\`Demo \"\\${demoName}\" not found.\\`,\n pageId: \"\",\n sourceCode: [],\n }\n }\n return demo\n }\n `\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;AAEA,OAAOA,YAAW;AAClB,SAAwB,aAAY;AACpC,SAAQ,QAAAC,aAAW;AACnB,SAAQ,YAAY,gBAAe;AACnC,SAAQ,YAAAC,iBAAe;AACvB,SAAQ,YAAAC,WAAU,WAAAC,UAAS,QAAAC,OAAM,YAAAC,WAAU,WAAAC,gBAAc;AACzD;AAAA,EACE;AAAA,OAKK;AACP,YAAYC,SAAQ;AAGpB;AAAA,EAEE,sBAAAC;AAAA,OAEK;AACP,SAAQ,UAAAC,eAAa;;;ACpBrB,SAA6C,uBAAsB;;;ACG5D,SAAS,QAAQ,KAAqB;AAC3C,SAAO,IAAI,WAAW,MAAM,GAAG;AACjC;AAKO,SAAS,oBAAoB,KAAqB;AACvD,SAAO,IAAI,SAAS,GAAG,IAAI,IAAI,UAAU,GAAG,IAAI,SAAS,CAAC,IAAI;AAChE;;;ACZA,SAAQ,KAAAC,UAAwC;;;ACAhD,SAAQ,SAAQ;AAYT,SAAS,YAA2B;AACzC,SAAO;AAAA,IACL,MAAM,CAKJ,WACG,EAAE,OAAO,MAAM;AAAA,EACtB;AACF;;;ADPO,IAAM,gBAA+B,UAAmB,EAAE,KAAK;AAAA,EACpE,IAAIC,GAAE,MAAM,EAAE,SAAS;AAAA,EACvB,cAAcA,GAAE,OAAO,EAAE,SAAS;AAAA,EAClC,WAAWA,GAAE,QAAQ,EAAE,SAAS;AAClC,CAAC;AAEM,IAAM,kBACX,UAAqB,EAAE,KAAK;AAAA,EAC1B,UAAUA,GAAE,MAAMA,GAAE,KAAK,MAAM,eAAe,CAAC,EAAE,SAAS;AAAA,EAC1D,UAAUA,GAAE,QAAQ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,EACA,KAAK,KAAK;AACb,WAAO;AAAA,EAAmC,OAAO;AAAA;AAAA,EACnD;AAEA,WAAS,4BAAoC;AAC3C,WAAOL;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAeT;AACF;",
|
|
6
|
-
"names": ["chalk", "glob", "readFile", "basename", "dirname", "join", "relative", "resolve", "ts", "quiCustomDarkTheme", "dedent", "z", "z", "join", "chalk", "readFileSync", "join", "resolve", "z", "z", "remarkFrontmatter", "remarkParse", "remarkStringify", "unified", "item", "visit", "visit", "visit", "visit", "visit", "remove", "visit", "visit", "visit", "unified", "remarkParse", "remarkFrontmatter", "remarkStringify", "minimatch", "join", "visit", "capitalCase", "segment", "capitalCase", "state", "routeSegment", "readFile", "join", "visit", "createHash", "join", "resolve", "resolve", "join", "readFile", "visit", "join", "readFile", "dirname", "join", "resolve", "visit", "resolve", "join", "dirname", "readFile", "visit", "visit", "visit", "visit", "visit", "visit", "toString", "remarkGfm", "remarkStringify", "unified", "visit", "
|
|
4
|
+
"sourcesContent": ["// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\nimport chalk from \"chalk\"\nimport {type FSWatcher, watch} from \"chokidar\"\nimport {glob} from \"glob\"\nimport {existsSync, statSync} from \"node:fs\"\nimport {readFile} from \"node:fs/promises\"\nimport {basename, dirname, join, relative, resolve} from \"node:path\"\nimport {\n createHighlighter,\n type Highlighter,\n type ThemeRegistration,\n type ThemeRegistrationRaw,\n type ThemeRegistrationResolved,\n} from \"shiki\"\nimport * as ts from \"typescript\"\nimport type {Plugin, ViteDevServer} from \"vite\"\n\nimport {\n type AngularDemoInfo,\n quiCustomDarkTheme,\n type SourceCodeData,\n} from \"@qualcomm-ui/mdx-common\"\nimport {dedent} from \"@qualcomm-ui/utils/dedent\"\n\nimport {getShikiTransformers} from \"../docs-plugin\"\nimport {\n extractPreviewFromHighlightedHtml,\n transformerCodeAttribute,\n transformerPreviewBlock,\n} from \"../docs-plugin/shiki\"\nimport {createShikiTailwindTransformer} from \"../docs-plugin/shiki/internal\"\n\nexport interface AngularDemoPluginOptions {\n demoPattern?: string | string[]\n /**\n * A mapping of <demoId, initialHtml>, which will be used for the initial\n * serverside render of each demo to prevent FOUC.\n */\n initialHtml?: Record<string, string>\n routesDir?: string\n theme?: {\n dark:\n | ThemeRegistrationRaw\n | ThemeRegistration\n | ThemeRegistrationResolved\n | string\n light:\n | ThemeRegistrationRaw\n | ThemeRegistration\n | ThemeRegistrationResolved\n | string\n }\n /**\n * When enabled, transforms Tailwind class names to inline styles in the\n * highlighted code. Non-inlineable classes (hover:, sm:, etc.) are kept as\n * className and their CSS rules are aggregated into a residual-css entry.\n */\n transformTailwindStyles?: boolean\n}\n\ninterface RelativeImport {\n resolvedPath: string\n source: string\n}\n\ninterface PathAlias {\n pattern: RegExp\n replacement: string\n}\n\ninterface HighlightCodeResult {\n full: string\n preview?: string | null\n}\n\nconst VIRTUAL_MODULE_ID = \"\\0virtual:angular-demo-registry\"\nconst LOG_PREFIX = \"[angular-demo]\"\n\nlet hasWatcherInitialized = false\n\nfunction logDev(...args: any[]) {\n if (!hasWatcherInitialized) {\n return\n }\n console.log(...args)\n}\n\nlet demoDimensionsCache: Record<string, DOMRect> = {}\nlet highlighter: Highlighter | null = null\nlet initCount = 0\nconst demoRegistry = new Map<string, AngularDemoInfo>()\nlet hotUpdateDemoIds: string[] = []\n\nexport function angularDemoPlugin({\n demoPattern = \"src/routes/**/demos/*.ts\",\n initialHtml,\n routesDir = \"src/routes\",\n theme = {\n dark: quiCustomDarkTheme,\n light: \"github-light-high-contrast\",\n },\n transformTailwindStyles,\n}: AngularDemoPluginOptions = {}): Plugin {\n let watcher: FSWatcher | null = null\n let devServer: ViteDevServer | null = null\n\n const defaultShikiOptions = {\n defaultColor: \"light-dark()\",\n themes: {\n dark: theme.dark,\n light: theme.light,\n },\n }\n\n return {\n async buildEnd() {\n if (watcher) {\n await watcher.close()\n watcher = null\n hasWatcherInitialized = false\n }\n },\n async buildStart() {\n if (initCount === 0) {\n initCount++\n return\n }\n\n if (!highlighter) {\n try {\n highlighter = await createHighlighter({\n langs: [\"angular-ts\", \"angular-html\", \"css\"],\n themes: [theme.dark, theme.light],\n })\n logDev(`${chalk.blue.bold(LOG_PREFIX)} Shiki highlighter initialized`)\n } catch (error) {\n console.warn(\n `${chalk.blue.bold(LOG_PREFIX)} Failed to initialize highlighter:`,\n error,\n )\n }\n }\n\n logDev(`${chalk.blue.bold(LOG_PREFIX)} Initializing Angular demo scanner`)\n await collectAngularDemos()\n\n if (process.env.NODE_ENV === \"development\") {\n if (!hasWatcherInitialized) {\n hasWatcherInitialized = true\n setupAngularWatcher()\n } else {\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} Watcher already initialized by another instance`,\n )\n }\n }\n },\n configureServer(server) {\n devServer = server\n let dimensionUpdateTimeout: NodeJS.Timeout | null = null\n\n server.ws.on(\n \"custom:store-demo-dimensions\",\n (data: {demoId: string; dimensions: DOMRect}) => {\n const demoId = data.demoId\n demoDimensionsCache[demoId] = data.dimensions\n\n if (dimensionUpdateTimeout) {\n clearTimeout(dimensionUpdateTimeout)\n }\n\n dimensionUpdateTimeout = setTimeout(() => {\n const module = server.moduleGraph.getModuleById(VIRTUAL_MODULE_ID)\n if (module) {\n server.moduleGraph.invalidateModule(module)\n }\n }, 50)\n },\n )\n\n server.ws.on(\"custom:reset-demo-dimensions\", () => {\n demoDimensionsCache = {}\n const module = server.moduleGraph.getModuleById(VIRTUAL_MODULE_ID)\n if (module) {\n server.moduleGraph.invalidateModule(module)\n server.reloadModule(module)\n }\n })\n },\n async handleHotUpdate({file, modules, server}) {\n if (!isAngularDemoFile(file)) {\n if (isCssAsset(file)) {\n return modules\n }\n\n if (file.endsWith(\"main.js\")) {\n const ids = [...hotUpdateDemoIds]\n server.ws.send({\n data: {\n demoInfo: ids.reduce(\n (acc: Record<string, AngularDemoInfo | undefined>, current) => {\n acc[current] = demoRegistry.get(current)\n return acc\n },\n {},\n ),\n },\n event: \"demo-bundle-updated\",\n type: \"custom\",\n })\n }\n\n return []\n }\n\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} Processing Angular demo change: ${chalk.cyan(file)}`,\n )\n\n const code = await readFile(file, \"utf-8\")\n const demoInfo = await parseAngularDemo(file, code)\n\n if (!demoInfo || !isAngularDemoEntrypoint(file)) {\n // might be an imported file\n const affectedDemos: AngularDemoInfo[] =\n await scanDemosForFileImport(file)\n\n if (affectedDemos.length > 0) {\n hotUpdateDemoIds = []\n for (const demo of affectedDemos) {\n hotUpdateDemoIds.push(demo.id)\n }\n }\n\n server.ws.send({\n data: {\n ids: [...hotUpdateDemoIds],\n },\n event: \"demo-bundle-updating\",\n type: \"custom\",\n })\n\n return\n }\n\n delete demoDimensionsCache[demoInfo.id]\n demoRegistry.set(demoInfo.id, demoInfo)\n hotUpdateDemoIds = [demoInfo.id]\n\n server.ws.send({\n data: {\n ids: [...hotUpdateDemoIds],\n },\n event: \"demo-bundle-updating\",\n type: \"custom\",\n })\n\n const mainModule = server.moduleGraph.getModuleById(VIRTUAL_MODULE_ID)\n if (mainModule) {\n server.moduleGraph.invalidateModule(mainModule)\n }\n\n const demoModule = server.moduleGraph.getModuleById(file)\n if (demoModule) {\n server.moduleGraph.invalidateModule(demoModule)\n }\n\n return []\n },\n load(id) {\n if (id === VIRTUAL_MODULE_ID) {\n return generateRegistryModule()\n }\n },\n name: \"angular-demo-plugin\",\n resolveId(id) {\n if (id === \"virtual:angular-demo-registry\") {\n return VIRTUAL_MODULE_ID\n }\n },\n writeBundle() {\n console.log(\n `${chalk.blue.bold(LOG_PREFIX)} Successfully integrated ${chalk.green(demoRegistry.size)} component demos`,\n )\n },\n }\n\n async function collectAngularDemos() {\n if (demoRegistry.size) {\n logDev(\n `${chalk.magenta.bold(LOG_PREFIX)} Using cached ${chalk.cyanBright.bold(demoRegistry.size)} demos`,\n )\n return\n }\n\n const demoFiles = await glob(demoPattern)\n demoRegistry.clear()\n\n for (const filePath of demoFiles) {\n const code = await readFile(filePath, \"utf-8\")\n const demoInfo = await parseAngularDemo(filePath, code)\n if (demoInfo) {\n demoRegistry.set(demoInfo.id, demoInfo)\n }\n }\n }\n\n async function scanDemosForFileImport(\n file: string,\n ): Promise<AngularDemoInfo[]> {\n const affectedDemos: AngularDemoInfo[] = []\n\n for (const [demoId, demo] of demoRegistry.entries()) {\n if (demo.sourceCode.find((entry) => entry.filePath === file)) {\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} Reloading demo ${chalk.cyan(demoId)} due to imported file change: ${chalk.yellow(file)}`,\n )\n\n const code = await readFile(demo.filePath, \"utf-8\")\n const updatedDemo = await parseAngularDemo(demo.filePath, code)\n\n if (updatedDemo) {\n delete demoDimensionsCache[updatedDemo.id]\n demoRegistry.set(updatedDemo.id, updatedDemo)\n affectedDemos.push(updatedDemo)\n hotUpdateDemoIds.push(updatedDemo.id)\n }\n }\n }\n\n return affectedDemos\n }\n\n async function highlightCode(\n code: string,\n language: \"angular-ts\" | \"angular-html\" | \"css\" = \"angular-ts\",\n options: {\n onClassesDetected?: (detected: boolean) => void\n onResidualCss?: (rules: Map<string, string>) => void\n } = {},\n ): Promise<HighlightCodeResult> {\n const {onClassesDetected, onResidualCss} = options\n\n if (!highlighter) {\n return {full: code}\n }\n\n let previewCode: string | null = null\n\n const tailwindTransformers = []\n if (transformTailwindStyles && onResidualCss) {\n const transformer = await createShikiTailwindTransformer({\n onClassesDetected: (detected) => {\n onClassesDetected?.(detected)\n },\n onResidualCss,\n styleFormat: \"html\",\n styles: dedent`\n @layer theme, base, components, utilities;\n @import \"tailwindcss/theme.css\" layer(theme);\n @import \"tailwindcss/utilities.css\" layer(utilities);\n @import \"@qualcomm-ui/tailwind-plugin/qui-strict.css\";\n `,\n })\n tailwindTransformers.push(transformer)\n }\n\n try {\n const highlightedCode = highlighter.codeToHtml(code, {\n ...defaultShikiOptions,\n lang: language,\n transformers: [\n ...getShikiTransformers(),\n ...tailwindTransformers,\n transformerPreviewBlock({\n attributeName: \"data-preview\",\n onComplete: (extractedPreview) => {\n previewCode = extractedPreview\n },\n }),\n transformerCodeAttribute({\n attributeName: \"data-code\",\n }),\n {\n enforce: \"post\",\n name: \"shiki-transformer-trim\",\n preprocess(inner) {\n return inner.trim()\n },\n },\n ],\n })\n\n return {\n full: highlightedCode,\n preview: previewCode\n ? extractPreviewFromHighlightedHtml(highlightedCode)\n : null,\n }\n } catch (error) {\n console.warn(\n `${chalk.blue.bold(LOG_PREFIX)} Failed to highlight code with ${language} language:`,\n error,\n )\n return {full: code}\n }\n }\n\n async function extractRelativeImports(\n filePath: string,\n ): Promise<RelativeImport[]> {\n try {\n const content = await readFile(filePath, \"utf-8\")\n\n const sourceFile = ts.createSourceFile(\n filePath,\n content,\n ts.ScriptTarget.Latest,\n true,\n ts.ScriptKind.TS,\n )\n\n const relativeImports: RelativeImport[] = []\n\n function visit(node: ts.Node) {\n if (ts.isImportDeclaration(node)) {\n const moduleSpecifier = node.moduleSpecifier\n\n if (ts.isStringLiteral(moduleSpecifier)) {\n const source = moduleSpecifier.text\n\n if (isRelativeImport(source)) {\n const resolvedPath = resolveRelativeImport(source, filePath)\n relativeImports.push({resolvedPath, source})\n } else if (!isNodeBuiltin(source)) {\n const pathAliases = loadTsConfigPaths(filePath)\n\n if (isPathAliasImport(source, pathAliases)) {\n const resolvedPath = resolvePathAlias(source, pathAliases)\n if (resolvedPath) {\n relativeImports.push({resolvedPath, source})\n }\n }\n }\n }\n }\n\n ts.forEachChild(node, visit)\n }\n\n visit(sourceFile)\n\n return relativeImports\n } catch (error) {\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} ${chalk.yellowBright(\"Failed to extract imports from\")} ${chalk.cyan(filePath)}:`,\n error,\n )\n return []\n }\n }\n\n async function collectAllImports(\n filePath: string,\n visited = new Set<string>(),\n ): Promise<string[]> {\n if (visited.has(filePath)) {\n return []\n }\n\n visited.add(filePath)\n\n const directImports = await extractRelativeImports(filePath)\n\n for (const {resolvedPath} of directImports) {\n await collectAllImports(resolvedPath, visited)\n }\n\n return Array.from(visited).slice(1)\n }\n\n function stripImports(code: string, fileName: string): string[] {\n try {\n const sourceFile = ts.createSourceFile(\n fileName,\n code,\n ts.ScriptTarget.Latest,\n true,\n ts.ScriptKind.TS,\n )\n\n const importRanges: Array<{end: number; start: number}> = []\n\n function visit(node: ts.Node) {\n if (ts.isImportDeclaration(node)) {\n importRanges.push({\n end: node.getEnd(),\n start: node.getFullStart(),\n })\n }\n\n ts.forEachChild(node, visit)\n }\n\n visit(sourceFile)\n\n return importRanges.map((range) => {\n let endPos = range.end\n if (code[endPos] === \"\\n\") {\n endPos++\n }\n return code.slice(range.start, endPos).trim()\n })\n } catch (error) {\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} ${chalk.redBright(\"Failed to strip imports from\")} ${chalk.cyan(fileName)}:`,\n error,\n )\n return []\n }\n }\n\n async function parseAngularDemo(\n filePath: string,\n code: string,\n ): Promise<AngularDemoInfo | null> {\n try {\n const {\n componentClass,\n hasDefaultExport,\n isStandalone,\n selector,\n templateUrl,\n } = parseAngularComponentMeta(filePath, code)\n\n if (!componentClass || !selector) {\n return null\n }\n\n const demoId = componentClass\n const importPath = relative(process.cwd(), filePath).replace(/\\\\/g, \"/\")\n const fileName = basename(filePath)\n const importsWithoutStrip = stripImports(code, filePath)\n\n const sourceCode: SourceCodeData[] = []\n // Use Map for deduplication across all files in this demo\n const aggregatedRules = new Map<string, string>()\n\n const mainSourceEntry = await buildAngularSourceEntry({\n code,\n fileName,\n filePath,\n language: \"angular-ts\",\n })\n sourceCode.push(mainSourceEntry.sourceCodeData)\n if (mainSourceEntry.residualRules) {\n for (const [className, rule] of mainSourceEntry.residualRules) {\n aggregatedRules.set(className, rule)\n }\n }\n\n if (templateUrl) {\n const templateEntry = await maybeBuildTemplateSourceEntry(\n templateUrl,\n filePath,\n )\n if (templateEntry) {\n sourceCode.push(templateEntry.sourceCodeData)\n if (templateEntry.residualRules) {\n for (const [className, rule] of templateEntry.residualRules) {\n aggregatedRules.set(className, rule)\n }\n }\n }\n }\n\n const importedEntries = await buildImportedSourceEntries(filePath)\n for (const entry of importedEntries) {\n sourceCode.push(entry.sourceCodeData)\n if (entry.residualRules) {\n for (const [className, rule] of entry.residualRules) {\n aggregatedRules.set(className, rule)\n }\n }\n }\n\n // Convert aggregated rules to CSS string\n const aggregatedResidualCss =\n aggregatedRules.size > 0\n ? [...aggregatedRules.values()].join(\"\\n\\n\")\n : undefined\n\n if (aggregatedResidualCss) {\n const cssHighlighted = await highlightCode(aggregatedResidualCss, \"css\")\n sourceCode.push({\n fileName: \"styles.css\",\n highlighted: cssHighlighted,\n type: \"residual-css\",\n })\n }\n\n return {\n componentClass,\n filePath: importPath.startsWith(\".\") ? importPath : `./${importPath}`,\n hasDefaultExport,\n id: demoId,\n imports: importsWithoutStrip,\n initialHtml: initialHtml?.[demoId] || undefined,\n isStandalone,\n lastModified: Date.now(),\n selector,\n sourceCode,\n }\n } catch (error) {\n console.error(\n `${chalk.blue.bold(LOG_PREFIX)} Failed to parse Angular demo ${filePath}:`,\n error,\n )\n return null\n }\n }\n\n function parseAngularComponentMeta(\n filePath: string,\n source: string,\n ): {\n componentClass: string\n hasDefaultExport: boolean\n importsFromAst: string[]\n isStandalone: boolean\n selector: string\n templateUrl: string | null\n } {\n const sourceFile = ts.createSourceFile(\n filePath,\n source,\n ts.ScriptTarget.Latest,\n true,\n ts.ScriptKind.TS,\n )\n\n let componentClass = \"\"\n let selector = \"\"\n let isStandalone = true\n let templateUrl: string | null = null\n let hasDefaultExport = false\n const importsFromAst: string[] = []\n\n function visit(node: ts.Node) {\n if (ts.isImportDeclaration(node)) {\n importsFromAst.push(node.getFullText(sourceFile).trim())\n }\n\n if (ts.isClassDeclaration(node)) {\n const decorators = node.modifiers?.filter(ts.isDecorator)\n const componentDecorator = decorators?.find((decorator) => {\n if (!ts.isCallExpression(decorator.expression)) {\n return false\n }\n const expression = decorator.expression.expression\n return ts.isIdentifier(expression) && expression.text === \"Component\"\n })\n\n if (componentDecorator && node.name) {\n componentClass = node.name.text\n\n if (\n ts.isCallExpression(componentDecorator.expression) &&\n componentDecorator.expression.arguments[0] &&\n ts.isObjectLiteralExpression(\n componentDecorator.expression.arguments[0],\n )\n ) {\n const properties =\n componentDecorator.expression.arguments[0].properties\n\n const selectorProp = properties.find(\n (prop) =>\n ts.isPropertyAssignment(prop) &&\n ts.isIdentifier(prop.name) &&\n prop.name.text === \"selector\",\n ) as ts.PropertyAssignment | undefined\n\n if (selectorProp && ts.isStringLiteral(selectorProp.initializer)) {\n selector = selectorProp.initializer.text\n }\n\n const templateUrlProp = properties.find(\n (prop) =>\n ts.isPropertyAssignment(prop) &&\n ts.isIdentifier(prop.name) &&\n prop.name.text === \"templateUrl\",\n ) as ts.PropertyAssignment | undefined\n\n if (templateUrlProp) {\n const init = templateUrlProp.initializer\n if (ts.isStringLiteral(init)) {\n templateUrl = init.text\n } else if (ts.isNoSubstitutionTemplateLiteral(init)) {\n templateUrl = init.text\n }\n }\n\n const standaloneProp = properties.find(\n (prop) =>\n ts.isPropertyAssignment(prop) &&\n ts.isIdentifier(prop.name) &&\n prop.name.text === \"standalone\",\n ) as ts.PropertyAssignment | undefined\n\n if (\n standaloneProp &&\n standaloneProp.initializer.kind === ts.SyntaxKind.FalseKeyword\n ) {\n isStandalone = false\n }\n }\n }\n }\n\n if (ts.isExportAssignment(node) && !node.isExportEquals) {\n hasDefaultExport = true\n }\n\n ts.forEachChild(node, visit)\n }\n\n visit(sourceFile)\n\n return {\n componentClass,\n hasDefaultExport,\n importsFromAst,\n isStandalone,\n selector,\n templateUrl,\n }\n }\n\n interface BuildAngularSourceEntryParams {\n code: string\n fileName: string\n filePath: string\n language: \"angular-ts\" | \"angular-html\"\n }\n\n interface ExtractedSourceCode {\n residualRules?: Map<string, string>\n sourceCodeData: SourceCodeData\n }\n\n async function buildAngularSourceEntry(\n params: BuildAngularSourceEntryParams,\n ): Promise<ExtractedSourceCode> {\n const {code, fileName, filePath, language} = params\n\n const baseResult = await highlightCode(code, language)\n\n let inlineResult: HighlightCodeResult | undefined\n let classesDetected = false\n let residualRules: Map<string, string> | undefined\n\n if (transformTailwindStyles) {\n inlineResult = await highlightCode(code, language, {\n onClassesDetected: (detected) => {\n classesDetected = detected\n },\n onResidualCss: (rules) => {\n residualRules = rules\n },\n })\n }\n\n return {\n residualRules,\n sourceCodeData: {\n fileName,\n filePath,\n highlighted: {\n full: baseResult.full,\n preview: baseResult.preview,\n },\n highlightedInline:\n classesDetected && inlineResult\n ? {\n full: inlineResult.full,\n preview: inlineResult.preview,\n }\n : undefined,\n type: \"file\",\n },\n }\n }\n\n async function maybeBuildTemplateSourceEntry(\n templateUrl: string,\n fromFilePath: string,\n ): Promise<ExtractedSourceCode | null> {\n const templatePath = resolveTemplateFile(templateUrl, fromFilePath)\n if (!existsSync(templatePath)) {\n return null\n }\n\n try {\n const templateCode = await readFile(templatePath, \"utf-8\")\n\n return buildAngularSourceEntry({\n code: templateCode,\n fileName: basename(templatePath),\n filePath: templatePath,\n language: \"angular-html\",\n })\n } catch (error) {\n console.log(\n `${chalk.blue.bold(LOG_PREFIX)} ${chalk.redBright(\"Failed to read template file:\")} ${chalk.cyan(templatePath)}`,\n error,\n )\n return null\n }\n }\n\n async function buildImportedSourceEntries(\n fromFilePath: string,\n ): Promise<ExtractedSourceCode[]> {\n const entries: ExtractedSourceCode[] = []\n const relativeImports = await collectAllImports(fromFilePath)\n\n for (const resolvedPath of relativeImports) {\n try {\n const importedCode = await readFile(resolvedPath, \"utf-8\")\n\n const entry = await buildAngularSourceEntry({\n code: importedCode,\n fileName: basename(resolvedPath),\n filePath: resolvedPath,\n language: \"angular-ts\",\n })\n\n entries.push(entry)\n } catch (error) {\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} ${chalk.yellowBright(\"Failed to process relative import:\")} ${chalk.cyan(resolvedPath)}`,\n )\n }\n }\n\n return entries\n }\n\n function generateRegistryModule(): string {\n const demos = Array.from(demoRegistry.values())\n\n return `// Auto-generated Angular demo registry\nexport const ANGULAR_DEMOS = {\n${demos\n .map(\n (demo) =>\n ` \"${demo.id}\": ${JSON.stringify(\n {\n componentClass: demo.componentClass,\n dimensions: demoDimensionsCache[demo.id],\n filePath: demo.filePath,\n hasDefaultExport: demo.hasDefaultExport,\n id: demo.id,\n imports: demo.imports,\n initialHtml: demo.initialHtml,\n isStandalone: demo.isStandalone,\n lastModified: demo.lastModified,\n selector: demo.selector,\n sourceCode: demo.sourceCode,\n },\n null,\n 4,\n )}`,\n )\n .join(\",\\n\")}\n}\n\nexport function getAngularDemoInfo(demoId) {\n return ANGULAR_DEMOS[demoId] || null\n}`\n }\n\n function isAngularDemoFile(filePath: string): boolean {\n return (\n filePath.includes(\"/demos/\") &&\n (filePath.endsWith(\".ts\") || filePath.endsWith(\"html\"))\n )\n }\n\n function isAngularDemoEntrypoint(filePath: string): boolean {\n return filePath.endsWith(\"-demo.ts\") || filePath.endsWith(\"-demo.html\")\n }\n\n function isCssAsset(filePath: string) {\n return filePath.endsWith(\".css\")\n }\n\n function isRelativeImport(source: string): boolean {\n return source.startsWith(\"./\") || source.startsWith(\"../\")\n }\n\n function isNodeBuiltin(source: string): boolean {\n const NODE_BUILTINS = [\n \"assert\",\n \"buffer\",\n \"child_process\",\n \"cluster\",\n \"crypto\",\n \"dgram\",\n \"dns\",\n \"domain\",\n \"events\",\n \"fs\",\n \"http\",\n \"https\",\n \"net\",\n \"os\",\n \"path\",\n \"punycode\",\n \"querystring\",\n \"readline\",\n \"stream\",\n \"string_decoder\",\n \"timers\",\n \"tls\",\n \"tty\",\n \"url\",\n \"util\",\n \"v8\",\n \"vm\",\n \"zlib\",\n ]\n\n return source.startsWith(\"node:\") || NODE_BUILTINS.includes(source)\n }\n\n function resolveRelativeImport(source: string, fromFile: string): string {\n const fromDir = dirname(fromFile)\n const resolved = resolve(fromDir, source)\n const extensions = [\".ts\", \".js\"]\n\n for (const ext of extensions) {\n const withExt = resolved + ext\n if (existsSync(withExt)) {\n return withExt\n }\n }\n\n for (const ext of extensions) {\n const indexFile = join(resolved, `index${ext}`)\n if (existsSync(indexFile)) {\n return indexFile\n }\n }\n\n return resolved\n }\n\n function loadTsConfigPaths(fromFile: string): PathAlias[] {\n let currentDir = dirname(fromFile)\n const pathAliases: PathAlias[] = []\n\n while (currentDir !== dirname(currentDir)) {\n const tsconfigPath = join(currentDir, \"tsconfig.json\")\n\n if (existsSync(tsconfigPath)) {\n try {\n const configContent = ts.sys.readFile(tsconfigPath)\n if (!configContent) {\n currentDir = dirname(currentDir)\n continue\n }\n\n const parseResult = ts.parseConfigFileTextToJson(\n tsconfigPath,\n configContent,\n )\n\n if (parseResult.error) {\n currentDir = dirname(currentDir)\n continue\n }\n\n const paths = parseResult.config?.compilerOptions?.paths\n const baseUrl = parseResult.config?.compilerOptions?.baseUrl || \"./\"\n const resolvedBaseUrl = resolve(currentDir, baseUrl)\n\n if (paths) {\n for (const [alias, targets] of Object.entries(paths)) {\n if (Array.isArray(targets) && targets.length > 0) {\n const target = targets[0]\n\n const pattern = new RegExp(\n `^${alias\n .replace(\"*\", \"(.*)\")\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(\"\\\\(\\\\*\\\\)\", \"(.*)\")}$`,\n )\n\n const replacement = resolve(\n resolvedBaseUrl,\n target.replace(\"*\", \"$1\"),\n )\n\n pathAliases.push({pattern, replacement})\n }\n }\n }\n\n const extendsPath = parseResult.config?.extends\n if (extendsPath) {\n const resolvedExtends = resolve(currentDir, extendsPath)\n const extendedAliases = loadTsConfigPathsFromFile(resolvedExtends)\n pathAliases.push(...extendedAliases)\n }\n\n return pathAliases\n } catch (error) {\n currentDir = dirname(currentDir)\n continue\n }\n }\n\n currentDir = dirname(currentDir)\n }\n\n return pathAliases\n }\n\n function setupAngularWatcher() {\n watcher = watch(routesDir, {\n ignoreInitial: true,\n persistent: true,\n })\n\n watcher.on(\"ready\", () => {\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} Registered ${chalk.green(demoRegistry.size)} demo files. Watching for file changes...`,\n )\n })\n\n watcher.on(\"add\", (filePath: string) => {\n try {\n const fileStats = statSync(filePath)\n if (!fileStats || fileStats.size === 0) {\n console.debug(\"Failed to read file stats\", filePath)\n return\n }\n\n if (isAngularDemoFile(filePath)) {\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} New Angular demo: ${chalk.green(filePath)}`,\n )\n void handleAngularDemoUpdate(filePath).then(() => {\n triggerRegistryUpdate()\n })\n }\n } catch {\n console.debug(\"Failed to update registry file stats\")\n }\n })\n\n watcher.on(\"unlink\", (filePath: string) => {\n if (isAngularDemoFile(filePath)) {\n const demoEntry = Array.from(demoRegistry.entries()).find(\n ([, info]) => info.filePath === filePath,\n )\n\n if (demoEntry) {\n const [demoId] = demoEntry\n demoRegistry.delete(demoId)\n\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} Removed demo: ${chalk.red(demoId)}`,\n )\n\n triggerRegistryUpdate()\n }\n }\n })\n }\n\n async function handleAngularDemoUpdate(filePath: string) {\n const code = await readFile(filePath, \"utf-8\")\n const demoInfo = await parseAngularDemo(filePath, code)\n\n if (demoInfo) {\n demoRegistry.set(demoInfo.id, demoInfo)\n }\n }\n\n function triggerRegistryUpdate() {\n if (!devServer) {\n return\n }\n\n const mainModule = devServer.moduleGraph.getModuleById(VIRTUAL_MODULE_ID)\n if (mainModule) {\n devServer.moduleGraph.invalidateModule(mainModule)\n mainModule.lastHMRTimestamp = Date.now()\n devServer.reloadModule(mainModule)\n }\n }\n}\n\nfunction loadTsConfigPathsFromFile(tsconfigPath: string): PathAlias[] {\n const pathAliases: PathAlias[] = []\n const configDir = dirname(tsconfigPath)\n\n try {\n const configContent = ts.sys.readFile(tsconfigPath)\n if (!configContent) {\n return pathAliases\n }\n\n const parseResult = ts.parseConfigFileTextToJson(\n tsconfigPath,\n configContent,\n )\n\n if (parseResult.error) {\n return pathAliases\n }\n\n const paths = parseResult.config?.compilerOptions?.paths\n const baseUrl = parseResult.config?.compilerOptions?.baseUrl || \"./\"\n const resolvedBaseUrl = resolve(configDir, baseUrl)\n\n if (paths) {\n for (const [alias, targets] of Object.entries(paths)) {\n if (Array.isArray(targets) && targets.length > 0) {\n const target = targets[0]\n\n const pattern = new RegExp(\n `^${alias\n .replace(\"*\", \"(.*)\")\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(\"\\\\(\\\\*\\\\)\", \"(.*)\")}$`,\n )\n\n const replacement = resolve(\n resolvedBaseUrl,\n target.replace(\"*\", \"$1\"),\n )\n\n pathAliases.push({pattern, replacement})\n }\n }\n }\n\n const extendsPath = parseResult.config?.extends\n if (extendsPath) {\n let resolvedExtends = resolve(configDir, extendsPath)\n\n if (!resolvedExtends.endsWith(\".json\")) {\n resolvedExtends += \".json\"\n }\n\n if (existsSync(resolvedExtends)) {\n const extendedAliases = loadTsConfigPathsFromFile(resolvedExtends)\n pathAliases.push(...extendedAliases)\n }\n }\n } catch {\n return pathAliases\n }\n\n return pathAliases\n}\n\nfunction isPathAliasImport(source: string, pathAliases: PathAlias[]): boolean {\n return pathAliases.some((alias) => alias.pattern.test(source))\n}\n\nfunction resolvePathAlias(\n source: string,\n pathAliases: PathAlias[],\n): string | null {\n for (const alias of pathAliases) {\n if (alias.pattern.test(source)) {\n const resolvedPath = source.replace(alias.pattern, alias.replacement)\n const extensions = [\".ts\", \".js\"]\n\n for (const ext of extensions) {\n const withExt = resolvedPath + ext\n if (existsSync(withExt)) {\n return withExt\n }\n }\n\n for (const ext of extensions) {\n const indexFile = join(resolvedPath, `index${ext}`)\n if (existsSync(indexFile)) {\n return indexFile\n }\n }\n\n return resolvedPath\n }\n }\n\n return null\n}\n\nfunction resolveTemplateFile(templateUrl: string, fromFile: string): string {\n const fromDir = dirname(fromFile)\n const resolved = resolve(fromDir, templateUrl)\n\n if (existsSync(resolved)) {\n return resolved\n }\n\n if (!resolved.endsWith(\".html\")) {\n const withHtml = `${resolved}.html`\n if (existsSync(withHtml)) {\n return withHtml\n }\n }\n\n return resolved\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {type Config, type CosmiconfigResult, cosmiconfigSync} from \"cosmiconfig\"\n\nimport {removeTrailingSlash} from \"../path-utils\"\n\nimport {configSchema} from \"./config-schema\"\nimport type {ResolvedQuiDocsConfig} from \"./types\"\n\ninterface LoadedCosmicConfig {\n config: Config\n filepath: string\n isEmpty?: boolean\n}\n\nexport interface ConfigLoaderOptions {\n /**\n * Path to the qui-docs config file. This is automatically detected if omitted.\n */\n configFile?: string\n}\n\nexport class ConfigLoader {\n private readonly options: ConfigLoaderOptions\n\n constructor(options: ConfigLoaderOptions) {\n this.options = options\n return this\n }\n\n private getCosmiconfig(): LoadedCosmicConfig {\n const explorer = cosmiconfigSync(\"qui-docs\")\n\n const result: CosmiconfigResult | null = this.options.configFile\n ? explorer.load(this.options.configFile)\n : explorer.search()\n\n if (!result) {\n throw new Error(\n \"Config file not found. Please consult the docs at https://docs.qui.qualcomm.com/guide/page-setup#config\",\n )\n }\n\n return result\n }\n\n private resolveConfigFromCosmiconfig(\n config: CosmiconfigResult,\n ): ResolvedQuiDocsConfig {\n const parsed = configSchema.safeParse(config!.config)\n if (!parsed.success) {\n console.dir(parsed.error.issues, {depth: 10})\n throw new Error(\"Failed to parse config file.\")\n }\n const conf = parsed.data\n return {\n ...conf,\n appDirectory: conf.appDirectory || \"app\",\n filePath: config!.filepath,\n pageDirectory: conf.pageDirectory\n ? removeTrailingSlash(conf.pageDirectory)\n : \"routes\",\n }\n }\n\n loadConfig(): ResolvedQuiDocsConfig {\n const config = this.getCosmiconfig()\n return this.resolveConfigFromCosmiconfig(config)\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\n/**\n * Winblows fix\n */\nexport function fixPath(str: string): string {\n return str.replaceAll(\"\\\\\", \"/\")\n}\n\n/**\n * Removes the trailing slash from a string.\n */\nexport function removeTrailingSlash(str: string): string {\n return str.endsWith(\"/\") ? str.substring(0, str.length - 1) : str\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {z, type ZodObject, type ZodSchema} from \"zod\"\n\nimport type {NavMeta, RouteMeta} from \"../nav-builder/types\"\n\nimport type {\n KnowledgeConfig,\n KnowledgeExtraFile,\n OpenWebUiIntegration,\n PagesExportConfig,\n QuiDocsConfig,\n QuiDocsTypeDocOptions,\n SectionExportConfig,\n} from \"./types\"\nimport {implement} from \"./zod\"\n\nexport const navMetaSchema: ZodObject<{}> = implement<NavMeta>().with({\n id: z.never().optional(),\n sectionTitle: z.string().optional(),\n separator: z.boolean().optional(),\n})\n\nexport const routeMetaSchema: ZodSchema<RouteMeta> =\n implement<RouteMeta>().with({\n children: z.array(z.lazy(() => routeMetaSchema)).optional(),\n expanded: z.boolean().optional(),\n group: z.string().optional(),\n groupOrder: z.string().array().optional(),\n hidden: z.boolean().optional(),\n hideBreadcrumbs: z.boolean().optional(),\n hideFromSearch: z.boolean().optional(),\n hidePageLinks: z.boolean().optional(),\n hideSideNav: z.boolean().optional(),\n hideToc: z.boolean().optional(),\n id: z.string(),\n ignoreRouteMetaOrder: z.boolean().optional(),\n restricted: z.boolean().optional(),\n sectionTitle: z.never().optional(),\n separator: z.never().optional(),\n sideNavTitle: z.string().optional(),\n title: z.string().optional(),\n })\n\nconst typeDocPropsSchema = implement<QuiDocsTypeDocOptions>().with({\n includeInSearchIndex: z.boolean().optional(),\n})\n\nconst knowledgeExtraFileSchema = implement<KnowledgeExtraFile>().with({\n contents: z.string(),\n id: z.string(),\n processAsMdx: z.boolean().optional(),\n title: z.string().optional(),\n})\n\nconst frontmatterConfigSchema = z\n .object({\n exclude: z.array(z.string()).optional(),\n include: z.array(z.string()).optional(),\n })\n .optional()\n\nconst pagesExportsSchema = implement<PagesExportConfig>().with({\n outputPath: z.string().optional(),\n})\n\nconst sectionsExportsSchema = implement<SectionExportConfig>().with({\n depths: z.array(z.number()).optional(),\n minContentLength: z.number().optional(),\n outputPath: z.string().optional(),\n})\n\nconst openWebUiIntegrationSchema = implement<OpenWebUiIntegration>().with({\n envFile: z.string().optional(),\n id: z.string(),\n})\n\nconst knowledgeConfigSchema = implement<KnowledgeConfig>().with({\n baseUrl: z.string().optional(),\n exclude: z.array(z.string()).optional(),\n extraFiles: z.array(knowledgeExtraFileSchema).optional(),\n frontmatter: frontmatterConfigSchema,\n integrations: z\n .object({\n openWebUi: z.array(openWebUiIntegrationSchema).optional(),\n })\n .optional(),\n outputPath: z.string().optional(),\n pageIdPrefix: z.string().optional(),\n pages: pagesExportsSchema.optional(),\n sections: sectionsExportsSchema.optional(),\n})\n\nexport const configSchema = implement<QuiDocsConfig>().with({\n appDirectory: z.string().optional(),\n disableCache: z.boolean().optional(),\n headings: z\n .array(\n z.union([\n z.literal(\"h1\"),\n z.literal(\"h2\"),\n z.literal(\"h3\"),\n z.literal(\"h4\"),\n z.literal(\"h5\"),\n z.literal(\"h6\"),\n ]),\n )\n .optional(),\n hotUpdateIgnore: z.instanceof(RegExp).optional(),\n knowledge: knowledgeConfigSchema.optional(),\n navConfig: z.array(z.union([routeMetaSchema, navMetaSchema])).optional(),\n pageDirectory: z.string().optional(),\n pageTimestampMetadata: z\n .union([\n z.literal(\"off\"),\n z.literal(\"timestamp\"),\n z.literal(\"user-and-timestamp\"),\n ])\n .optional(),\n routingStrategy: z.union([z.literal(\"vite-generouted\"), z.any()]).optional(),\n throwOnError: z.boolean().optional(),\n typeDocProps: z.string().optional(),\n typeDocPropsOptions: typeDocPropsSchema.optional(),\n})\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {z} from \"zod\"\n\ntype Implements<Model> = {\n [key in keyof Model]-?: undefined extends Model[key]\n ? null extends Model[key]\n ? z.ZodNullable<z.ZodOptional<z.ZodType<Model[key]>>>\n : z.ZodOptional<z.ZodType<Model[key]>>\n : null extends Model[key]\n ? z.ZodNullable<z.ZodType<Model[key]>>\n : z.ZodType<Model[key]> | z.ZodDefault<z.ZodType<Model[key]>>\n}\n\nexport function implement<Model = never>() {\n return {\n with: <\n Schema extends Implements<Model> & {\n [unknownKey in Exclude<keyof Schema, keyof Model>]: never\n },\n >(\n schema: Schema,\n ) => z.object(schema),\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {join} from \"node:path\"\nimport type {PluginOption, ResolvedConfig} from \"vite\"\n\nimport {dedent} from \"@qualcomm-ui/utils/dedent\"\n\nimport {ConfigLoader} from \"./config/config-loader\"\nimport {fixPath} from \"./path-utils\"\nimport {\n CONFIG_VIRTUAL_MODULE_ID,\n EXPORTS_VIRTUAL_MODULE_ID,\n PLUGIN_VIRTUAL_MODULE_ID,\n PluginState,\n} from \"./plugin-state\"\n\nconst isDev = process.env.NODE_ENV === \"development\"\n\nexport interface QuiDocsPluginOptions {\n /**\n * Path to the qui-docs config file. This is automatically detected if omitted.\n */\n configFile?: string\n\n /**\n * The current working directory.\n *\n * @default process.cwd()\n */\n cwd?: string\n}\n\nconst state = new PluginState()\n\nexport function quiDocsPlugin(opts?: QuiDocsPluginOptions): PluginOption {\n state.init(fixPath(opts?.cwd ?? process.cwd()))\n\n // https://vitejs.dev/guide/api-plugin#virtual-modules-convention\n\n const configLoader = new ConfigLoader(opts || {})\n const config = configLoader.loadConfig()\n state.createIndexer(config)\n\n let viteConfig: ResolvedConfig\n\n function getPublicDir() {\n return viteConfig.publicDir || join(state.getCwd(), \"public\")\n }\n\n return {\n apply(config, env) {\n return (\n (env.mode === \"development\" && env.command === \"serve\") ||\n (env.mode === \"production\" && env.command === \"build\")\n )\n },\n buildStart: async () => {\n state.buildIndex(state.buildCount > 0)\n state.buildCount++\n\n if (!isDev && state.knowledgeConfig) {\n await state.generateKnowledge(getPublicDir())\n }\n },\n configResolved(resolved) {\n viteConfig = resolved\n },\n configureServer: async (server) => {\n if (!isDev) {\n return\n }\n state.initWatchers(opts?.configFile)\n\n if (state.knowledgeConfig) {\n await state.generateKnowledge(getPublicDir())\n }\n\n server.middlewares.use(\"/__qui-docs/pages\", (_req, res) => {\n res.setHeader(\"Content-Type\", \"application/json\")\n res.end(JSON.stringify(state.pages))\n })\n\n server.middlewares.use(\"/__qui-docs/sections\", (_req, res) => {\n res.setHeader(\"Content-Type\", \"application/json\")\n res.end(JSON.stringify(state.sections))\n })\n\n server.watcher.on(\"add\", (path: string) => {\n if (path.endsWith(\".mdx\")) {\n state.handleChange({\n onComplete: () => {\n server.ws.send({type: \"full-reload\"})\n state.debouncedGenerateKnowledge(getPublicDir())\n },\n })\n }\n })\n server.watcher.on(\"unlink\", (path: string) => {\n if (path.endsWith(\".mdx\")) {\n state.handleChange({\n onComplete: () => {\n server.ws.send({type: \"full-reload\"})\n state.debouncedGenerateKnowledge(getPublicDir())\n },\n })\n }\n })\n state.servers.push(server)\n },\n handleHotUpdate: ({file: updateFile, modules, server}) => {\n if (updateFile.endsWith(\".css\")) {\n return modules\n }\n const file = fixPath(updateFile)\n if (\n (!config.hotUpdateIgnore || !config.hotUpdateIgnore.test(file)) &&\n file !== state.configFilePath\n ) {\n if (\n state.docPropsDirectory &&\n file.startsWith(state.docPropsFilePath)\n ) {\n return []\n }\n\n if (updateFile.endsWith(\".mdx\")) {\n state.debouncedGenerateKnowledge(getPublicDir())\n const files = state.buildIndex(true)\n\n const moduleByFile = server.moduleGraph.getModulesByFile(updateFile)\n if (!moduleByFile?.size) {\n console.debug(\"no module found for file, returning\", updateFile)\n return []\n }\n\n const virtualModule = server.moduleGraph.getModuleById(\n PLUGIN_VIRTUAL_MODULE_ID,\n )\n if (virtualModule) {\n server.moduleGraph.invalidateModule(virtualModule)\n\n server.ws.send({\n data: state.siteData,\n event: \"qui-docs-plugin:refresh-site-data\",\n type: \"custom\",\n })\n }\n if (files.some((file) => file.metadata.changed.frontmatter)) {\n console.debug(\n \"Frontmatter changed, reloading plugin to reflect changes in the page configuration\",\n )\n if (virtualModule) {\n server.moduleGraph.invalidateModule(virtualModule)\n }\n server.ws.send({type: \"full-reload\"})\n return []\n }\n return virtualModule ? [virtualModule] : []\n }\n }\n return []\n },\n load: (id): string | undefined => {\n if (id === PLUGIN_VIRTUAL_MODULE_ID) {\n return `export const siteData = ${JSON.stringify(state.siteData)}`\n }\n if (id === CONFIG_VIRTUAL_MODULE_ID) {\n return `export const quiDocsConfig = ${JSON.stringify({...state.config, cwd: state.cwd, publicDir: viteConfig.publicDir})}`\n }\n if (id === EXPORTS_VIRTUAL_MODULE_ID) {\n if (isDev) {\n // serve the sections/pages as middleware for faster updates in dev mode.\n // This prevents the vite dev server from slowing down from frequent,\n // large module invalidations.\n const {host = \"localhost\", port = 5173} = viteConfig.server\n const hostname = host === true ? \"localhost\" : host || \"localhost\"\n const base = `${viteConfig.server.https ? \"https\" : \"http\"}://${hostname}:${port}`\n return dedent`\n export const getSections = () => fetch('${base}/__qui-docs/sections').then(r => r.json())\n export const getPages = () => fetch('${base}/__qui-docs/pages').then(r => r.json())\n `\n }\n return dedent`\n export const getSections = () => Promise.resolve(${JSON.stringify(state.sections)})\n export const getPages = () => Promise.resolve(${JSON.stringify(state.pages)})\n `\n }\n return undefined\n },\n name: \"qui-mdx-vite-plugin\",\n resolveId: (id) => {\n if (id === PLUGIN_VIRTUAL_MODULE_ID.substring(1)) {\n return PLUGIN_VIRTUAL_MODULE_ID\n }\n if (id === CONFIG_VIRTUAL_MODULE_ID.substring(1)) {\n return CONFIG_VIRTUAL_MODULE_ID\n }\n if (id === EXPORTS_VIRTUAL_MODULE_ID.substring(1)) {\n return EXPORTS_VIRTUAL_MODULE_ID\n }\n return undefined\n },\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport chalk from \"chalk\"\nimport chokidar from \"chokidar\"\nimport {glob} from \"glob\"\nimport {readFileSync} from \"node:fs\"\nimport {mkdir, writeFile} from \"node:fs/promises\"\nimport {join, resolve} from \"node:path\"\nimport prettyMilliseconds from \"pretty-ms\"\nimport type {ViteDevServer} from \"vite\"\n\nimport type {\n KnowledgePages,\n KnowledgeSections,\n PageDocProps,\n SiteData,\n} from \"@qualcomm-ui/mdx-common\"\nimport type {QuiPropTypes} from \"@qualcomm-ui/typedoc-common\"\n\nimport type {ResolvedQuiDocsConfig} from \"./config\"\nimport {ConfigLoader} from \"./config/config-loader\"\nimport {type CompiledMdxFile, MdxFileReader} from \"./markdown\"\nimport {KnowledgeExporter} from \"./markdown/knowledge\"\nimport type {KnowledgePageCache} from \"./markdown/knowledge/types\"\nimport {fixPath} from \"./path-utils\"\nimport {SearchIndexer} from \"./search-indexer\"\n\nconst isDev = process.env.NODE_ENV === \"development\"\n\n// TODO: deprecate and rename to @qualcomm-ui/docs-plugin/site-data\nexport const PLUGIN_VIRTUAL_MODULE_ID = \"\\0@qualcomm-ui/mdx-vite-plugin\"\nexport const CONFIG_VIRTUAL_MODULE_ID = \"\\0@qualcomm-ui/docs-plugin/config\"\nexport const EXPORTS_VIRTUAL_MODULE_ID =\n \"\\0@qualcomm-ui/docs-plugin/markdown-content\"\n\nexport interface ChangeOptions {\n onComplete?: () => void\n}\n\nexport interface ExportsState {\n dir: string\n enabled: boolean\n pathnames: string[]\n}\n\n/**\n * TODO: adjust when https://github.com/vitejs/vite/discussions/16358 lands.\n */\nexport class PluginState {\n buildCount: number = 0\n config: ResolvedQuiDocsConfig | null = null\n configFilePath: string = \"\"\n docPropsFilePath: string = \"\"\n exports: ExportsState = {dir: \"\", enabled: false, pathnames: []}\n indexer!: SearchIndexer\n configLoader: ConfigLoader | null = null\n knowledgeConfig: ResolvedQuiDocsConfig[\"knowledge\"] = undefined\n private knowledgePageCache: KnowledgePageCache = new Map()\n pages: KnowledgePages | null = null\n sections: KnowledgeSections | null = null\n routesDir!: string\n servers: ViteDevServer[] = []\n timeout: ReturnType<typeof setTimeout> | undefined = undefined\n exportsTimeout: ReturnType<typeof setTimeout> | undefined = undefined\n watching = false\n\n cwd!: string\n\n init(cwd: string) {\n this.cwd = cwd\n }\n\n getCwd() {\n return this.cwd\n }\n\n get docPropsDirectory() {\n if (!this.docPropsFilePath) {\n return \"\"\n }\n return this.docPropsFilePath.substring(\n 0,\n this.docPropsFilePath.lastIndexOf(\"/\"),\n )\n }\n\n get siteData(): SiteData & {\n config: Omit<ResolvedQuiDocsConfig, \"filePath\">\n exports: ExportsState\n } {\n const {filePath: _filePath, ...config} =\n this.config ?? ({} as ResolvedQuiDocsConfig)\n return {\n config,\n exports: this.exports,\n navItems: this.indexer.navItems,\n pageDocProps: this.indexer.pageDocProps as unknown as PageDocProps,\n pageMap: this.indexer.pageMap,\n searchIndex: this.indexer.searchIndex,\n }\n }\n\n private resolveDocProps(): Record<string, QuiPropTypes> {\n if (!this.docPropsFilePath) {\n return {}\n }\n try {\n return JSON.parse(readFileSync(this.docPropsFilePath, \"utf-8\"))?.props\n } catch (e) {\n console.debug(\n \"Invalid doc props file. Unable to parse JSON. Please check the file\",\n )\n return {}\n }\n }\n\n createIndexer(config: ResolvedQuiDocsConfig) {\n this.knowledgePageCache.clear()\n this.config = config\n this.configFilePath = config.filePath\n this.docPropsFilePath = config.typeDocProps\n ? fixPath(resolve(this.cwd, config.typeDocProps))\n : \"\"\n this.routesDir = fixPath(resolve(config.appDirectory, config.pageDirectory))\n this.knowledgeConfig = config.knowledge\n this.indexer = new SearchIndexer({\n ...config,\n srcDir: fixPath(resolve(this.cwd, config.appDirectory)),\n typeDocProps: this.resolveDocProps(),\n })\n\n const knowledgeEnabled = !!config.knowledge\n const outputPath = config.knowledge?.outputPath ?? \"exports\"\n this.exports = {\n dir: knowledgeEnabled ? `/${outputPath}` : \"\",\n enabled: knowledgeEnabled,\n pathnames: [],\n }\n }\n\n buildIndex(shouldLog: boolean): CompiledMdxFile[] {\n const files = glob.sync(\n [`${this.routesDir}/**/*.mdx`, `${this.routesDir}/**/*.tsx`],\n {\n absolute: true,\n cwd: this.cwd,\n },\n )\n\n if (!files.length) {\n return []\n }\n\n const startTime = Date.now()\n\n const compiledMdxFiles = this.indexer.buildIndex(files, shouldLog)\n\n if (isDev && shouldLog) {\n console.debug(\n `${chalk.magenta.bold(`@qualcomm-ui/mdx-vite/docs-plugin:`)} Compiled search index in: ${chalk.blueBright.bold(prettyMilliseconds(Date.now() - startTime))}${this.indexer.cachedFileCount ? chalk.greenBright.bold(` (${this.indexer.cachedFileCount}/${this.indexer.mdxFileCount} files cached)`) : \"\"}`,\n )\n }\n\n return compiledMdxFiles\n }\n\n sendUpdate() {\n for (const server of this.servers) {\n const virtualModule = server.moduleGraph.getModuleById(\n PLUGIN_VIRTUAL_MODULE_ID,\n )\n if (virtualModule) {\n server.moduleGraph.invalidateModule(virtualModule)\n server.reloadModule(virtualModule)\n }\n }\n }\n\n handleChange(opts: ChangeOptions = {}) {\n clearTimeout(this.timeout)\n this.timeout = setTimeout(() => {\n this.buildIndex(true)\n this.sendUpdate()\n opts?.onComplete?.()\n }, 300)\n }\n\n initWatchers(configFile?: string) {\n if (this.watching) {\n return\n }\n this.initConfigWatcher(configFile)\n this.watching = true\n }\n\n private initConfigWatcher(configFile?: string) {\n const paths: string[] = [this.configFilePath]\n if (this.docPropsFilePath) {\n paths.push(this.docPropsFilePath)\n }\n chokidar\n .watch(paths, {\n cwd: this.cwd,\n })\n .on(\"change\", () => {\n console.debug(`qui-docs config changed, reloading plugin`)\n this.configLoader = new ConfigLoader({configFile})\n const resolvedConfig = this.configLoader.loadConfig()\n this.configFilePath = resolvedConfig.filePath\n this.createIndexer(resolvedConfig)\n this.handleChange({\n onComplete: () => {\n this.servers.forEach((server) =>\n server.ws.send({type: \"full-reload\"}),\n )\n },\n })\n })\n }\n\n async generateKnowledge(publicDir: string): Promise<void> {\n if (!this.knowledgeConfig) {\n return\n }\n\n const outputDir = join(\n publicDir,\n this.knowledgeConfig.outputPath ?? \"exports\",\n )\n const startTime = Date.now()\n\n const fileReader = new MdxFileReader(isDev)\n const exporter = new KnowledgeExporter(\n {\n baseUrl: this.knowledgeConfig.baseUrl,\n docPropsPath: this.docPropsFilePath || undefined,\n exclude: this.knowledgeConfig.exclude,\n extraFiles: this.knowledgeConfig.extraFiles,\n frontmatter: this.knowledgeConfig.frontmatter,\n pageIdPrefix: this.knowledgeConfig.pageIdPrefix,\n pages: this.knowledgeConfig.pages,\n routeDir: this.routesDir,\n sections: this.knowledgeConfig.sections,\n },\n fileReader,\n this.knowledgePageCache,\n )\n\n const result = await exporter.generate()\n this.pages = result.pages\n this.sections = result.sections\n\n await mkdir(outputDir, {recursive: true})\n await writeFile(\n join(outputDir, \"sections.json\"),\n JSON.stringify(result.sections, null, 2),\n \"utf-8\",\n )\n await writeFile(\n join(outputDir, \"pages.json\"),\n JSON.stringify(result.pages, null, 2),\n \"utf-8\",\n )\n\n this.exports.pathnames = result.pages.pages.map((p) => p.pathname)\n\n const cacheInfo =\n result.cachedPageCount > 0\n ? chalk.greenBright.bold(\n ` (${result.cachedPageCount}/${result.totalPageCount} pages cached)`,\n )\n : \"\"\n console.debug(\n `${chalk.magenta.bold(`@qualcomm-ui/mdx-vite/docs-plugin:`)} Generated knowledge exports in: ${chalk.blueBright.bold(prettyMilliseconds(Date.now() - startTime))}${cacheInfo}`,\n )\n }\n\n debouncedGenerateKnowledge(\n publicDir: string,\n opts: {onDone?: () => void} = {},\n ): void {\n if (!this.knowledgeConfig) {\n return\n }\n clearTimeout(this.exportsTimeout)\n this.exportsTimeout = setTimeout(() => {\n void this.generateKnowledge(publicDir).then(() => {\n opts.onDone?.()\n })\n }, 500)\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\n/**\n * Converts heading text to a URL-friendly slug. Handles multi-word text,\n * PascalCase identifiers, and single lowercase words. Does NOT deduplicate \u2014\n * callers manage their own counter state via {@link SlugGenerator}.\n */\nexport function slugify(text: string): string {\n const cleaned = text\n .replace(/[<>]/g, \"\")\n .replace(/[^\\w\\s-]/g, \"\")\n .trim()\n\n if (cleaned.includes(\" \")) {\n return cleaned\n .toLowerCase()\n .replace(/\\s+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n }\n\n // PascalCase \u2192 kebab-case (e.g. \"MyComponent\" \u2192 \"my-component\")\n if ((cleaned.match(/[A-Z]/g) || []).length >= 2) {\n return cleaned\n .replace(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1-$2\")\n .toLowerCase()\n }\n\n return cleaned.toLowerCase()\n}\n\n/**\n * Stateful slug generator that appends `-1`, `-2`, etc. for duplicate slugs\n * within a single page/document scope.\n */\nexport class SlugGenerator {\n private seenIds = new Map<string, number>()\n\n reset(): void {\n this.seenIds.clear()\n }\n\n createSlug(text: string): string {\n const slug = slugify(text)\n const count = this.seenIds.get(slug) || 0\n this.seenIds.set(slug, count + 1)\n return count > 0 ? `${slug}-${count}` : slug\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport chalk from \"chalk\"\nimport {execSync} from \"node:child_process\"\nimport {createHash} from \"node:crypto\"\nimport {readFileSync} from \"node:fs\"\nimport {resolve} from \"node:path\"\nimport remarkFrontmatter from \"remark-frontmatter\"\nimport remarkParse from \"remark-parse\"\nimport remarkParseFrontmatter from \"remark-parse-frontmatter\"\nimport remarkStringify from \"remark-stringify\"\nimport {unified} from \"unified\"\n\nimport type {PageFrontmatter} from \"@qualcomm-ui/mdx-common\"\nimport type {QuiPropTypes} from \"@qualcomm-ui/typedoc-common\"\n\nimport type {PageTimestampMetadataMode} from \"../config\"\n\nimport {frontmatterSchema} from \"./frontmatter-schema\"\nimport type {IndexedPage, IndexedSection} from \"./markdown.types\"\n\nexport interface GitMetadata {\n updatedBy?: string\n updatedOn?: string\n}\n\n/**\n * Runs a single git log command to collect the last commit metadata for all\n * MDX files under srcDir. Returns a map keyed by absolute file path.\n */\nexport function buildGitMetadataMap(\n srcDir: string,\n mode: PageTimestampMetadataMode,\n): Map<string, GitMetadata> {\n const map = new Map<string, GitMetadata>()\n if (mode === \"off\") {\n return map\n }\n\n try {\n const repoRoot = execSync(\"git rev-parse --show-toplevel\", {\n encoding: \"utf-8\",\n }).trim()\n\n const format = mode === \"user-and-timestamp\" ? \"%cI%x09%aN\" : \"%cI\"\n const output = execSync(\n `git log --format=\"COMMIT%x09${format}\" --name-only -- \"${srcDir}/**/*.mdx\"`,\n {encoding: \"utf-8\", stdio: [\"pipe\", \"pipe\", \"pipe\"]},\n )\n\n let currentMetadata: GitMetadata = {}\n\n for (const line of output.split(\"\\n\")) {\n if (line.startsWith(\"COMMIT\\t\")) {\n const parts = line.split(\"\\t\")\n currentMetadata =\n mode === \"user-and-timestamp\"\n ? {updatedBy: parts[2], updatedOn: parts[1]}\n : {updatedOn: parts[1]}\n } else if (line.trim()) {\n const absolutePath = resolve(repoRoot, line.trim())\n if (!map.has(absolutePath)) {\n map.set(absolutePath, currentMetadata)\n }\n }\n }\n } catch {\n // git unavailable \u2014 return empty map\n }\n\n return map\n}\n\ninterface PageCache {\n frontmatter: PageFrontmatter\n md5: string\n page: IndexedPage\n pageDocProps: Record<string, QuiPropTypes>\n pageDocPropSections: IndexedSection[]\n}\n\nexport class MdxFileReader {\n cachedFileCount = 0\n gitMetadataMap: Map<string, GitMetadata> = new Map()\n logWarnings = true\n private mdxCache: Record<string, PageCache> = {}\n\n constructor(\n public enabled: boolean,\n public pageTimestampMetadata: PageTimestampMetadataMode = \"off\",\n ) {}\n\n private hash(input: string) {\n return createHash(\"md5\").update(input).digest(\"hex\")\n }\n\n reset(): void {\n this.cachedFileCount = 0\n }\n\n readCache(filePath: string): PageCache | null {\n return this.mdxCache[filePath] || null\n }\n\n private checkCache(\n filePath: string,\n fileContents: string,\n ): Omit<PageCache, \"md5\"> | undefined {\n if (!this.enabled) {\n return\n }\n\n const fileMd5 = this.hash(fileContents)\n const cached = this.mdxCache[filePath]\n\n if (cached?.md5 !== fileMd5) {\n return\n }\n\n this.cachedFileCount++\n\n return {\n frontmatter: cached.frontmatter,\n page: cached.page,\n pageDocProps: cached.pageDocProps,\n pageDocPropSections: cached.pageDocPropSections,\n }\n }\n\n private parseFrontmatter(\n filepath: string,\n fileContents: string,\n cachedFrontmatter?: PageFrontmatter,\n ): PageFrontmatter {\n let file:\n | {data: {frontmatter: PageFrontmatter}}\n | ReturnType<typeof unified.processSync>\n if (cachedFrontmatter) {\n file = {data: {frontmatter: cachedFrontmatter}}\n } else {\n // Only parse the YAML section \u2014 we just need the frontmatter at this stage.\n const yamlSection = fileContents.substring(\n 0,\n fileContents.indexOf(\"\\n---\") + 4,\n )\n file = unified()\n .use(remarkParse)\n .use(remarkFrontmatter, [\"yaml\"])\n .use(remarkParseFrontmatter)\n .use(remarkStringify)\n .processSync(yamlSection)\n }\n\n const frontmatter: PageFrontmatter = (file.data\n .frontmatter as PageFrontmatter) ?? {title: \"\"}\n\n if (!frontmatter.title) {\n const lines = fileContents.split(\"\\n\")\n const fallbackTitle = lines.find((line) => line.startsWith(\"# \"))\n if (fallbackTitle) {\n frontmatter.title = fallbackTitle.substring(2).trim()\n }\n }\n // TODO: permit omitting title from frontmatter if provided in the navConfig\n if (!frontmatter.title && this.logWarnings) {\n console.debug(chalk.red.bold(\"Missing title:\"), filepath)\n }\n\n const parsedFrontmatter = frontmatterSchema.safeParse(frontmatter)\n\n if (!parsedFrontmatter.success) {\n console.debug(\n `${chalk.redBright.bold(\"Invalid frontmatter detected for file\")}: ${filepath}\\n`,\n )\n console.debug(chalk.redBright.bold(\"Please check the following fields:\"))\n parsedFrontmatter.error.issues.map((issue: any) => {\n console.debug(`- ${issue.path.join(\".\")}`)\n })\n }\n\n return frontmatter\n }\n\n private enrichWithGitMetadata(\n filepath: string,\n frontmatter: PageFrontmatter,\n cached: Omit<PageCache, \"md5\"> | undefined,\n ): void {\n // In dev mode, only fetch git metadata for new files (not in cache).\n // For file updates, reuse cached git metadata to avoid repeated git calls.\n // In production mode, always fetch fresh git metadata.\n const existingCache = this.mdxCache[filepath]\n const shouldFetchGitMetadata = !this.enabled || !existingCache\n\n if (shouldFetchGitMetadata) {\n const gitMetadata = this.gitMetadataMap.get(filepath) ?? {}\n if (!frontmatter.updatedOn && gitMetadata.updatedOn) {\n frontmatter.updatedOn = gitMetadata.updatedOn\n }\n if (!frontmatter.updatedBy && gitMetadata.updatedBy) {\n frontmatter.updatedBy = gitMetadata.updatedBy\n }\n } else if (!cached && existingCache) {\n if (!frontmatter.updatedOn && existingCache.frontmatter.updatedOn) {\n frontmatter.updatedOn = existingCache.frontmatter.updatedOn\n }\n if (!frontmatter.updatedBy && existingCache.frontmatter.updatedBy) {\n frontmatter.updatedBy = existingCache.frontmatter.updatedBy\n }\n }\n }\n\n /**\n * Synchronous file read with MD5 caching and git metadata enrichment.\n * Used by the search indexer on every HMR update.\n */\n readFileSync(filepath: string): {\n cached: Omit<PageCache, \"md5\"> | undefined\n fileContents: string\n frontmatter: PageFrontmatter\n } {\n const fileContents = readFileSync(filepath, \"utf-8\")\n const cached = this.checkCache(filepath, fileContents)\n const frontmatter = this.parseFrontmatter(\n filepath,\n fileContents,\n cached?.frontmatter,\n )\n this.enrichWithGitMetadata(filepath, frontmatter, cached)\n return {cached, fileContents, frontmatter}\n }\n\n updateCache(\n filepath: string,\n fileContents: string,\n cacheData: Omit<PageCache, \"md5\">,\n ): void {\n if (this.enabled) {\n this.mdxCache[filepath] = {...cacheData, md5: this.hash(fileContents)}\n }\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {z, type ZodObject} from \"zod\"\n\nimport type {PageFrontmatter} from \"@qualcomm-ui/mdx-common\"\n\nimport {implement} from \"../config/zod\"\n\n/**\n * Used to validate the MDX frontmatter and emit warnings for pages that violate the\n * schema.\n */\nexport const frontmatterSchema: ZodObject<{}> =\n implement<PageFrontmatter>().with({\n categories: z.string().array().optional(),\n description: z.string().optional(),\n group: z.string().optional(),\n hidden: z.boolean().optional(),\n hideBreadcrumbs: z.boolean().optional(),\n hideFromSearch: z.boolean().optional(),\n hidePageLinks: z.boolean().optional(),\n hideSideNav: z.boolean().optional(),\n hideToc: z.boolean().optional(),\n id: z.string().optional(),\n restricted: z.boolean().optional(),\n sideNavTitle: z.string().optional(),\n title: z.string(),\n updatedBy: z.string().optional(),\n updatedOn: z.string().optional(),\n })\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {MdxJsxAttribute} from \"mdast-util-mdx-jsx\"\n\nexport function extractNamesFromAttribute(attr: MdxJsxAttribute): string[] {\n if (!attr.value) {\n return []\n }\n\n if (typeof attr.value === \"string\") {\n return [attr.value]\n }\n\n if (attr.value.type === \"mdxJsxAttributeValueExpression\") {\n const estree = attr.value.data?.estree\n if (!estree?.body?.[0] || estree.body[0].type !== \"ExpressionStatement\") {\n return []\n }\n\n const expression = estree.body[0].expression\n\n if (expression.type === \"ArrayExpression\") {\n const names: string[] = []\n for (const element of expression.elements) {\n if (element?.type === \"Literal\" && typeof element.value === \"string\") {\n names.push(element.value)\n }\n }\n return names\n }\n\n // Handle single string expression\n if (expression.type === \"Literal\" && typeof expression.value === \"string\") {\n return [expression.value]\n }\n }\n\n return []\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport remarkFrontmatter from \"remark-frontmatter\"\nimport remarkGfm from \"remark-gfm\"\nimport remarkMdx from \"remark-mdx\"\nimport remarkParse from \"remark-parse\"\nimport remarkStringify from \"remark-stringify\"\nimport {type PluggableList, unified} from \"unified\"\n\nimport type {PageFrontmatter} from \"@qualcomm-ui/mdx-common\"\n\nimport {\n remarkAlerts,\n remarkExtractMeta,\n remarkFrontmatterInterpolation,\n remarkRemoveJsx,\n remarkRemoveMermaidCodeBlocks,\n} from \"../remark\"\n\nexport interface RemarkPipelineOptions {\n /** GitHub-style alert blocks. */\n alerts?: boolean\n /**\n * Strip :::meta::: and :::terms::: blocks, storing extracted data in the provided\n * object.\n */\n extractMeta?: Record<string, string | string[]>\n /** Include remarkFrontmatter for YAML front matter. */\n frontmatter?: boolean\n /** Include remarkGfm for GitHub Flavored Markdown. */\n gfm?: boolean\n /** Interpolate {frontmatter.*} expressions in the content. */\n interpolateFrontmatter?: PageFrontmatter\n /** Include remarkMdx for MDX parsing. */\n mdx?: boolean\n /**\n * \"md\" appends remarkStringify; \"none\" (default) leaves serialization to the\n * caller.\n */\n output?: \"md\" | \"none\"\n /** Additional remark plugins appended after built-in transforms. */\n plugins?: PluggableList\n /** Strip JSX/MDX elements from the AST. */\n removeJsx?: boolean\n /** Remove mermaid code blocks. */\n removeMermaidCodeBlocks?: boolean\n}\n\n/**\n * Creates a configured unified remark processor. The caller can further extend\n * the returned processor with `.use()` (e.g. to add remarkRehype for HTML output).\n */\nexport function createRemarkProcessor(options: RemarkPipelineOptions = {}) {\n const processor = unified().use(remarkParse)\n\n if (options.mdx) {\n processor.use(remarkMdx)\n }\n if (options.frontmatter) {\n processor.use(remarkFrontmatter, [\"yaml\"])\n }\n\n // Transform plugins \u2014 order matters\n if (options.removeJsx) {\n processor.use(remarkRemoveJsx)\n }\n if (options.removeMermaidCodeBlocks) {\n processor.use(remarkRemoveMermaidCodeBlocks)\n }\n if (options.gfm) {\n processor.use(remarkGfm)\n }\n if (options.alerts) {\n processor.use(remarkAlerts)\n }\n if (options.interpolateFrontmatter) {\n processor.use(\n remarkFrontmatterInterpolation,\n options.interpolateFrontmatter,\n )\n }\n if (options.extractMeta) {\n processor.use(remarkExtractMeta, options.extractMeta)\n }\n\n if (options.plugins) {\n for (const plugin of options.plugins) {\n if (Array.isArray(plugin)) {\n processor.use(...plugin)\n } else {\n // @ts-expect-error mdast types\n processor.use(plugin)\n }\n }\n }\n\n if (options.output === \"md\") {\n processor.use(remarkStringify)\n }\n\n return processor\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {PhrasingContent, Root} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nconst alertLegacyRegex = /^\\[!(NOTE|TIP|SUCCESS|WARNING|CAUTION)(\\/.*)?\\]/i\n\n/**\n * Alerts are a Markdown extension based on the blockquote syntax that you can use\n * to emphasize critical information. On GitHub, they are displayed with distinctive\n * colors and icons to indicate the significance of the content.\n * https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#alerts\n */\nexport const remarkAlerts: Plugin<[], Root> = () => {\n return (tree) => {\n visit(tree, \"blockquote\", (node) => {\n let alertType = \"\"\n let title = \"\"\n let isNext = true\n const child = node.children.map((item) => {\n if (isNext && item.type === \"paragraph\") {\n const firstNode = item.children[0]\n const text = firstNode.type === \"text\" ? firstNode.value : \"\"\n const reg = alertLegacyRegex\n const match = text.match(reg)\n if (match) {\n isNext = false\n alertType = match[1].toLocaleLowerCase()\n title = match[2] || alertType.toLocaleUpperCase()\n if (text.includes(\"\\n\")) {\n item.children[0] = {\n type: \"text\",\n value: text.replace(reg, \"\").replace(/^\\n+/, \"\"),\n }\n }\n\n if (!text.includes(\"\\n\")) {\n const itemChild: PhrasingContent[] = []\n item.children.forEach((item: any, idx: number) => {\n if (idx === 0) {\n return\n }\n if (idx === 1 && item.type === \"break\") {\n return\n }\n itemChild.push(item)\n })\n item.children = [...itemChild]\n }\n }\n }\n return item\n })\n\n title = title.replace(/^\\//, \"\")\n\n if (!!alertType) {\n node.data = {\n hName: \"div\",\n hProperties: {\n class: `qui-notification__root`,\n \"data-emphasis\":\n alertToEmphasis[alertType as IconType] || \"neutral\",\n \"data-orientation\": \"vertical\",\n dir: \"auto\",\n },\n }\n node.children = [\n {\n children: [getAlertIcon(alertType as IconType)],\n data: {\n hProperties: {\n class: \"qui-notification__icon\",\n \"data-part\": \"status-icon\",\n \"data-scope\": \"inline-notification\",\n },\n },\n type: \"paragraph\",\n },\n {\n children: [\n {\n type: \"text\",\n value: title,\n },\n ],\n data: {\n hProperties: {\n class: \"qui-notification__label\",\n dir: \"auto\",\n },\n },\n type: \"paragraph\",\n },\n {\n children: child,\n data: {\n hName: \"div\",\n hProperties: {\n class: `qui-notification__description`,\n dir: \"auto\",\n },\n },\n type: \"blockquote\",\n },\n ]\n }\n })\n }\n}\n\nexport function getAlertIcon(type: IconType): PhrasingContent {\n const svgChildren = svgData[type] ?? []\n return {\n children: svgChildren,\n data: {\n hName: \"svg\",\n hProperties: {\n ariaHidden: \"true\",\n class: \"lucide\",\n fill: \"transparent\",\n height: \"20\",\n stroke: \"currentColor\",\n strokeLinecap: \"round\",\n strokeLinejoin: \"round\",\n strokeWidth: \"2\",\n viewBox: \"0 0 24 24\",\n width: \"20\",\n },\n },\n type: \"emphasis\",\n }\n}\n\ntype IconType = \"note\" | \"tip\" | \"success\" | \"warning\" | \"caution\"\n\n/**\n * These SVG children correspond to the lucide icons matching our\n * {@link https://react.qui.qualcomm.com/components/inline-alert | Alert} component.\n */\nconst svgData: Record<IconType, PhrasingContent[]> = {\n caution: [\n {\n children: [],\n data: {\n hName: \"polygon\",\n hProperties: {\n points:\n \"7.86 2 16.14 2 22 7.86 22 16.14 16.14 22 7.86 22 2 16.14 2 7.86 7.86 2\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"line\",\n hProperties: {\n x1: \"12\",\n x2: \"12\",\n y1: \"8\",\n y2: \"12\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"line\",\n hProperties: {\n x1: \"12\",\n x2: \"12.01\",\n y1: \"16\",\n y2: \"16\",\n },\n },\n type: \"emphasis\",\n },\n ],\n note: [\n {\n children: [],\n data: {\n hName: \"circle\",\n hProperties: {\n cx: \"12\",\n cy: \"12\",\n r: \"10\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M12 16v-4\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M12 8h.01\",\n },\n },\n type: \"emphasis\",\n },\n ],\n success: [\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M20 6 9 17l-5-5\",\n },\n },\n type: \"emphasis\",\n },\n ],\n tip: [\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M9 18h6\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M10 22h4\",\n },\n },\n type: \"emphasis\",\n },\n ],\n warning: [\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M12 9v4\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M12 17h.01\",\n },\n },\n type: \"emphasis\",\n },\n ],\n}\n\nconst alertToEmphasis: Record<IconType, string> = {\n caution: \"danger\",\n note: \"neutral\",\n success: \"success\",\n tip: \"info\",\n warning: \"warning\",\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Code, Parent, Root} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\ninterface Tab {\n index: number\n label: string\n meta: string | undefined\n tabsGroup: string\n}\n\nfunction parseTabAttributes(meta: string): {\n label: string | null\n remainingMeta: string\n tabsGroup: string | null\n} {\n if (!meta) {\n return {label: null, remainingMeta: \"\", tabsGroup: null}\n }\n\n const tabsMatch = meta.match(/tabs=[\"']([^\"']+)[\"']|tabs=(\\S+)/)\n const labelMatch = meta.match(/label=[\"']([^\"']+)[\"']|label=(\\S+)/)\n\n const tabsGroup = tabsMatch ? tabsMatch[1] || tabsMatch[2] : null\n const label = labelMatch ? labelMatch[1] || labelMatch[2] : null\n\n // Remove both tabs and label attributes from meta\n const remainingMeta = meta\n .replace(/\\s*tabs=[\"']([^\"']+)[\"']/g, \"\")\n .replace(/\\s*tabs=(\\S+)/g, \"\")\n .replace(/\\s*label=[\"']([^\"']+)[\"']/g, \"\")\n .replace(/\\s*label=(\\S+)/g, \"\")\n .trim()\n\n return {label, remainingMeta, tabsGroup}\n}\n\nfunction findConsecutiveTabs(\n startIndex: number,\n parent: Parent,\n targetTabsGroup: string,\n): Tab[] {\n const tabs: Tab[] = []\n let currentIndex = startIndex\n\n while (currentIndex < parent.children.length) {\n const currentNode = parent.children[currentIndex]\n\n if (!currentNode || currentNode.type !== \"code\") {\n break\n }\n\n const codeNode = currentNode\n\n if (!codeNode.meta) {\n break\n }\n\n const {label, remainingMeta, tabsGroup} = parseTabAttributes(codeNode.meta)\n\n // Only include if it matches the target tabs group and has a label\n if (!tabsGroup || !label || tabsGroup !== targetTabsGroup) {\n break\n }\n\n // Clean the original node's meta NOW\n codeNode.meta = remainingMeta || undefined\n\n tabs.push({\n index: currentIndex,\n label,\n meta: remainingMeta || undefined,\n tabsGroup,\n })\n\n if (remainingMeta && remainingMeta.includes(\"end\")) {\n break\n }\n\n currentIndex++\n }\n\n return tabs\n}\n\nfunction renderTabs(tabs: Tab[], parent: Parent): any[] {\n const tabsContainer = {\n attributes: [],\n children: [] as any[],\n name: \"CodeTabs\",\n type: \"mdxJsxFlowElement\",\n }\n\n tabs.forEach((tab) => {\n const codeNode = parent.children[tab.index] as Code\n\n const tabAttributes = [\n {\n name: \"label\",\n type: \"mdxJsxAttribute\",\n value: tab.label,\n },\n ]\n\n // Add meta to JSX element if it exists\n if (tab.meta) {\n tabAttributes.push({\n name: \"meta\",\n type: \"mdxJsxAttribute\",\n value: tab.meta,\n })\n }\n\n const tabElement = {\n attributes: tabAttributes,\n children: [\n {\n lang: codeNode.lang,\n meta: codeNode.meta, // This is now clean\n type: \"code\",\n value: codeNode.value,\n },\n ],\n name: \"CodeTab\",\n type: \"mdxJsxFlowElement\",\n }\n\n tabsContainer.children.push(tabElement)\n })\n\n return [tabsContainer]\n}\n\n/**\n * Very cool. TODO: document this https://docs.qui.qualcomm.com/guide/markdown\n *\n * @example\n * ```angular-html tabs=\"demo\" label=\"HTML\"\n * <div class=\"w-72\" q-text-input [invalid]=\"!value()\" [(ngModel)]=\"value\">\n * <label q-text-input-label>Label</label>\n * <input placeholder=\"Enter a value\" q-text-input-input />\n * <div q-text-input-error-text>You must enter a value</div>\n * </div>\n * ```\n *\n * ```angular-ts tabs=\"demo\" label=\"TS\"\n * @Component()\n * export class DemoComponent {\n * readonly value = signal(\"\")\n * }\n * ```\n */\nexport const remarkCodeTabs: Plugin<[], Root> = () => {\n return (tree) => {\n const transformations: Array<{\n endIndex: number\n parent: Parent\n replacement: any[]\n startIndex: number\n }> = []\n\n visit(\n tree,\n \"code\",\n (node: Code, index: number | undefined, parent: Parent | undefined) => {\n if (!node.meta || !parent || index === undefined) {\n return\n }\n\n const {label, tabsGroup} = parseTabAttributes(node.meta)\n if (!tabsGroup || !label) {\n return\n }\n\n const alreadyProcessed = transformations.some(\n (t) =>\n t.parent === parent && index >= t.startIndex && index < t.endIndex,\n )\n\n if (alreadyProcessed) {\n return\n }\n\n const tabs = findConsecutiveTabs(index, parent, tabsGroup)\n\n if (tabs.length > 1) {\n const startIndex = tabs[0].index\n const endIndex = tabs[tabs.length - 1].index + 1\n const newChildren = renderTabs(tabs, parent)\n\n transformations.push({\n endIndex,\n parent,\n replacement: newChildren,\n startIndex,\n })\n }\n },\n )\n\n transformations\n .sort((a, b) => b.startIndex - a.startIndex)\n .forEach((transformation) => {\n transformation.parent.children.splice(\n transformation.startIndex,\n transformation.endIndex - transformation.startIndex,\n ...transformation.replacement,\n )\n })\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Parent, Root} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {SKIP, visit} from \"unist-util-visit\"\n\nexport type MetadataValue = Record<string, string | string[]>\n\n/**\n * Parses a YAML-like value, handling arrays and strings.\n */\nfunction parseValue(value: string): string | string[] {\n const trimmed = value.trim()\n\n // Handle array syntax: [item1, item2, item3]\n if (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\")) {\n const inner = trimmed.slice(1, -1)\n return inner\n .split(\",\")\n .map((item) => item.trim())\n .filter(Boolean)\n }\n\n return trimmed\n}\n\n/**\n * Parses the content of a meta block into key-value pairs.\n */\nfunction parseMetaContent(content: string): MetadataValue {\n const result: MetadataValue = {}\n const lines = content.split(\"\\n\")\n\n for (const line of lines) {\n const trimmed = line.trim()\n if (!trimmed || trimmed === \":::\") {\n continue\n }\n\n const colonIndex = trimmed.indexOf(\":\")\n if (colonIndex === -1) {\n continue\n }\n\n const key = trimmed.slice(0, colonIndex).trim()\n const value = trimmed.slice(colonIndex + 1).trim()\n\n if (key && value) {\n result[key] = parseValue(value)\n }\n }\n\n return result\n}\n\n/**\n * Parses the content of a terms block into a terms array.\n * Terms are a flat list, one per line.\n */\nfunction parseTermsContent(content: string): string[] {\n return content\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line && line !== \":::\")\n}\n\n/**\n * Extracts metadata from MDX files and removes it from the MDX content.\n *\n * Supports two formats:\n *\n * @example `::: meta` - YAML-like key-value pairs\n * ```\n * ::: meta\n * component: NumberInput\n * :::\n *\n * result: {component: \"NumberInput\"}\n * ```\n *\n * @example `::: terms` - flat list of terms\n * ```\n * ::: terms\n * forms\n * input\n * data entry\n * :::\n *\n * result: {terms: [\"forms\", \"input\", \"data entry\"]}\n * ```\n */\nexport const remarkExtractMeta: Plugin<[MetadataValue], Root> = (\n metadata = {},\n) => {\n return (tree) => {\n const nodesToRemove: Array<{index: number; parent: Parent}> = []\n\n visit(tree, \"paragraph\", (node, index, parent) => {\n if (!parent || index === undefined) {\n return\n }\n\n const firstChild = node.children[0]\n if (firstChild?.type !== \"text\") {\n return\n }\n\n const text = firstChild.value\n const metaMatch = text.match(/^:::\\s*meta\\s*/)\n const termsMatch = text.match(/^:::\\s*terms\\s*/)\n\n if (!metaMatch && !termsMatch) {\n return\n }\n\n const openMatch = metaMatch || termsMatch\n const isTermsBlock = !!termsMatch\n\n // Check if the entire block is in this single paragraph\n // (common when markdown parser keeps it together)\n if (\n text.includes(\":::\") &&\n text.lastIndexOf(\":::\") > openMatch![0].length\n ) {\n // Extract content between opening ::: and closing :::\n const afterOpen = text.slice(openMatch![0].length)\n const closeIndex = afterOpen.lastIndexOf(\":::\")\n const content = afterOpen.slice(0, closeIndex)\n\n if (isTermsBlock) {\n const terms = parseTermsContent(content)\n if (terms.length > 0) {\n const existing = metadata.terms\n metadata.terms = Array.isArray(existing)\n ? [...existing, ...terms]\n : terms\n }\n } else {\n const parsed = parseMetaContent(content)\n Object.assign(metadata, parsed)\n }\n\n nodesToRemove.push({index, parent})\n return SKIP\n }\n\n // Multi-paragraph case: collect text from multiple nodes\n // The block might span multiple text children\n let fullText = text\n for (let i = 1; i < node.children.length; i++) {\n const child = node.children[i]\n if (child.type === \"text\") {\n fullText += child.value\n }\n }\n\n // Check for closing ::: in the combined text\n const afterOpenFull = fullText.slice(openMatch![0].length)\n const closeIndexFull = afterOpenFull.lastIndexOf(\":::\")\n\n if (closeIndexFull !== -1) {\n const content = afterOpenFull.slice(0, closeIndexFull)\n\n if (isTermsBlock) {\n const terms = parseTermsContent(content)\n if (terms.length > 0) {\n const existing = metadata.terms\n metadata.terms = Array.isArray(existing)\n ? [...existing, ...terms]\n : terms\n }\n } else {\n const parsed = parseMetaContent(content)\n Object.assign(metadata, parsed)\n }\n\n nodesToRemove.push({index, parent})\n return SKIP\n }\n })\n\n // Remove blocks from AST (in reverse order to preserve indices)\n for (let i = nodesToRemove.length - 1; i >= 0; i--) {\n const {index, parent} = nodesToRemove[i]\n parent.children.splice(index, 1)\n }\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Parent, Root} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\ninterface MdxFlowExpression {\n type: \"mdxFlowExpression\"\n value: string\n}\n\n/**\n * Wraps standalone `{frontmatter.description}` expressions in a\n * `<p class=\"mdx\">` element for styling purposes.\n */\nexport const remarkFrontmatterDescription: Plugin<[], Root> = () => {\n return (tree) => {\n visit(\n tree,\n \"mdxFlowExpression\",\n (\n node: MdxFlowExpression,\n index: number | undefined,\n parent: Parent | undefined,\n ) => {\n if (\n node.value.trim() !== \"frontmatter.description\" ||\n index === undefined ||\n !parent\n ) {\n return\n }\n\n const wrappedNode = {\n attributes: [\n {\n name: \"className\",\n type: \"mdxJsxAttribute\",\n value: \"mdx qui-docs__page-description\",\n },\n ],\n children: [node],\n name: \"p\",\n type: \"mdxJsxFlowElement\",\n }\n\n parent.children[index] = wrappedNode as any\n },\n )\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Parent, Root, Text} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nimport type {PageFrontmatter} from \"@qualcomm-ui/mdx-common\"\n\ninterface MdxExpression {\n type: \"mdxFlowExpression\" | \"mdxTextExpression\"\n value: string\n}\n\nconst FRONTMATTER_PATTERN = /^\\s*frontmatter\\.(\\w+)\\s*$/\n\nfunction isMdxExpression(node: unknown): node is MdxExpression {\n const n = node as {type?: string; value?: unknown}\n return (\n (n.type === \"mdxFlowExpression\" || n.type === \"mdxTextExpression\") &&\n typeof n.value === \"string\"\n )\n}\n\n/**\n * Replaces `{frontmatter.*}` expressions with their actual values from the\n * frontmatter object. This is safer than string replacement as it operates\n * on the AST and won't accidentally match text in code blocks or examples.\n */\nexport const remarkFrontmatterInterpolation: Plugin<[PageFrontmatter], Root> = (\n frontmatter,\n) => {\n return (tree) => {\n visit(tree, (node, index, parent) => {\n if (!isMdxExpression(node) || index === undefined || !parent) {\n return\n }\n\n const match = node.value.match(FRONTMATTER_PATTERN)\n if (!match) {\n return\n }\n\n const key = match[1] as keyof PageFrontmatter\n const value = frontmatter[key]\n\n if (typeof value === \"string\" || typeof value === \"number\") {\n const textNode: Text = {\n type: \"text\",\n value: String(value),\n }\n ;(parent as Parent).children[index] = textNode\n }\n })\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Heading, Parent, Root} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {EXIT, visit} from \"unist-util-visit\"\n\n/**\n * Replaces the first h1 heading in the document with a `PageHeader`\n * JSX element. This allows the page title to be enhanced with extra features\n * like a since tag or a copy markdown button.\n */\nexport const remarkFrontmatterTitle: Plugin<[], Root> = () => {\n return (tree) => {\n visit(\n tree,\n \"heading\",\n (node: Heading, index, parent: Parent | undefined) => {\n if (index === undefined || !parent || node.depth !== 1) {\n return\n }\n\n const wrappedNode = {\n attributes: [],\n children: node.children,\n name: \"PageHeader\",\n type: \"mdxJsxFlowElement\",\n }\n\n parent.children[index] = wrappedNode as (typeof parent.children)[number]\n\n return EXIT\n },\n )\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Plugin} from \"unified\"\nimport {remove} from \"unist-util-remove\"\n\nexport const remarkRemoveMermaidCodeBlocks: Plugin = () => {\n return (tree, _file, done) => {\n remove(tree, (node: any) => node.type === \"code\" && node.lang === \"mermaid\")\n done()\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Plugin} from \"unified\"\nimport {remove} from \"unist-util-remove\"\n\nexport const remarkRemoveJsx: Plugin = () => {\n return (tree, _file, done) => {\n remove(tree, \"mdxjsEsm\")\n remove(tree, \"mdxJsxFlowElement\")\n remove(tree, \"mdxJsxTextElement\")\n done()\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Heading, Link, Root} from \"mdast\"\nimport {toString} from \"mdast-util-to-string\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nexport interface RemarkSelfLinkOptions {\n /**\n * @default [2, 3, 4]\n */\n allowedLevels?: number[]\n prefix?: string\n}\n\nconst emptyOptions: RemarkSelfLinkOptions = {}\n\nexport function remarkSelfLinkHeadings(\n baseUrl: string = \"\",\n options?: RemarkSelfLinkOptions | null,\n): Plugin<[], Root> {\n if (!baseUrl) {\n return () => {}\n }\n return () => {\n const settings = options || emptyOptions\n const prefix = settings.prefix || \"\"\n const allowedLevels = new Set<number>(settings.allowedLevels || [2, 3, 4])\n const seenIds = new Map<string, number>()\n\n function createSlug(text: string): string {\n const cleaned = text\n .replace(/[<>]/g, \"\")\n .replace(/[^\\w\\s-]/g, \"\")\n .trim()\n\n let slug: string\n if (cleaned.includes(\" \")) {\n slug = cleaned\n .toLowerCase()\n .replace(/\\s+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n } else if ((cleaned.match(/[A-Z]/g) || []).length >= 2) {\n slug = cleaned\n .replace(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1-$2\")\n .toLowerCase()\n } else {\n slug = cleaned.toLowerCase()\n }\n\n const count = seenIds.get(slug) || 0\n seenIds.set(slug, count + 1)\n return count > 0 ? `${slug}-${count}` : slug\n }\n\n return (tree) => {\n seenIds.clear()\n visit(tree, \"heading\", (node: Heading) => {\n if (allowedLevels.has(node.depth)) {\n const text = toString(node)\n const slug = prefix + createSlug(text)\n\n const linkNode: Link = {\n children: node.children,\n type: \"link\",\n url: `${baseUrl}#${slug}`,\n }\n\n node.children = [linkNode]\n }\n })\n }\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {BlockContent, Root} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\ninterface SpoilerOptions {\n defaultSummary?: string\n detailsClassName?: string[]\n summaryClassName?: string[]\n}\n\nfunction getSpoilerStartMatch(text: string) {\n return text.match(/^:::\\s*spoiler\\s*(.*)$/)\n}\n\nfunction getSpoilerEndMatch(text: string) {\n return text.trim() === \":::\"\n}\n\nexport function isSpoilerBlock(text: string) {\n return !!getSpoilerStartMatch(text) || getSpoilerEndMatch(text)\n}\n\n/**\n * Transforms spoiler blocks into MDX components.\n *\n * @example\n * ```\n * ::: spoiler Title\n *\n * Content\n *\n * :::\n * ```\n *\n * result:\n *\n * ```jsx\n * <SpoilerRoot>\n * <SpoilerTrigger><p>Title</p></SpoilerTrigger>\n * <SpoilerContent>Content</SpoilerContent>\n * </SpoilerRoot>\n * ```\n */\nexport const remarkSpoilers: Plugin<[SpoilerOptions?], Root> = (\n options = {},\n) => {\n const {\n defaultSummary = \"Open spoiler\",\n detailsClassName = [],\n summaryClassName = [],\n } = options\n\n return (tree) => {\n visit(tree, \"paragraph\", (node, index, parent) => {\n if (!parent || index === undefined) {\n return\n }\n\n const firstChild = node.children[0]\n if (firstChild?.type !== \"text\") {\n return\n }\n\n const match = getSpoilerStartMatch(firstChild.value)\n if (!match) {\n return\n }\n\n const summary = match[1].trim() || defaultSummary\n let endIndex = index + 1\n const contentNodes: BlockContent[] = []\n\n while (endIndex < parent.children.length) {\n const child = parent.children[endIndex]\n\n if (child.type === \"paragraph\") {\n const firstText = child.children[0]\n if (\n firstText?.type === \"text\" &&\n getSpoilerEndMatch(firstText.value.trim())\n ) {\n break\n }\n }\n\n contentNodes.push(child as BlockContent)\n endIndex++\n }\n\n if (endIndex >= parent.children.length) {\n return\n }\n\n const summaryNode: BlockContent = {\n attributes: summaryClassName.length\n ? [\n {\n name: \"className\",\n type: \"mdxJsxAttribute\",\n value: summaryClassName.join(\" \"),\n },\n ]\n : [],\n children: [\n {\n children: [{type: \"text\", value: summary}],\n type: \"paragraph\",\n },\n ],\n name: \"SpoilerSummary\",\n type: \"mdxJsxFlowElement\",\n }\n\n const contentNode: BlockContent = {\n attributes: [],\n children: contentNodes,\n name: \"SpoilerContent\",\n type: \"mdxJsxFlowElement\",\n }\n\n const detailsNode: BlockContent = {\n attributes: detailsClassName.length\n ? [\n {\n name: \"className\",\n type: \"mdxJsxAttribute\",\n value: detailsClassName.join(\" \"),\n },\n ]\n : [],\n children: [summaryNode, contentNode],\n name: \"SpoilerRoot\",\n type: \"mdxJsxFlowElement\",\n }\n\n parent.children.splice(index, endIndex - index + 1, detailsNode)\n })\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {BlockContent, Heading, Root} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nconst defaultAllowedHeadings = new Set([2, 3, 4])\n\n/**\n * Parses a heading specifier into a Set of depths.\n * Supports a single level (`h2`) or a range (`h2-h5`).\n * Returns `undefined` for invalid input.\n */\nfunction parseHeadingRange(value: string): Set<number> | undefined {\n const match = value.match(/^h([1-6])(?:-h([1-6]))?$/)\n if (!match) {\n return undefined\n }\n\n const start = Number(match[1])\n const end = match[2] ? Number(match[2]) : start\n if (start > end) {\n return undefined\n }\n\n const depths = new Set<number>()\n for (let i = start; i <= end; i++) {\n depths.add(i)\n }\n return depths\n}\n\nfunction isHeading(node: {type: string}): node is Heading {\n return node.type === \"heading\"\n}\n\nfunction getStepStartMatch(text: string) {\n return text.match(/^:::\\s*steps(?:\\s+(h[1-6](?:-h[1-6])?))?\\s*$/)\n}\n\nfunction getStepEndMatch(text: string) {\n return text.match(/^:::\\s*\\/steps\\s*$/)\n}\n\nexport function isStepBlock(text: string) {\n return !!(getStepStartMatch(text) || getStepEndMatch(text))\n}\n\n/**\n * Transforms `:::steps` blocks into a styled `<div>` wrapper.\n *\n * Accepts an optional heading specifier to control which headings receive\n * step numbering. Supports a single level (`h3`) or a range (`h2-h5`).\n * Defaults to `h2-h4`.\n *\n * @example\n * ```\n * :::steps\n *\n * ## Step 1\n *\n * Content for step 1.\n *\n * ## Step 2\n *\n * Content for step 2.\n *\n * :::/steps\n * ```\n *\n * With a single heading level:\n *\n * ```\n * :::steps h3\n *\n * ### Step 1\n *\n * :::/steps\n * ```\n *\n * With a custom heading range:\n *\n * ```\n * :::steps h2-h5\n *\n * ## Step 1\n *\n * :::/steps\n * ```\n *\n * result:\n *\n * ```jsx\n * <div className=\"qui-docs__steps\">\n * <h2 data-step>Step 1</h2>\n * <p>Content for step 1.</p>\n * <h2 data-step>Step 2</h2>\n * <p>Content for step 2.</p>\n * </div>\n * ```\n */\nexport const remarkSteps: Plugin<[], Root> = () => {\n return (tree) => {\n visit(tree, \"paragraph\", (node, index, parent) => {\n if (!parent || index === undefined) {\n return\n }\n\n const firstChild = node.children[0]\n if (firstChild?.type !== \"text\") {\n return\n }\n\n const match = getStepStartMatch(firstChild.value)\n if (!match) {\n return\n }\n\n const allowedHeadings = match[1]\n ? (parseHeadingRange(match[1]) ?? defaultAllowedHeadings)\n : defaultAllowedHeadings\n\n let endIndex = index + 1\n const contentNodes: BlockContent[] = []\n\n while (endIndex < parent.children.length) {\n const child = parent.children[endIndex]\n\n if (child.type === \"paragraph\") {\n const firstText = child.children[0]\n if (firstText?.type === \"text\" && getStepEndMatch(firstText.value)) {\n break\n }\n }\n\n if (isHeading(child) && allowedHeadings.has(child.depth)) {\n child.data = {\n ...child.data,\n hProperties: {\n ...(child.data as {hProperties?: Record<string, unknown>})\n ?.hProperties,\n \"data-step\": \"\",\n },\n }\n }\n\n contentNodes.push(child as BlockContent)\n endIndex++\n }\n\n if (endIndex >= parent.children.length) {\n return\n }\n\n const stepsNode: BlockContent = {\n attributes: [],\n children: contentNodes,\n name: \"HeadingSteps\",\n type: \"mdxJsxFlowElement\",\n }\n\n parent.children.splice(index, endIndex - index + 1, stepsNode)\n })\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Link, Parent, Root} from \"mdast\"\nimport {minimatch} from \"minimatch\"\nimport {readdir} from \"node:fs/promises\"\nimport {join, relative} from \"node:path\"\nimport {visit} from \"unist-util-visit\"\n\nimport type {\n KnowledgePageData,\n KnowledgePages,\n KnowledgeSections,\n PageEntry,\n PageFrontmatter,\n SectionEntry,\n} from \"@qualcomm-ui/mdx-common\"\n\nimport type {\n KnowledgeExtraFile,\n KnowledgeFrontmatterConfig,\n PagesExportConfig,\n SectionExportConfig,\n} from \"../../config\"\nimport {\n getPathnameFromPathSegments,\n getPathSegmentsFromFileName,\n} from \"../../nav-builder\"\nimport type {MdxFileReader} from \"../markdown-file-reader\"\nimport {createRemarkProcessor} from \"../remark-pipeline\"\n\nimport {filterFrontmatter} from \"./filter-frontmatter\"\nimport {\n filterTextDirectives,\n formatDemos,\n formatNpmInstallTabs,\n formatThemeNodes,\n PropFormatter,\n} from \"./plugins\"\nimport {SectionExtractor} from \"./section-extractor\"\nimport type {\n KnowledgePageCache,\n MdxFlowExpression,\n ProcessedPage,\n} from \"./types\"\nimport {computeMd5} from \"./utils\"\n\nexport interface KnowledgeExporterConfig {\n baseUrl?: string\n docPropsPath?: string\n exclude?: string[]\n extraFiles?: KnowledgeExtraFile[]\n frontmatter?: KnowledgeFrontmatterConfig\n pageIdPrefix?: string\n pages?: PagesExportConfig\n routeDir: string\n sections?: SectionExportConfig\n verbose?: boolean\n}\n\n/**\n * Processes MDX documentation pages into structured JSON data (sections + pages).\n * Does not write files \u2014 the caller handles persistence.\n */\nexport class KnowledgeExporter {\n private readonly cache: KnowledgePageCache\n private readonly config: KnowledgeExporterConfig\n private readonly fileReader: MdxFileReader\n private readonly propFormatter: PropFormatter\n\n constructor(\n config: KnowledgeExporterConfig,\n fileReader: MdxFileReader,\n cache?: KnowledgePageCache,\n ) {\n this.cache = cache ?? new Map()\n this.config = config\n this.fileReader = fileReader\n this.propFormatter = new PropFormatter({\n docPropsPath: config.docPropsPath,\n routeDir: config.routeDir,\n verbose: config.verbose,\n })\n }\n\n async generate(): Promise<{\n cachedPageCount: number\n pages: KnowledgePages\n sections: KnowledgeSections\n totalPageCount: number\n }> {\n if (this.config.verbose) {\n console.log(`Scanning pages in: ${this.config.routeDir}`)\n if (this.config.exclude?.length) {\n console.log(`Excluding patterns: ${this.config.exclude.join(\", \")}`)\n }\n }\n\n const [pageInfos] = await Promise.all([\n this.scanPages(),\n this.propFormatter.loadDocProps(),\n ])\n\n if (pageInfos.length === 0) {\n console.log(\"No pages found.\")\n } else if (this.config.verbose) {\n console.log(`Found ${pageInfos.length} page(s)`)\n }\n\n let cachedCount = 0\n const currentFiles = new Set<string>()\n const allSections: SectionEntry[] = []\n const allPages: PageEntry[] = []\n\n const sectionsConfig = this.config.sections ?? {}\n const extractor = new SectionExtractor({\n depths: sectionsConfig.depths,\n minContentLength: sectionsConfig.minContentLength,\n pageIdPrefix: this.config.pageIdPrefix,\n })\n\n for (const page of pageInfos) {\n currentFiles.add(page.mdxFile)\n\n try {\n if (this.config.verbose) {\n console.log(`Processing page: ${page.name}`)\n }\n\n const {fileContents, frontmatter} = this.fileReader.readFileSync(\n page.mdxFile,\n )\n const contentHash = computeMd5(fileContents)\n const cached = this.cache.get(page.mdxFile)\n\n if (cached && cached.contentHash === contentHash) {\n cachedCount++\n allSections.push(...cached.sections)\n if (cached.pageEntry) {\n allPages.push(cached.pageEntry)\n }\n continue\n }\n\n const processed = await this.processMdxPage(page, {\n fileContents,\n frontmatter,\n })\n\n const filteredFrontmatter = filterFrontmatter(\n processed.frontmatter,\n this.config.frontmatter,\n )\n const pageInfo = {\n frontmatter: filteredFrontmatter,\n id: page.id,\n pathname: page.pathname,\n title: processed.title,\n url: processed.url,\n }\n\n const {sections: pageSections} = extractor.extract(\n processed.sectionAst,\n pageInfo,\n )\n allSections.push(...pageSections)\n\n const pageEntry = extractor.extractPage(processed.sectionAst, pageInfo)\n if (pageEntry) {\n pageEntry.content = `# ${processed.title}\\n\\n${pageEntry.content}`\n allPages.push(pageEntry)\n }\n\n this.cache.set(page.mdxFile, {\n contentHash,\n pageEntry: pageEntry ?? null,\n processedPage: processed,\n sections: pageSections,\n })\n } catch (error) {\n console.error(`Failed to process page: ${page.name}`)\n throw error\n }\n }\n\n // Prune cache entries for deleted files\n for (const key of this.cache.keys()) {\n if (!currentFiles.has(key)) {\n this.cache.delete(key)\n }\n }\n\n // Process extra files\n if (this.config.extraFiles?.length) {\n await this.processExtraFiles(\n this.config.extraFiles,\n extractor,\n allSections,\n allPages,\n )\n }\n\n const sectionsHash = computeMd5(JSON.stringify(allSections))\n const pagesHash = computeMd5(JSON.stringify(allPages))\n\n return {\n cachedPageCount: cachedCount,\n pages: {\n generatedAt: new Date().toISOString(),\n hash: pagesHash,\n pages: allPages,\n totalPages: allPages.length,\n version: 1,\n },\n sections: {\n generatedAt: new Date().toISOString(),\n hash: sectionsHash,\n sections: allSections,\n totalSections: allSections.length,\n version: 1,\n },\n totalPageCount: pageInfos.length,\n }\n }\n\n private async scanPages(): Promise<KnowledgePageData[]> {\n const components: KnowledgePageData[] = []\n const excludePatterns = this.config.exclude ?? []\n\n const shouldExclude = (absolutePath: string): boolean => {\n if (excludePatterns.length === 0) {\n return false\n }\n const relativePath = relative(this.config.routeDir, absolutePath)\n return excludePatterns.some((pattern) =>\n minimatch(relativePath, pattern, {matchBase: true}),\n )\n }\n\n const scanDirectory = async (dirPath: string): Promise<void> => {\n if (shouldExclude(dirPath)) {\n if (this.config.verbose) {\n console.log(\n `Excluding directory: ${relative(this.config.routeDir, dirPath)}`,\n )\n }\n return\n }\n\n const entries = await readdir(dirPath, {withFileTypes: true})\n const mdxFiles =\n entries.filter(\n (f) =>\n f.name.endsWith(\".mdx\") && !shouldExclude(join(dirPath, f.name)),\n ) ?? []\n\n for (const mdxFile of mdxFiles) {\n const demosFolder = entries.find((f) => f.name === \"demos\")\n const demosFolderPath = demosFolder\n ? join(dirPath, demosFolder.name)\n : undefined\n\n const segments = getPathSegmentsFromFileName(\n join(dirPath, mdxFile.name),\n this.config.routeDir,\n )\n const url = getPathnameFromPathSegments(segments)\n\n components.push({\n demosFolder: demosFolderPath,\n filePath: dirPath,\n id: segments.join(\"-\").trim(),\n mdxFile: join(dirPath, mdxFile.name),\n name: segments.at(-1)!,\n pathname: url,\n url: this.config.baseUrl\n ? new URL(url, this.config.baseUrl).toString()\n : undefined,\n })\n\n if (this.config.verbose) {\n console.log(`Found file: ${segments.at(-1)}`)\n console.log(` Demos folder: ${demosFolderPath || \"NOT FOUND\"}`)\n }\n }\n\n for (const entry of entries) {\n if (entry.isDirectory()) {\n await scanDirectory(join(dirPath, entry.name))\n }\n }\n }\n\n await scanDirectory(this.config.routeDir)\n return components\n }\n\n private formatFrontmatterExpressions(\n frontmatter: Record<string, unknown> | PageFrontmatter,\n ) {\n return () => (tree: Root) => {\n visit(\n tree,\n \"mdxFlowExpression\",\n (\n node: MdxFlowExpression,\n index: number | undefined,\n parent: Parent | undefined,\n ) => {\n if (\n node.value.trim() !== \"frontmatter.description\" ||\n index === undefined ||\n !parent\n ) {\n return\n }\n\n if (frontmatter.description) {\n parent.children.splice(index, 1, {\n children: [\n {type: \"text\", value: frontmatter.description as string},\n ],\n type: \"paragraph\",\n })\n } else {\n parent.children.splice(index, 1)\n }\n },\n )\n\n const root = tree as Parent\n const h1Index = root.children.findIndex((node) => {\n if (node.type !== \"heading\" || node.depth !== 1) {\n return false\n }\n return node.children?.some(\n (child) =>\n child.type === \"mdxTextExpression\" &&\n child.value?.includes(\"frontmatter\"),\n )\n })\n if (h1Index >= 0) {\n root.children.splice(h1Index, 1)\n }\n }\n }\n\n private transformRelativeUrls() {\n const baseUrl = this.config.baseUrl\n return () => (tree: Root) => {\n if (!baseUrl) {\n return\n }\n visit(tree, \"link\", (node: Link) => {\n if (node.url.startsWith(\"/\")) {\n node.url = `${baseUrl}${node.url}`\n }\n })\n }\n }\n\n private async processMdxContent(\n mdxContent: string,\n pageInfo: KnowledgePageData,\n frontmatter: Record<string, unknown> | PageFrontmatter,\n ): Promise<Root> {\n const themePlugin = await formatThemeNodes()\n\n const processor = createRemarkProcessor({\n frontmatter: true,\n gfm: true,\n mdx: true,\n plugins: [\n formatNpmInstallTabs,\n this.propFormatter.propsToMarkdownList(),\n this.formatFrontmatterExpressions(frontmatter),\n themePlugin,\n formatDemos(pageInfo.demosFolder, this.config.verbose),\n filterTextDirectives,\n this.transformRelativeUrls(),\n ],\n })\n\n return (await processor.run(processor.parse(mdxContent))) as Root\n }\n\n private async processMdxPage(\n pageInfo: KnowledgePageData,\n preRead?: {\n fileContents: string\n frontmatter: Record<string, unknown> | PageFrontmatter\n },\n ): Promise<ProcessedPage> {\n const {fileContents, frontmatter} =\n preRead ?? this.fileReader.readFileSync(pageInfo.mdxFile)\n const ast = await this.processMdxContent(\n fileContents,\n pageInfo,\n frontmatter,\n )\n\n const jsxAndMetaProcessor = createRemarkProcessor({\n extractMeta: {},\n frontmatter: true,\n gfm: true,\n mdx: true,\n output: \"md\",\n removeJsx: true,\n })\n const sectionAst = jsxAndMetaProcessor.runSync(ast) as Root\n const processed = String(jsxAndMetaProcessor.stringify(sectionAst))\n const rawContent = processed\n .replace(/^---\\r?\\n[\\s\\S]*?\\r?\\n---\\r?\\n?/, \"\")\n .replace(/(^#{1,6} .*\\\\<[^>]+)>/gm, \"$1\\\\>\")\n\n // Strip meta blocks from raw content for the prose-only field\n const stripMetaProcessor = createRemarkProcessor({\n extractMeta: {},\n output: \"md\",\n })\n const strippedContent = String(await stripMetaProcessor.process(rawContent))\n\n const title = (frontmatter.title as string) || pageInfo.name\n\n return {\n content: strippedContent.trim(),\n frontmatter: frontmatter as unknown as Record<string, unknown>,\n rawContent: rawContent.trim(),\n sectionAst,\n title,\n url: pageInfo.url,\n }\n }\n\n private async processExtraFiles(\n extraFiles: KnowledgeExtraFile[],\n extractor: SectionExtractor,\n allSections: SectionEntry[],\n allPages: PageEntry[],\n ): Promise<void> {\n await Promise.all(\n extraFiles.map(async (extraFile) => {\n let contents = extraFile.contents\n if (extraFile.processAsMdx) {\n const removeJsxProcessor = createRemarkProcessor({\n frontmatter: true,\n gfm: true,\n mdx: true,\n output: \"md\",\n plugins: [this.transformRelativeUrls()],\n removeJsx: true,\n })\n\n contents = String(await removeJsxProcessor.process(contents))\n }\n\n const lines: string[] = []\n if (extraFile.title) {\n lines.push(`# ${extraFile.title}`)\n lines.push(\"\")\n }\n lines.push(contents)\n const content = lines.join(\"\\n\")\n\n const processor = createRemarkProcessor({gfm: true, output: \"md\"})\n const tree = processor.parse(content)\n\n const pageInfo = {\n frontmatter: {},\n id: extraFile.id,\n pathname: `/${extraFile.id}`,\n title: extraFile.title || extraFile.id,\n }\n\n const {sections: pageSections} = extractor.extract(tree, pageInfo)\n allSections.push(...pageSections)\n\n const pageEntry = extractor.extractPage(tree, pageInfo)\n if (pageEntry) {\n allPages.push(pageEntry)\n }\n }),\n )\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {RouteMetaEntryInternal, RouteMetaInternal} from \"./types\"\n\n/**\n * Retrieves the route metadata for a given path based on its path segments.\n */\nexport function getRouteMeta(\n pathSegments: string[],\n metaJson: RouteMetaInternal,\n): RouteMetaEntryInternal | undefined | null {\n const routeMeta = metaJson[pathSegments[0]]\n if (!routeMeta) {\n // backup, fetch using id if provided\n return undefined\n }\n\n if (pathSegments.length === 1) {\n return routeMeta\n }\n\n return pathSegments\n .slice(1)\n .reduce((acc: RouteMetaEntryInternal | undefined | null, segment) => {\n return acc?.children?.[segment]\n }, routeMeta)\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {sortBy} from \"lodash-es\"\nimport {v4 as uuidv4} from \"uuid\"\n\nimport type {\n NavItem,\n PageFrontmatter,\n PageSection,\n} from \"@qualcomm-ui/mdx-common\"\nimport {capitalCase} from \"@qualcomm-ui/utils/change-case\"\nimport {defined} from \"@qualcomm-ui/utils/guard\"\n\nimport {getRouteMeta} from \"./get-route-meta\"\nimport type {NavMeta, RouteMetaEntryInternal, RouteMetaInternal} from \"./types\"\n\ninterface InitialRoute {\n pageFrontmatter: Partial<PageFrontmatter>\n pageSection: PageSection\n routeMeta?: RouteMetaEntryInternal\n}\n\n/**\n * Given a flat remix route structure, computes nested navigation items for the QUI\n * side nav.\n */\nexport class NavBuilder {\n private initialRoutes: InitialRoute[] = []\n private flatNavItems: NavItem[] = []\n\n get navItems(): NavItem[] {\n return this._navItems\n }\n private _navItems: NavItem[] = []\n\n private readonly metaJson: RouteMetaInternal\n private readonly navMeta: Record<number, NavMeta>\n\n constructor(metaJson: RouteMetaInternal, navMeta: Record<number, NavMeta>) {\n this.navMeta = navMeta\n this.metaJson = metaJson\n }\n\n add(\n pageSection: PageSection,\n pageFrontmatter: Partial<PageFrontmatter>,\n routeMeta?: RouteMetaEntryInternal,\n ): void {\n this.initialRoutes.push({pageFrontmatter, pageSection, routeMeta})\n }\n\n reset(): void {\n this.initialRoutes = []\n this.flatNavItems = []\n this._navItems = []\n }\n\n /**\n * Sorts nav items. Nav items with an order defined take precedence over nav items\n * without an order. Nav items with the same order are sorted alphabetically by\n * title.\n */\n private navItemSort(a: NavItem, b: NavItem, groupOrder?: string[]) {\n if (a.depth !== b.depth) {\n return a.depth - b.depth\n }\n\n if (a.order && !b.order) {\n return -1\n }\n if (!a.order && b.order) {\n return 1\n } else if (a.order && b.order && a.order !== b.order) {\n return a.order - b.order\n }\n\n if (groupOrder && a.group && b.group) {\n const aIndex = a.group ? groupOrder.indexOf(a.group) : -1\n const bIndex = b.group ? groupOrder.indexOf(b.group) : -1\n\n if (aIndex === bIndex) {\n // continue\n } else if (aIndex !== -1 && bIndex !== -1) {\n return aIndex - bIndex\n } else if (aIndex !== -1) {\n return -1\n } else if (bIndex !== -1) {\n return 1\n }\n }\n\n // group items with the same group\n if (a.group !== b.group) {\n if (!a.group && b.group) {\n return -1\n }\n if (a.group && !b.group) {\n return 1\n }\n if (a.group && b.group) {\n return a.group.localeCompare(b.group)\n }\n }\n\n return a.title.localeCompare(b.title)\n }\n\n resolveSideNavTitle(\n frontmatter: Partial<PageFrontmatter>,\n routeMeta: Partial<RouteMetaEntryInternal>,\n fallback: string,\n ): string {\n return (\n (defined(routeMeta.sideNavTitle)\n ? routeMeta.sideNavTitle || \"\"\n : frontmatter.sideNavTitle || \"\") || fallback\n )\n }\n\n /**\n * Builds a flat list of nav items from the MDX pages and _meta.json. If a page\n * does not exist, it is not added to the side nav (even if it has an entry in\n * _meta.json).\n */\n private buildNavItem({\n pageFrontmatter,\n pageSection: {pathname, pathSegments, title},\n routeMeta: routeMetaParam,\n }: InitialRoute) {\n const id = pageFrontmatter?.id || \"\"\n\n // handle home page (this route does not have path segments)\n if (!pathSegments.length && pathname === \"/\") {\n const routeMeta =\n routeMetaParam || getRouteMeta(id ? [id] : [], this.metaJson)\n if (!routeMeta) {\n return\n }\n\n this.flatNavItems.push({\n depth: 1,\n expanded: routeMeta?.expanded || false,\n id: `/`,\n order: routeMeta?.order,\n pathname,\n pathSegments: [],\n title: this.resolveSideNavTitle(\n pageFrontmatter,\n routeMeta,\n routeMeta?.title || title,\n ),\n })\n }\n\n pathSegments.forEach((segment, index) => {\n const depth = index + 1\n\n // we only add an item if it doesn't already exist, which we determine by\n // comparing the path segments iteratively.\n const navItem = this.flatNavItems.find((item) =>\n pathSegments\n .slice(0, depth)\n .every((value, i) => value === item.pathSegments[i]),\n )\n\n if (!navItem) {\n const isPage = index === pathSegments.length - 1\n const adjustedSegments = pathSegments.slice(0, depth)\n\n const routeMeta =\n getRouteMeta(\n isPage ? pathSegments : adjustedSegments,\n this.metaJson,\n ) ?? {}\n\n this.flatNavItems.push({\n depth,\n expanded: routeMeta?.expanded || false,\n group: isPage\n ? routeMeta.group || pageFrontmatter.group\n : routeMeta.group,\n id: `/${adjustedSegments.join(\"/\")}`,\n items: [],\n order: routeMeta?.order,\n pathname: isPage ? pathname : undefined,\n pathSegments: adjustedSegments,\n title: this.resolveSideNavTitle(\n isPage ? pageFrontmatter : {},\n routeMeta,\n routeMeta?.title\n ? routeMeta.title\n : isPage\n ? title\n : capitalCase(segment),\n ),\n })\n }\n })\n }\n\n /**\n * Iterates through a nav item's path segments and ensures that all of its parent\n * elements exist in the recursive structure.\n */\n private ensureParent(navItem: NavItem) {\n const segments = navItem.pathSegments\n let items: NavItem[] = this.navItems\n let item: NavItem | undefined\n let prevItem: NavItem | undefined = undefined\n\n for (let i = 0; i < segments.length - 1; i++) {\n const segment = segments[i]\n item = items?.find((entry) => entry.pathSegments[i] === segment)\n if (item) {\n // point to the found item's children and keep iterating\n items = item.items ?? []\n prevItem = item\n continue\n }\n if (prevItem) {\n const pathSegments = segments.slice(0, i + 1)\n const routeMeta = getRouteMeta(pathSegments, this.metaJson)\n\n items = []\n const base = {\n depth: pathSegments.length,\n id: `/routes/${pathSegments.join(\"/\")}`,\n items,\n pathSegments,\n title: segment,\n }\n const newItem = routeMeta\n ? {\n ...base,\n expanded: routeMeta.expanded,\n order: routeMeta.order,\n restricted: routeMeta.restricted,\n title: routeMeta.title ?? segment,\n }\n : base\n prevItem.items = prevItem.items\n ? [...prevItem.items, newItem]\n : [newItem]\n }\n prevItem = item\n }\n }\n\n /**\n * Deeply inserts a nav item into the array, iterating through parent routes\n * (based on the pathSegments) and adding them if they don't exist.\n *\n * For example, given a leaf node 4 path segments deep, this function will create\n * all parent nav items as nested children of the top-most nav item.\n */\n private nestedInsert(\n item: NavItem,\n pathSegments: string[],\n items: NavItem[],\n ) {\n const segment = pathSegments[0]\n const parentItem = items.find(\n (parent) =>\n parent.pathSegments[parent.pathSegments.length - 1] === segment,\n )\n if (parentItem) {\n this.nestedInsert(item, pathSegments.slice(1), parentItem.items ?? [])\n } else if (pathSegments.length === 1) {\n items.push(item)\n }\n }\n\n private buildNestedNavItems() {\n for (let i = 0; i < this.flatNavItems.length; i++) {\n const navItem = this.flatNavItems[i]\n if (navItem.depth === 1) {\n this.navItems.push(navItem)\n continue\n }\n\n this.ensureParent(navItem)\n this.nestedInsert(navItem, navItem.pathSegments, this.navItems)\n }\n }\n\n private sortNestedNavItems(items: NavItem[], groupOrder?: string[]) {\n items.sort((a, b) => this.navItemSort(a, b, groupOrder))\n items.forEach((item) => {\n if (item.items?.length) {\n const meta = getRouteMeta(item.pathSegments, this.metaJson)\n this.sortNestedNavItems(item.items, meta?.groupOrder)\n }\n })\n }\n\n /**\n * To be called after every mdx page route has been added through the {@link add}\n * function.\n */\n build(): NavItem[] {\n // We need to process parent items first, so we sort by path segment. Routes\n // with shorter path segments will be processed first.\n sortBy(\n this.initialRoutes,\n (item) => item.pageSection.pathSegments.length,\n ).map((r) => this.buildNavItem(r))\n\n this.buildNestedNavItems()\n\n const rootMeta = getRouteMeta([], this.metaJson)\n this.sortNestedNavItems(this.navItems, rootMeta?.groupOrder)\n\n if (this.navMeta) {\n Object.entries(this.navMeta).forEach(([index, value]) => {\n this._navItems.splice(parseInt(index), 0, {\n depth: 1,\n id: uuidv4(),\n pathSegments: [],\n sectionTitle: value.sectionTitle,\n separator: value.separator,\n title: \"\",\n })\n })\n }\n\n this._navItems = this.groupNavItems(this.navItems)\n this._navItems = this.buildSearchMeta(this.navItems, [])\n return this.navItems\n }\n\n private groupNavItems(items: NavItem[]): NavItem[] {\n const result: NavItem[] = []\n const seenGroups = new Set<string>()\n\n for (const item of items) {\n if (item.group && !seenGroups.has(item.group)) {\n seenGroups.add(item.group)\n result.push({\n depth: item.depth,\n group: item.group,\n id: uuidv4(),\n pathSegments: [],\n sectionTitle: item.group,\n title: \"\",\n })\n }\n\n result.push({\n ...item,\n items: item.items ? this.groupNavItems(item.items) : undefined,\n })\n }\n\n return result\n }\n\n /**\n * Walks over the tree and builds search metadata using the nearest sectionTitle.\n */\n private buildSearchMeta(items: NavItem[], meta: string[]): NavItem[] {\n let sectionTitle = \"\"\n const results: NavItem[] = []\n\n for (const ogItem of items) {\n const item = {...ogItem}\n\n if (item.sectionTitle) {\n sectionTitle = item.sectionTitle\n } else if (item.separator) {\n sectionTitle = \"\"\n }\n\n if (!item.separator) {\n const currentMeta = sectionTitle ? [...meta, sectionTitle] : [...meta]\n const nextMeta = [...(item.searchMeta || []), ...currentMeta]\n if (nextMeta.length) {\n item.searchMeta = [...nextMeta]\n }\n\n if (item.items) {\n item.items = this.buildSearchMeta(item.items, currentMeta)\n }\n }\n\n results.push(item)\n }\n\n return results\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {join} from \"node:path\"\n\nimport {capitalCase} from \"@qualcomm-ui/utils/change-case\"\n\nimport type {RoutingStrategy} from \"../config\"\n\nimport {getRouteMeta} from \"./get-route-meta\"\nimport type {RouteMetaInternal} from \"./types\"\n\nexport function getPathnameFromPathSegments(segments: string[]) {\n return `/${segments.join(\"/\")}`\n}\n\nexport function getCategoriesFromPathSegments(\n segments: string[],\n metaJson: RouteMetaInternal,\n // the frontmatter title only applies to the last segment.\n frontmatterTitle: string,\n): string[] {\n return segments.reduce((acc: string[], segment, index) => {\n const pathSegments = segments.slice(0, index + 1)\n if (index === segments.length - 1) {\n acc.push(frontmatterTitle)\n return acc\n }\n const meta = getRouteMeta(pathSegments, metaJson)\n if (meta?.title) {\n acc.push(meta.title)\n } else {\n acc.push(pathSegmentToCategory(segment))\n }\n return acc\n }, [])\n}\n\n// fallback for unmatched path segments\nexport function pathSegmentToCategory(segment: string): string {\n // we don't transform words like `a`, `or`, and `and`\n return segment\n .split(\"-\")\n .map((segment) =>\n /\\b(a|an|and|but|or|in|on|at)\\b/.test(segment)\n ? segment\n : capitalCase(segment),\n )\n .join(\" \")\n}\n\nfunction getGeneroutedPathSegments(filePath: string): string[] {\n const extension = filePath.endsWith(\"mdx\") ? \"mdx\" : \"tsx\"\n\n const segments = filePath\n .substring(0, filePath.lastIndexOf(`.${extension}`))\n .split(\"/\")\n\n if (segments[segments.length - 1] === \"index\") {\n return segments.slice(0, segments.length - 1)\n }\n return segments\n}\n\nconst pathSeparatorRegex = /[\\/\\\\.]/\nfunction isPathSeparator(char: string) {\n return pathSeparatorRegex.test(char)\n}\n\nconst indexRouteRegex =\n /((^|[.]|[+]\\/)(index|_index))(\\/[^\\/]+)?$|(\\/_?index\\/)/\n\nfunction getRemixFlatRoutesSegments(\n name: string,\n index: boolean,\n paramPrefixChar: string = \"$\",\n) {\n let routeSegments: string[] = []\n let i = 0\n let routeSegment = \"\"\n let state = \"START\"\n let subState = \"NORMAL\"\n let hasPlus = false\n\n // ignore layout routes\n if (name.endsWith(\"_layout\")) {\n return []\n }\n\n /*\n * name has already been normalized to use / as path separator.\n * replace `+/_.` with `_+/`\n * this supports the ability to specify parent folder will not be a layout.\n * _public+/_.about.tsx => _public_.about.tsx\n */\n if (/\\+\\/_\\./.test(name)) {\n name = name.replace(/\\+\\/_\\./g, \"_+/\")\n }\n\n /*\n * replace `+/` with `.`\n * this supports folders for organizing flat-files convention.\n * _public+/about.tsx => _public.about.tsx\n */\n if (/\\+\\//.test(name)) {\n name = name.replace(/\\+\\//g, \".\")\n hasPlus = true\n }\n const hasFolder = /\\//.test(name)\n // if name has plus folder, but we still have regular folders\n // then treat ending route as flat-folders\n if (\n ((hasPlus && hasFolder) || !hasPlus) &&\n !(name.endsWith(\".route\") || name.endsWith(\".index\"))\n ) {\n // Do not remove segments ending in .route\n // since these would be part of the route directory name\n // docs/readme.route.tsx => docs/readme\n // Remove last segment since this should just be the route filename, and we only\n // want the directory name docs/_layout.tsx => docs\n const last = name.lastIndexOf(\"/\")\n if (last >= 0) {\n name = name.substring(0, last)\n }\n }\n\n const pushRouteSegment = (routeSegment: string) => {\n if (routeSegment) {\n routeSegments.push(routeSegment)\n }\n }\n\n while (i < name.length) {\n const char = name[i]\n switch (state) {\n case \"START\":\n // process existing segment\n if (\n routeSegment.includes(paramPrefixChar) &&\n !(\n routeSegment.startsWith(paramPrefixChar) ||\n routeSegment.startsWith(`(${paramPrefixChar}`)\n )\n ) {\n throw new Error(\n `Route params must start with prefix char ${paramPrefixChar}: ${routeSegment}`,\n )\n }\n if (\n routeSegment.includes(\"(\") &&\n !routeSegment.startsWith(\"(\") &&\n !routeSegment.endsWith(\")\")\n ) {\n throw new Error(\n `Optional routes must start and end with parentheses: ${routeSegment}`,\n )\n }\n pushRouteSegment(routeSegment)\n routeSegment = \"\"\n state = \"PATH\"\n continue // restart without advancing index\n case \"PATH\":\n if (isPathSeparator(char) && subState === \"NORMAL\") {\n state = \"START\"\n break\n } else if (char === \"[\") {\n subState = \"ESCAPE\"\n break\n } else if (char === \"]\") {\n subState = \"NORMAL\"\n break\n }\n routeSegment += char\n break\n }\n i++ // advance to next character\n }\n // process remaining segment\n pushRouteSegment(routeSegment)\n // strip trailing .route segment\n if (\n routeSegments.at(-1) === \"route\" ||\n routeSegments.at(-1) === \"index\" ||\n routeSegments.at(-1) === \"_index\" ||\n routeSegments.at(-1) === \"_route\"\n ) {\n routeSegments = routeSegments.slice(0, -1)\n }\n // if hasPlus, we need to strip the trailing segment if it starts with _\n // and route is not an index route\n // this is to handle layouts in flat-files\n // _public+/_layout.tsx => _public.tsx\n // _public+/index.tsx => _public.index.tsx\n if (!index && hasPlus && routeSegments.at(-1)?.startsWith(\"_\")) {\n routeSegments = routeSegments.slice(0, -1)\n }\n return routeSegments\n}\n\nfunction getRemixHybridRoutesPathSegments(filePath: string): string[] {\n const routeWithoutExtension = filePath.substring(0, filePath.lastIndexOf(\".\"))\n\n return getRemixFlatRoutesSegments(\n routeWithoutExtension,\n indexRouteRegex.test(routeWithoutExtension),\n )\n}\n\nexport function getPathSegmentsFromFileName(\n filePath: string,\n pageDirectory: string,\n strategy?: RoutingStrategy,\n): string[] {\n const filePathWithoutPageDirectory = filePath.substring(\n filePath.indexOf(pageDirectory) + pageDirectory.length + 1,\n )\n if (typeof strategy === \"function\") {\n return strategy(filePathWithoutPageDirectory)\n }\n switch (strategy) {\n case \"vite-generouted\":\n return getGeneroutedPathSegments(filePathWithoutPageDirectory)\n default:\n return getRemixHybridRoutesPathSegments(filePathWithoutPageDirectory)\n }\n}\n\nexport function filterFileGlob(\n fileGlob: string[],\n ext: string,\n srcDir: string,\n router?: RoutingStrategy,\n): string[] {\n if (typeof router === \"string\" && router === \"vite-generouted\") {\n // vite-generouted: filter routes\n const restrictedPattern = /(\\(.*\\))|(\\[.*\\])/\n // pull out the full path before filtering to avoid potential issues with\n // parent directories.\n const relativeGlobs = fileGlob.map((file) => file.replace(srcDir, \"\"))\n return (\n relativeGlobs\n .filter(\n (file) =>\n file.endsWith(`.${ext}`) &&\n !file.includes(\"/_\") &&\n !file.includes(\"/+\"),\n )\n // filter pathless segments\n .map((file) =>\n file\n .split(\"/\")\n .filter((segment) => !restrictedPattern.test(segment))\n .join(\"/\"),\n )\n // restore full path\n .map((file) => join(srcDir, file))\n )\n }\n return fileGlob.filter((file) => file.endsWith(ext) && !file.includes(\"$\"))\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {NavConfig, NavMeta, RouteMeta, RouteMetaInternal} from \"./types\"\n\nexport function transformRouteMetaArray(\n meta: NavConfig[],\n routeMetaNav: Record<string, NavMeta>,\n): RouteMetaInternal {\n let ignoringOrder = 0\n return meta.reduce((acc: RouteMetaInternal, item, index) => {\n // strip the nav meta and populate a separate record. This will be used for\n // lookup while building the nav items.\n if (!(\"id\" in item)) {\n if (\"separator\" in item || \"sectionTitle\" in item) {\n // offset the navMeta index by the number of items that will be sorted to\n // the back of the nav order.\n routeMetaNav[index - ignoringOrder] = item\n }\n return acc\n }\n const current = item as RouteMeta\n if (current.ignoreRouteMetaOrder || current.hidden) {\n // items with ignored order are always sorted to the back of the nav order. We\n // need to account for this when splicing in the navMeta entries.\n ignoringOrder++\n }\n acc[current.id] = {\n children: current.children\n ? transformRouteMetaArray(current.children, routeMetaNav)\n : undefined,\n expanded: current.expanded,\n group: current.group,\n groupOrder: current.groupOrder,\n hidden: current.hidden,\n hideBreadcrumbs: current.hideBreadcrumbs,\n hideFromSearch: current.hideFromSearch,\n hidePageLinks: current.hidePageLinks,\n hideSideNav: current.hideSideNav,\n hideToc: current.hideToc,\n order: current.ignoreRouteMetaOrder ? undefined : index + 1,\n restricted: current.restricted,\n title: current.title,\n }\n return acc\n }, {})\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {minimatch} from \"minimatch\"\n\nimport type {KnowledgeFrontmatterConfig} from \"../../config\"\n\nexport function filterFrontmatter(\n frontmatter: Record<string, unknown>,\n config: KnowledgeFrontmatterConfig | undefined,\n): Record<string, unknown> {\n if (!config?.include?.length) {\n return frontmatter\n }\n\n const includePatterns = config.include\n const excludePatterns = config.exclude ?? []\n const filtered: Record<string, unknown> = {}\n\n for (const [field, value] of Object.entries(frontmatter)) {\n if (value === undefined) {\n continue\n }\n const isIncluded = includePatterns.some((pattern) =>\n minimatch(field, pattern),\n )\n const isExcluded = excludePatterns.some((pattern) =>\n minimatch(field, pattern),\n )\n if (isIncluded && !isExcluded) {\n filtered[field] = value\n }\n }\n\n return filtered\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Code, Parent} from \"mdast\"\nimport type {MdxJsxAttribute, MdxJsxFlowElement} from \"mdast-util-mdx-jsx\"\nimport {readFile} from \"node:fs/promises\"\nimport {basename, extname, join} from \"node:path\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nimport {kebabCase} from \"@qualcomm-ui/utils/change-case\"\n\nimport type {ImportedModule} from \"../types\"\nimport {\n exists,\n extractRelativeImports,\n removePreviewLines,\n resolveModulePath,\n} from \"../utils\"\n\nasync function collectDemoImports(\n demoCode: string,\n demoFilePath: string,\n visited: Set<string> = new Set(),\n verbose?: boolean,\n): Promise<ImportedModule[]> {\n const modules: ImportedModule[] = []\n const relativeImports = extractRelativeImports(demoCode)\n\n for (const importPath of relativeImports) {\n const resolvedPath = await resolveModulePath(importPath, demoFilePath)\n if (!resolvedPath || visited.has(resolvedPath)) {\n continue\n }\n visited.add(resolvedPath)\n\n try {\n const importContent = await readFile(resolvedPath, \"utf-8\")\n modules.push({\n content: importContent,\n path: resolvedPath,\n })\n const nestedModules = await collectDemoImports(\n importContent,\n resolvedPath,\n visited,\n verbose,\n )\n modules.push(...nestedModules)\n } catch {\n if (verbose) {\n console.log(` Could not read import: ${resolvedPath}`)\n }\n }\n }\n\n return modules\n}\n\n/**\n * Creates a remark plugin that replaces demo JSX elements (QdsDemo, CodeDemo,\n * Demo) with code blocks containing the demo source code from the demos folder.\n * Imported files are added as sibling code blocks immediately after the demo.\n */\nexport function formatDemos(\n demosFolder: string | undefined,\n verbose?: boolean,\n): Plugin {\n return () => async (tree) => {\n const promises: Promise<void>[] = []\n\n visit(\n tree,\n \"mdxJsxFlowElement\",\n (\n node: MdxJsxFlowElement,\n index: number | undefined,\n parent: Parent | undefined,\n ) => {\n if (\n !node?.name ||\n ![\"QdsDemo\", \"CodeDemo\", \"Demo\"].includes(node.name)\n ) {\n return\n }\n\n const nameAttr = node.attributes?.find(\n (attr): attr is MdxJsxAttribute =>\n attr.type === \"mdxJsxAttribute\" && attr.name === \"name\",\n )\n\n const nodeAttr = node.attributes?.find(\n (attr): attr is MdxJsxAttribute =>\n attr.type === \"mdxJsxAttribute\" && attr.name === \"node\",\n )\n\n let demoName: string | undefined\n\n if (nameAttr && typeof nameAttr.value === \"string\") {\n demoName = nameAttr.value\n } else if (nodeAttr?.value && typeof nodeAttr.value !== \"string\") {\n const estree = nodeAttr.value.data?.estree\n if (estree?.body?.[0]?.type === \"ExpressionStatement\") {\n const expression = estree.body[0].expression\n if (\n expression.type === \"MemberExpression\" &&\n expression.object.type === \"Identifier\" &&\n expression.object.name === \"Demo\" &&\n expression.property.type === \"Identifier\"\n ) {\n demoName = expression.property.name\n }\n }\n }\n\n if (!demoName) {\n if (parent && index !== undefined) {\n parent.children.splice(index, 1)\n }\n return\n }\n\n promises.push(\n (async () => {\n const kebabName = kebabCase(demoName)\n let filePath = `${kebabName}.tsx`\n\n if (!demosFolder) {\n if (verbose) {\n console.log(` No demos folder for ${demoName}`)\n }\n if (parent && index !== undefined) {\n parent.children.splice(index, 1)\n }\n return\n }\n\n let demoFilePath = join(demosFolder, filePath)\n let isAngularDemo = false\n\n if (!(await exists(demoFilePath))) {\n demoFilePath = join(demosFolder, `${kebabName}.ts`)\n if (await exists(demoFilePath)) {\n isAngularDemo = true\n filePath = `${kebabCase(demoName).replace(\"-component\", \".component\")}.ts`\n demoFilePath = join(demosFolder, filePath)\n } else {\n console.log(` Demo not found ${demoName}`)\n if (parent && index !== undefined) {\n parent.children.splice(index, 1)\n }\n return\n }\n }\n\n try {\n const demoCode = await readFile(demoFilePath, \"utf-8\")\n const cleanedCode = removePreviewLines(demoCode)\n\n if (verbose) {\n console.log(` Replaced demo ${demoName} with source code`)\n }\n\n const demoCodeBlock: Code = {\n lang: isAngularDemo ? \"angular-ts\" : \"tsx\",\n meta: null,\n type: \"code\",\n value: cleanedCode,\n }\n\n const importedModules = await collectDemoImports(\n demoCode,\n demoFilePath,\n new Set(),\n verbose,\n )\n\n if (\n importedModules.length === 0 ||\n !parent ||\n index === undefined\n ) {\n Object.assign(node, demoCodeBlock)\n } else {\n const nodesToInsert: Code[] = [demoCodeBlock]\n\n for (const importedModule of importedModules) {\n const ext = extname(importedModule.path).slice(1)\n const filename = basename(importedModule.path)\n nodesToInsert.push({\n lang: ext,\n meta: `title=\"${filename}\"`,\n type: \"code\",\n value: importedModule.content,\n })\n }\n\n parent.children.splice(index, 1, ...nodesToInsert)\n\n if (verbose) {\n console.log(\n ` Added ${importedModules.length} imported file(s) after demo`,\n )\n }\n }\n } catch (error) {\n if (verbose) {\n console.log(`Error reading demo ${demoName}`, error)\n }\n if (parent && index !== undefined) {\n parent.children.splice(index, 1)\n }\n }\n })(),\n )\n },\n )\n\n await Promise.all(promises)\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {createHash} from \"node:crypto\"\nimport {access, readFile} from \"node:fs/promises\"\nimport {dirname, join, resolve} from \"node:path\"\nimport ts from \"typescript\"\n\nimport type {ImportedModule} from \"./types\"\n\nexport async function exists(dirPath: string): Promise<boolean> {\n return access(dirPath)\n .then(() => true)\n .catch(() => false)\n}\n\nexport function computeMd5(content: string): string {\n return createHash(\"md5\").update(content).digest(\"hex\")\n}\n\nexport function isPreviewLine(trimmedLine: string): boolean {\n return (\n trimmedLine === \"// preview\" ||\n /^\\{\\s*\\/\\*\\s*preview\\s*\\*\\/\\s*\\}$/.test(trimmedLine) ||\n /^<!--\\s*preview\\s*-->$/.test(trimmedLine)\n )\n}\n\nexport function removePreviewLines(code: string): string {\n return code\n .split(\"\\n\")\n .filter((line) => !isPreviewLine(line.trim()))\n .join(\"\\n\")\n}\n\nexport function getIntroLines(projectName?: string, description?: string) {\n const lines: string[] = []\n\n if (projectName) {\n lines.push(`# ${projectName}`)\n }\n\n if (description) {\n lines.push(\"\")\n lines.push(`> ${description}`)\n }\n\n return lines.join(\"\\n\")\n}\n\nexport function extractRelativeImports(content: string): string[] {\n const sourceFile = ts.createSourceFile(\n \"temp.ts\",\n content,\n ts.ScriptTarget.Latest,\n false,\n ts.ScriptKind.TSX,\n )\n\n const imports: string[] = []\n\n for (const statement of sourceFile.statements) {\n if (\n ts.isImportDeclaration(statement) &&\n ts.isStringLiteral(statement.moduleSpecifier)\n ) {\n const path = statement.moduleSpecifier.text\n if (path.startsWith(\".\")) {\n imports.push(path)\n }\n }\n }\n\n return imports\n}\n\nexport async function resolveModulePath(\n importPath: string,\n fromFile: string,\n): Promise<string | null> {\n const fromDir = dirname(fromFile)\n const baseResolved = resolve(fromDir, importPath)\n const extensions = [\".ts\", \".tsx\", \".js\", \".jsx\", \"\"]\n for (const ext of extensions) {\n const fullPath = baseResolved + ext\n if (await exists(fullPath)) {\n return fullPath\n }\n }\n if (await exists(baseResolved)) {\n const indexPath = join(baseResolved, \"index.ts\")\n if (await exists(indexPath)) {\n return indexPath\n }\n }\n return null\n}\n\nexport function extractMetadata(\n metadata: Record<string, string> | undefined,\n): [string, string][] {\n return Object.entries(metadata ?? {})\n}\n\nexport async function collectRelativeImports(\n filePath: string,\n visited: Set<string> = new Set(),\n verbose?: boolean,\n): Promise<ImportedModule[]> {\n const normalizedPath = resolve(filePath)\n if (visited.has(normalizedPath)) {\n return []\n }\n visited.add(normalizedPath)\n const modules: ImportedModule[] = []\n try {\n const content = await readFile(normalizedPath, \"utf-8\")\n const relativeImports = extractRelativeImports(content)\n for (const importPath of relativeImports) {\n const resolvedPath = await resolveModulePath(importPath, normalizedPath)\n if (!resolvedPath) {\n if (verbose) {\n console.log(\n ` Could not resolve import: ${importPath} from ${normalizedPath}`,\n )\n }\n continue\n }\n const importContent = await readFile(resolvedPath, \"utf-8\")\n modules.push({\n content: importContent,\n path: resolvedPath,\n })\n const nestedModules = await collectRelativeImports(\n resolvedPath,\n visited,\n verbose,\n )\n modules.push(...nestedModules)\n }\n } catch (error) {\n if (verbose) {\n console.log(`Error processing ${normalizedPath}`, error)\n }\n }\n return modules\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Parent} from \"mdast\"\nimport type {MdxJsxAttribute, MdxJsxFlowElement} from \"mdast-util-mdx-jsx\"\nimport {readFile} from \"node:fs/promises\"\nimport {dirname, join, resolve} from \"node:path\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nimport type {SimplifiedProp} from \"@qualcomm-ui/mdx-common\"\nimport type {\n QuiComment,\n QuiCommentDisplayPart,\n} from \"@qualcomm-ui/typedoc-common\"\n\nimport {extractNamesFromAttribute} from \"../../mdx-utils\"\nimport type {ComponentProps, DocProps, PropInfo} from \"../types\"\nimport {exists} from \"../utils\"\n\nfunction extractBestType(propInfo: PropInfo): string {\n const type = propInfo.resolvedType?.prettyType || propInfo.type\n\n return cleanType(type.startsWith(\"| \") ? type.substring(2) : type)\n}\n\nfunction extractRequired(propInfo: PropInfo, isPartial: boolean): boolean {\n return Boolean(propInfo.resolvedType?.required && !isPartial)\n}\n\nfunction cleanType(type: string): string {\n return type.replace(/\\n/g, \" \").replace(/\\s+/g, \" \").trim()\n}\n\nfunction cleanDefaultValue(defaultValue: string): string {\n return defaultValue.replace(/^\\n+/, \"\").replace(/\\n+$/, \"\").trim()\n}\n\nfunction escapeText(value: string): string {\n return value.replace(/\\n/g, \" \")\n}\n\nfunction propsToDefinitionList(props: SimplifiedProp[]): string {\n if (props.length === 0) {\n return \"\"\n }\n\n return props\n .map((prop) => {\n const parts = [`- **${prop.name}** (\\`${escapeText(prop.type)}\\``]\n\n if (prop.defaultValue) {\n parts.push(`, default: \\`${escapeText(prop.defaultValue)}\\``)\n }\n if (prop.required) {\n parts.push(\", required\")\n }\n\n parts.push(\")\")\n\n if (prop.description) {\n parts.push(` - ${escapeText(prop.description)}`)\n }\n\n return parts.join(\"\")\n })\n .join(\"\\n\")\n}\n\nexport interface PropFormatterOptions {\n docPropsPath?: string\n routeDir: string\n verbose?: boolean\n}\n\nexport class PropFormatter {\n private docProps: DocProps | null = null\n private readonly docPropsPath?: string\n private readonly routeDir: string\n private readonly verbose: boolean\n\n constructor(options: PropFormatterOptions) {\n this.docPropsPath = options.docPropsPath\n this.routeDir = options.routeDir\n this.verbose = options.verbose ?? false\n }\n\n async loadDocProps(): Promise<DocProps | null> {\n if (this.docProps) {\n return this.docProps\n }\n const resolvedDocPropsPath = this.docPropsPath\n ? (await exists(this.docPropsPath))\n ? this.docPropsPath\n : resolve(process.cwd(), this.docPropsPath)\n : join(dirname(this.routeDir), \"doc-props.json\")\n\n if (!(await exists(resolvedDocPropsPath))) {\n if (this.verbose) {\n console.log(`Doc props file not found at: ${resolvedDocPropsPath}`)\n }\n return null\n }\n\n try {\n const content = await readFile(resolvedDocPropsPath, \"utf-8\")\n const docProps = JSON.parse(content) as DocProps\n if (this.verbose) {\n console.log(`Loaded doc props from: ${resolvedDocPropsPath}`)\n console.log(\n `Found ${Object.keys(docProps.props).length} component types`,\n )\n }\n this.docProps = docProps\n return docProps\n } catch (error) {\n if (this.verbose) {\n console.log(\"Error loading doc props\", error)\n }\n return null\n }\n }\n\n private formatCommentParts(parts: QuiCommentDisplayPart[]): string {\n return parts\n .map((part) => {\n switch (part.kind) {\n case \"text\":\n return part.text\n case \"code\":\n const codeText = part.text\n .replace(/```\\w*\\n?/g, \"\") // Remove opening code blocks with optional language\n .replace(/\\n?```/g, \"\") // Remove closing code blocks\n .trim()\n\n if (codeText.includes(\"\\n\")) {\n return `\\`\\`\\`\\n${codeText}\\n\\`\\`\\``\n } else {\n return codeText\n }\n default:\n if (\n \"tag\" in part &&\n part.tag === \"@link\" &&\n typeof part.target === \"string\"\n ) {\n if (part.text === \"Learn more\") {\n return \"\"\n }\n }\n return part.text\n }\n })\n .join(\"\")\n .replace(/\\n/g, \" \")\n .replace(/\\s+/g, \" \")\n .trim()\n }\n\n private formatComment(comment: QuiComment | null): string {\n if (!comment) {\n return \"\"\n }\n\n const parts: string[] = []\n\n if (comment.summary && comment.summary.length > 0) {\n const summaryText = this.formatCommentParts(comment.summary)\n if (summaryText.trim()) {\n parts.push(summaryText.trim())\n }\n }\n\n if (comment.blockTags && comment.blockTags.length > 0) {\n for (const blockTag of comment.blockTags) {\n const tagContent = this.formatCommentParts(blockTag.content)\n if (tagContent.trim()) {\n const tagName = blockTag.tag.replace(\"@\", \"\")\n\n if (tagName === \"default\" || tagName === \"defaultValue\") {\n continue\n }\n\n if (tagName === \"example\") {\n parts.push(`**Example:**\\n\\`\\`\\`\\n${tagContent.trim()}\\n\\`\\`\\``)\n } else {\n parts.push(`**${tagName}:** ${tagContent.trim()}`)\n }\n }\n }\n }\n\n return parts.join(\"\\n\\n\")\n }\n\n extractProps(props: ComponentProps, isPartial: boolean): SimplifiedProp[] {\n const propsInfo: SimplifiedProp[] = []\n\n if (props.props?.length) {\n propsInfo.push(\n ...props.props.map((prop) => this.convertPropInfo(prop, isPartial)),\n )\n }\n if (props.input?.length) {\n propsInfo.push(\n ...props.input.map((prop) =>\n this.convertPropInfo(prop, isPartial, \"input\"),\n ),\n )\n }\n if (props.output?.length) {\n propsInfo.push(\n ...props.output.map((prop) =>\n this.convertPropInfo(prop, isPartial, \"output\"),\n ),\n )\n }\n\n return propsInfo\n }\n\n private convertPropInfo(\n propInfo: PropInfo,\n isPartial: boolean,\n propType: \"input\" | \"output\" | undefined = undefined,\n ): SimplifiedProp {\n return {\n name: propInfo.name,\n type: extractBestType(propInfo),\n ...(propInfo.defaultValue && {\n defaultValue: cleanDefaultValue(propInfo.defaultValue),\n }),\n description: this.formatComment(propInfo.comment || null),\n propType,\n required: extractRequired(propInfo, isPartial) || undefined,\n }\n }\n\n /**\n * Creates a remark plugin that replaces TypeDocProps JSX elements with\n * Markdown tables containing component prop documentation.\n */\n propsToMarkdownList(): Plugin {\n return () => (tree, _file, done) => {\n visit(\n tree,\n \"mdxJsxFlowElement\",\n (\n node: MdxJsxFlowElement,\n index: number | undefined,\n parent: Parent | undefined,\n ) => {\n if (node?.name !== \"TypeDocProps\") {\n return\n }\n const nameAttr = node.attributes?.find(\n (attr): attr is MdxJsxAttribute =>\n attr.type === \"mdxJsxAttribute\" && attr.name === \"name\",\n )\n const isPartial = node.attributes?.some(\n (attr): attr is MdxJsxAttribute =>\n attr.type === \"mdxJsxAttribute\" && attr.name === \"partial\",\n )\n if (!this.docProps || !nameAttr) {\n if (parent && index !== undefined) {\n parent.children.splice(index, 1)\n }\n return\n }\n const propsNames = extractNamesFromAttribute(nameAttr)\n if (propsNames.length === 0) {\n if (parent && index !== undefined) {\n parent.children.splice(index, 1)\n }\n return\n }\n const propsName = propsNames[0]\n const componentProps = this.docProps.props[propsName]\n if (!componentProps) {\n if (this.verbose) {\n console.log(` TypeDocProps not found: ${propsName}`)\n }\n if (parent && index !== undefined) {\n parent.children.splice(index, 1)\n }\n return\n }\n const propTypes = this.extractProps(\n componentProps,\n Boolean(isPartial),\n )\n if (this.verbose) {\n console.log(\n ` Replaced TypeDocProps ${propsName} with API documentation`,\n )\n }\n\n const regularProps = propTypes.filter((p) => p.propType === undefined)\n const inputs = propTypes.filter((p) => p.propType === \"input\")\n const outputs = propTypes.filter((p) => p.propType === \"output\")\n\n const sections: string[] = []\n\n if (regularProps.length > 0) {\n sections.push(propsToDefinitionList(regularProps))\n }\n\n if (inputs.length > 0) {\n sections.push(`**Inputs**\\n\\n${propsToDefinitionList(inputs)}`)\n }\n\n if (outputs.length > 0) {\n sections.push(`**Outputs**\\n\\n${propsToDefinitionList(outputs)}`)\n }\n\n const markdownContent = sections.join(\"\\n\\n\")\n\n if (!markdownContent) {\n if (parent && index !== undefined) {\n parent.children.splice(index, 1)\n }\n return\n }\n\n Object.assign(node, {\n data: {typeDocProps: {name: propsName, props: propTypes}},\n lang: null,\n meta: null,\n type: \"code\",\n value: markdownContent,\n })\n },\n )\n done()\n }\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Text} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nimport {isSpoilerBlock, isStepBlock} from \"../../../remark\"\n\nexport const filterTextDirectives: Plugin = () => {\n return (tree, _file, done) => {\n visit(tree, \"text\", (node: Text) => {\n const value = node.value?.trim?.()\n if (value && (isStepBlock(value) || isSpoilerBlock(value))) {\n Object.assign(node, {\n value: ``,\n })\n }\n })\n done()\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Parent} from \"mdast\"\nimport type {MdxJsxAttribute, MdxJsxFlowElement} from \"mdast-util-mdx-jsx\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nimport {extractNamesFromAttribute} from \"../../mdx-utils\"\n\nexport const formatNpmInstallTabs: Plugin = () => {\n return (tree, _file, done) => {\n visit(\n tree,\n \"mdxJsxFlowElement\",\n (\n node: MdxJsxFlowElement,\n index: number | undefined,\n parent: Parent | undefined,\n ) => {\n if (node?.name === \"NpmInstallTabs\") {\n const packages = node.attributes?.find(\n (attr): attr is MdxJsxAttribute =>\n attr.type === \"mdxJsxAttribute\" && attr.name === \"packages\",\n )\n const packageNames = packages\n ? extractNamesFromAttribute(packages)\n : []\n\n if (packageNames.length === 0) {\n if (parent && index !== undefined) {\n parent.children.splice(index, 1)\n }\n return\n }\n\n Object.assign(node, {\n lang: \"shell\",\n meta: null,\n type: \"code\",\n value: `npm install ${packageNames.join(\" \")}`,\n })\n }\n },\n )\n done()\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {MdxJsxAttribute, MdxJsxFlowElement} from \"mdast-util-mdx-jsx\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nfunction themeDataToJson(data: unknown, cssPropertyName?: string): string {\n if (!data || typeof data !== \"object\") {\n return \"\"\n }\n\n if (cssPropertyName) {\n return JSON.stringify({cssProperty: cssPropertyName, data}, null, 2)\n }\n\n return JSON.stringify(data, null, 2)\n}\n\nfunction getPath(obj: Record<string, unknown>, path: string): unknown {\n return path\n .split(\".\")\n .reduce<unknown>(\n (acc, key) =>\n acc && typeof acc === \"object\"\n ? (acc as Record<string, unknown>)[key]\n : undefined,\n obj,\n )\n}\n\nfunction getAttrExpression(\n node: MdxJsxFlowElement,\n name: string,\n): string | null {\n const attr = node.attributes?.find(\n (a): a is MdxJsxAttribute =>\n a.type === \"mdxJsxAttribute\" && a.name === name,\n )\n if (!attr?.value) {\n return null\n }\n if (typeof attr.value === \"string\") {\n return attr.value\n } else if (typeof attr.value === \"object\" && \"value\" in attr.value) {\n return attr.value.value\n }\n return null\n}\n\n/**\n * Creates a remark plugin that replaces theme JSX elements with\n * markdown tables containing theme data from.\n */\nexport async function formatThemeNodes(): Promise<Plugin> {\n let themes: any | null = null\n try {\n // may not be available since this is an optional dependency\n themes = await import(\"@qualcomm-ui/tailwind-plugin/theme\")\n } catch {\n return () => {}\n }\n\n const handlers: Record<string, (node: MdxJsxFlowElement) => unknown> = {\n ColorTable: (node) => {\n const path = getAttrExpression(node, \"data\")\n return path && getPath(themes, path)\n },\n FontTable: (node) => {\n const path = getAttrExpression(node, \"data\")\n return path && getPath(themes, path)\n },\n SpacingTable: (node) => {\n const path = getAttrExpression(node, \"data\")\n return path && getPath(themes, path)\n },\n ThemePropertyTable: (node) => {\n const path = getAttrExpression(node, \"data\")\n const property = getAttrExpression(node, \"cssProperty\")\n const data = path && getPath(themes, path)\n return path && property ? {cssPropertyName: property, data} : undefined\n },\n }\n\n return () => (tree, _file, done) => {\n visit(tree, \"mdxJsxFlowElement\", (node: MdxJsxFlowElement) => {\n const handler = node.name && handlers[node.name]\n if (!handler) {\n return\n }\n\n const data = handler(node)\n if (!data) {\n console.warn(`No theme data for ${node.name}`)\n return\n }\n\n let markdownTable: string\n if (\n typeof data === \"object\" &&\n data !== null &&\n \"cssPropertyName\" in data &&\n \"data\" in data\n ) {\n const {cssPropertyName, data: themeData} = data as {\n cssPropertyName: string\n data: unknown\n }\n markdownTable = themeDataToJson(themeData, cssPropertyName)\n } else {\n markdownTable = themeDataToJson(data)\n }\n\n if (!markdownTable) {\n return\n }\n\n Object.assign(node, {\n lang: \"json\",\n meta: null,\n type: \"code\",\n value: markdownTable,\n })\n })\n done()\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Code, Link, Parent, Root, RootContent, Text} from \"mdast\"\nimport {toString} from \"mdast-util-to-string\"\nimport remarkGfm from \"remark-gfm\"\nimport remarkStringify from \"remark-stringify\"\nimport {type Plugin, unified} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nimport type {\n CodeExample,\n PageEntry,\n PageHeading,\n SectionEntry,\n SectionTypes,\n SimplifiedProp,\n} from \"@qualcomm-ui/mdx-common\"\n\nimport {isSpoilerBlock, isStepBlock} from \"../../remark\"\nimport {SlugGenerator, slugify} from \"../create-slug\"\n\nimport {computeMd5} from \"./utils\"\n\nexport interface SectionExtractorOptions {\n /**\n * Header depths that define section boundaries.\n * @default [1, 2, 3, 4]\n */\n depths?: number[]\n\n /**\n * Minimum content length to create a section entry.\n * @default 0\n */\n minContentLength?: number\n\n /**\n * Prefix to use for page IDs.\n */\n pageIdPrefix?: string\n}\n\nexport interface PageInfo {\n frontmatter: Record<string, unknown>\n id: string\n pathname: string\n title: string\n url?: string\n}\n\ninterface HeaderInfo {\n depth: number\n text: string\n}\n\ninterface PendingSection {\n anchorId?: string\n headerPath: string[]\n headingLevel: number\n nodes: RootContent[]\n startIndex: number\n}\n\nexport interface ExtractionResult {\n sections: SectionEntry[]\n toc: PageHeading[]\n}\n\n/**\n * Convert links to inline code. URLs are not relevant for text embeddings\n * and will muddy the vector storage.\n */\nfunction transformLinks(): Plugin {\n return () => (tree) => {\n visit(tree, \"link\", (node: Link) => {\n let text = \"\"\n visit(node, \"text\", (textNode: Text) => {\n text += textNode.value\n })\n\n Object.assign(node, {\n children: undefined,\n type: \"inlineCode\",\n url: undefined,\n value: text,\n })\n })\n }\n}\n\nconst rawProcessor = unified().use(remarkGfm).use(remarkStringify)\n\nconst contentProcessor = unified()\n .use(remarkGfm)\n .use(transformLinks())\n .use(remarkStringify)\n\n/**\n * Extracts sections from processed markdown content, organized by headers.\n */\nexport class SectionExtractor {\n private readonly depths: Set<number>\n private readonly minContentLength: number\n private readonly pageIdPrefix: string\n\n constructor(options?: SectionExtractorOptions) {\n const defaultDepths = [1, 2, 3, 4]\n this.depths = new Set(options?.depths ?? defaultDepths)\n this.minContentLength = options?.minContentLength ?? 0\n this.pageIdPrefix = options?.pageIdPrefix ?? \"\"\n }\n\n /**\n * Extracts sections from a parsed AST and generates a table of contents.\n */\n extract(tree: Root, pageInfo: PageInfo): ExtractionResult {\n const sections: SectionEntry[] = []\n const toc: PageHeading[] = []\n const headerStack: HeaderInfo[] = [{depth: 1, text: pageInfo.title}]\n const slugGenerator = new SlugGenerator()\n\n let pendingSection: PendingSection | null = null\n\n const finalizeSection = () => {\n if (!pendingSection || pendingSection.nodes.length === 0) {\n return\n }\n\n const entry = this.buildSectionEntry(pendingSection, pageInfo)\n if (entry && entry.content.length >= this.minContentLength) {\n sections.push(entry)\n }\n }\n\n for (let i = 0; i < tree.children.length; i++) {\n const node = tree.children[i]\n\n if (node.type === \"yaml\") {\n continue\n }\n\n if (node.type === \"heading\") {\n const heading = node\n\n if (!this.depths.has(heading.depth)) {\n if (pendingSection) {\n pendingSection.nodes.push(node)\n } else {\n pendingSection = {\n headerPath: headerStack.map((h) => h.text),\n headingLevel: headerStack[headerStack.length - 1]?.depth ?? 1,\n nodes: [],\n startIndex: i,\n }\n }\n continue\n }\n\n finalizeSection()\n\n while (\n headerStack.length > 0 &&\n headerStack[headerStack.length - 1].depth >= heading.depth\n ) {\n headerStack.pop()\n }\n\n const headingText = toString(heading)\n headerStack.push({depth: heading.depth, text: headingText})\n\n let anchorId: string | undefined\n // h1 headings are page titles \u2014 don't include in ToC\n if (heading.depth > 1) {\n anchorId = slugGenerator.createSlug(headingText)\n toc.push({\n headingLevel: heading.depth,\n id: anchorId,\n tagName: `h${heading.depth}`,\n textContent: headingText,\n })\n }\n\n pendingSection = {\n anchorId,\n headerPath: headerStack.map((h) => h.text),\n headingLevel: heading.depth,\n nodes: [],\n startIndex: i,\n }\n } else if (pendingSection) {\n pendingSection.nodes.push(node)\n } else {\n pendingSection = {\n headerPath: headerStack.map((h) => h.text),\n headingLevel: headerStack[headerStack.length - 1]?.depth ?? 1,\n nodes: [node],\n startIndex: i,\n }\n }\n }\n\n finalizeSection()\n\n return {sections, toc}\n }\n\n /**\n * Extracts the entire page as a single entry with full raw markdown content.\n */\n extractPage(tree: Root, pageInfo: PageInfo): PageEntry | null {\n const nodes = tree.children.filter((node) => node.type !== \"yaml\")\n\n if (nodes.length === 0) {\n return null\n }\n\n const content = this.nodesToRawContent(nodes).trim()\n\n if (!content) {\n return null\n }\n\n const hashData = {\n content,\n pageId: `${this.pageIdPrefix}${pageInfo.id}`,\n pathname: pageInfo.pathname,\n }\n const hash = computeMd5(JSON.stringify(hashData))\n\n return {\n content,\n hash,\n pageId: `${this.pageIdPrefix}${pageInfo.id}`,\n pathname: pageInfo.pathname,\n title: pageInfo.title,\n }\n }\n\n private buildSectionEntry(\n section: PendingSection,\n pageInfo: PageInfo,\n ): SectionEntry | null {\n const {nodes, terms} = this.extractTerms(section.nodes)\n\n const contentNodes: RootContent[] = []\n const codeExamples: CodeExample[] = []\n\n const sectionTypes: SectionTypes[] = []\n for (const node of nodes) {\n if (node.type === \"code\") {\n const codeNode = node as Code & {\n data?: {typeDocProps?: {name: string; props: SimplifiedProp[]}}\n }\n\n if (codeNode.data?.typeDocProps) {\n const {name, props} = codeNode.data.typeDocProps\n sectionTypes.push({props, type: name})\n }\n\n codeExamples.push({\n code: codeNode.value,\n language: codeNode.lang ?? \"\",\n })\n } else if (\n node.type === \"text\" &&\n (isStepBlock(node.value.trim()) || isSpoilerBlock(node.value.trim()))\n ) {\n // continue\n } else {\n contentNodes.push(node)\n }\n }\n\n const rawContent = this.nodesToRawContent(nodes)\n const content = this.nodesToContent(contentNodes)\n\n const sectionId = this.generateSectionId(section.headerPath)\n const url =\n pageInfo.url && section.anchorId\n ? `${pageInfo.url}#${section.anchorId}`\n : undefined\n\n const hashData = {\n headerPath: section.headerPath,\n pageFrontmatter: Object.keys(pageInfo.frontmatter).length\n ? pageInfo.frontmatter\n : undefined,\n pageId: `${this.pageIdPrefix}${pageInfo.id}`,\n rawContent: rawContent.trim(),\n terms: terms.length ? terms : undefined,\n types: sectionTypes.length ? sectionTypes : undefined,\n url,\n }\n const sectionHash = computeMd5(JSON.stringify(hashData))\n\n return {\n ...hashData,\n codeExamples: codeExamples.length ? codeExamples : undefined,\n content: content.trim(),\n hash: sectionHash,\n headingLevel: section.headingLevel,\n sectionId,\n }\n }\n\n private extractTerms(nodes: RootContent[]): {\n nodes: RootContent[]\n terms: string[]\n } {\n const filteredNodes: RootContent[] = []\n const terms: string[] = []\n\n for (const node of nodes) {\n if (node.type === \"paragraph\") {\n const children = (node as Parent).children ?? []\n const firstChild = children[0]\n if (firstChild?.type === \"text\") {\n const firstText = firstChild.value\n const termsMatch = firstText.match(/^:::\\s*terms\\s*/)\n\n if (termsMatch) {\n // Collect text from all children (handles soft breaks in multiline\n // blocks)\n let fullText = firstText\n for (let i = 1; i < children.length; i++) {\n const child = children[i] as {type: string; value?: string}\n if (child.type === \"text\") {\n fullText += child.value\n } else if (child.type === \"softBreak\") {\n fullText += \"\\n\"\n }\n }\n\n const parsedTerms = this.parseTermsBlock(fullText)\n terms.push(...parsedTerms)\n continue\n }\n }\n }\n filteredNodes.push(node)\n }\n\n return {nodes: filteredNodes, terms}\n }\n\n private parseTermsBlock(text: string): string[] {\n const afterOpen = text.replace(/^:::\\s*terms\\s*/, \"\")\n const closeIndex = afterOpen.lastIndexOf(\":::\")\n const content =\n closeIndex !== -1 ? afterOpen.slice(0, closeIndex) : afterOpen\n\n return content\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line && line !== \":::\")\n }\n\n private nodesToRawContent(nodes: RootContent[]): string {\n const tree: Root = {children: nodes, type: \"root\"}\n return rawProcessor.stringify(tree)\n }\n\n private nodesToContent(nodes: RootContent[]): string {\n const tree: Root = {children: structuredClone(nodes), type: \"root\"}\n const transformed = contentProcessor.runSync(tree) as Root\n return contentProcessor.stringify(transformed)\n }\n\n private generateSectionId(headerPath: string[]): string {\n return headerPath.map((h) => slugify(h)).join(\"-\")\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport chalk from \"chalk\"\nimport type {Root} from \"mdast\"\n\nimport type {\n NavItem,\n PageFrontmatter,\n PageMap,\n PageSection,\n SectionEntry,\n} from \"@qualcomm-ui/mdx-common\"\nimport type {QuiPropTypes} from \"@qualcomm-ui/typedoc-common\"\nimport {defined} from \"@qualcomm-ui/utils/guard\"\n\nimport type {SearchIndexerOptions} from \"./config\"\nimport {DocPropsIndexer} from \"./doc-props\"\nimport {\n buildGitMetadataMap,\n type CompiledMdxFile,\n type CompiledMdxFileMetadata,\n createRemarkProcessor,\n type IndexedPage,\n type IndexedSection,\n MdxFileReader,\n} from \"./markdown\"\nimport {\n type PageInfo,\n SectionExtractor,\n} from \"./markdown/knowledge/section-extractor\"\nimport {\n filterFileGlob,\n getCategoriesFromPathSegments,\n getPathnameFromPathSegments,\n getPathSegmentsFromFileName,\n getRouteMeta,\n NavBuilder,\n transformRouteMetaArray,\n} from \"./nav-builder\"\nimport type {RouteMetaInternal, RouteMetaNavInternal} from \"./nav-builder/types\"\nimport {fixPath} from \"./path-utils\"\n\nexport class SearchIndexer {\n private readonly docPropsIndexer: DocPropsIndexer\n private readonly sectionExtractor: SectionExtractor\n private readonly navBuilder: NavBuilder\n private readonly mdxFileReader: MdxFileReader\n private readonly allowedHeadings: Set<string>\n private readonly metaJson: RouteMetaInternal\n private readonly routeMetaNav: Record<string, RouteMetaNavInternal> = {}\n readonly config: SearchIndexerOptions\n logWarnings: boolean\n\n get cachedFileCount(): number {\n return this.mdxFileReader.cachedFileCount\n }\n\n get pageDocProps(): Record<string, Record<string, QuiPropTypes>> {\n return this._pageDocProps\n }\n private _pageDocProps: Record<string, Record<string, QuiPropTypes>> = {}\n\n get mdxFileCount(): number {\n return this._mdxFileCount\n }\n private _mdxFileCount: number = 0\n\n get navItems(): NavItem[] {\n return this.navBuilder.navItems\n }\n\n get pageMap(): PageMap {\n return this._pageMap\n }\n private _pageMap: PageMap = {}\n\n get searchIndex(): PageSection[] {\n return this._searchIndex\n }\n private _searchIndex: PageSection[] = []\n\n reset(): void {\n this.mdxFileReader.reset()\n this._pageMap = {}\n this._searchIndex = []\n }\n\n constructor(\n config: SearchIndexerOptions,\n logWarnings = true,\n // enable composition by making these classes replaceable\n addons: {\n docPropsIndexer?: DocPropsIndexer\n mdxFileReader?: MdxFileReader\n navBuilder?: NavBuilder\n sectionExtractor?: SectionExtractor\n } = {},\n ) {\n this.config = config\n this.logWarnings = logWarnings\n this.allowedHeadings = new Set<string>(\n Array.from(config?.headings || [\"h2\", \"h3\", \"h4\"]),\n )\n this.metaJson = transformRouteMetaArray(\n this.config.navConfig ?? [],\n this.routeMetaNav,\n )\n\n const headingDepths = Array.from(this.allowedHeadings).map((h) =>\n parseInt(h.charAt(1)),\n )\n this.sectionExtractor =\n addons.sectionExtractor ||\n new SectionExtractor({depths: [1, ...headingDepths]})\n this.navBuilder =\n addons.navBuilder || new NavBuilder(this.metaJson, this.routeMetaNav)\n this.docPropsIndexer =\n addons.docPropsIndexer ||\n new DocPropsIndexer(this.config.typeDocProps ?? {})\n this.mdxFileReader =\n addons.mdxFileReader ||\n new MdxFileReader(\n process.env.NODE_ENV === \"development\" && !this.config.disableCache,\n this.config.pageTimestampMetadata,\n )\n }\n\n /**\n * Resolves a page's properties from the combined frontmatter and RouteMeta.\n * RouteMeta properties take precedence.\n */\n private getPageEntry(\n filepath: string,\n frontmatter: Partial<PageFrontmatter>,\n ): PageSection {\n const pagePath = filepath.replace(this.config.srcDir, \"\")\n\n const pathSegments = getPathSegmentsFromFileName(\n pagePath,\n this.config.pageDirectory,\n this.config.routingStrategy,\n )\n\n const pathname = getPathnameFromPathSegments(pathSegments)\n\n const routeMeta =\n getRouteMeta(\n pathSegments.length === 0\n ? frontmatter.id\n ? [frontmatter.id]\n : [\"_index\"]\n : pathSegments,\n this.metaJson,\n ) ?? {}\n\n return {\n categories:\n frontmatter.categories ??\n getCategoriesFromPathSegments(\n pathSegments,\n this.metaJson,\n routeMeta?.title || frontmatter.title || \"\",\n ),\n data: frontmatter,\n description: frontmatter.description,\n hidden: defined(routeMeta.hidden) ? routeMeta.hidden : frontmatter.hidden,\n hideBreadcrumbs: defined(routeMeta.hideBreadcrumbs)\n ? routeMeta.hideBreadcrumbs\n : frontmatter.hideBreadcrumbs,\n hideFromSearch: defined(routeMeta.hideFromSearch)\n ? routeMeta.hideFromSearch\n : frontmatter.hideFromSearch,\n hidePageLinks: defined(routeMeta.hidePageLinks)\n ? routeMeta.hidePageLinks\n : frontmatter.hidePageLinks,\n hideSideNav: defined(routeMeta.hideSideNav)\n ? routeMeta.hideSideNav\n : frontmatter.hideSideNav,\n hideToc: defined(routeMeta.hideToc)\n ? routeMeta.hideToc\n : frontmatter.hideToc,\n id: pagePath,\n pathname,\n pathSegments,\n restricted: defined(routeMeta.restricted)\n ? routeMeta.restricted\n : frontmatter.restricted,\n title: defined(routeMeta.title)\n ? routeMeta.title || \"\"\n : frontmatter.title || \"\",\n updatedBy: frontmatter.updatedBy,\n updatedOn: frontmatter.updatedOn,\n }\n }\n\n /**\n * Parses an MDX file to extract the site data for the nav items, doc props,\n * breadcrumbs, and search index.\n */\n private compileMdxFile(filePath: string): CompiledMdxFile {\n const {cached, fileContents, frontmatter} =\n this.mdxFileReader.readFileSync(filePath)\n\n const metadata: CompiledMdxFileMetadata = {\n changed: {},\n filePath,\n }\n\n let previousPage: IndexedPage | undefined = undefined\n\n if (!cached) {\n const previousData = this.mdxFileReader.readCache(filePath)\n if (previousData) {\n const cachedFm = JSON.stringify(previousData.frontmatter)\n const currentFm = JSON.stringify(frontmatter)\n previousPage = previousData.page\n if (cachedFm !== currentFm) {\n metadata.changed.frontmatter = true\n }\n }\n }\n\n this.docPropsIndexer.reset()\n\n const defaultSection: PageSection = this.getPageEntry(filePath, frontmatter)\n if (!defaultSection.categories.length && defaultSection.title) {\n defaultSection.categories = [defaultSection.title]\n }\n\n if (!defaultSection.hidden) {\n this.navBuilder.add(defaultSection, frontmatter)\n }\n\n this._pageMap[defaultSection.pathname] = defaultSection\n\n let indexedPage: IndexedPage\n\n try {\n if (cached?.page) {\n indexedPage = cached.page\n } else {\n const processor = createRemarkProcessor({\n alerts: true,\n extractMeta: {},\n frontmatter: true,\n gfm: true,\n interpolateFrontmatter: frontmatter,\n mdx: true,\n removeJsx: true,\n removeMermaidCodeBlocks: true,\n })\n const tree = processor.runSync(processor.parse(fileContents)) as Root\n const pageInfo: PageInfo = {\n frontmatter: frontmatter as unknown as Record<string, unknown>,\n id: defaultSection.id,\n pathname: defaultSection.pathname,\n title: defaultSection.title,\n url: defaultSection.pathname,\n }\n const {sections, toc} = this.sectionExtractor.extract(tree, pageInfo)\n indexedPage = {sections, toc}\n }\n } catch (error: any) {\n console.debug(\n `${chalk.yellowBright.bold(\n \"Failed to parse mdx page content.\",\n )} ${chalk.blueBright.bold(filePath)}`,\n )\n\n if (this.config.throwOnError) {\n throw new Error(error)\n }\n\n return {metadata, pageSections: [defaultSection]}\n }\n\n const {sections, toc} = indexedPage\n\n if (previousPage) {\n for (let i = 0; i < toc.length; i++) {\n const previousHeading = previousPage.toc[i]\n const currentHeading = toc[i]\n if (previousHeading?.id !== currentHeading.id) {\n metadata.changed.toc = true\n break\n }\n }\n }\n\n if (toc.length) {\n this._pageMap[defaultSection.pathname].toc = toc\n }\n\n let docPropSections: IndexedSection[] = []\n let docProps: Record<string, QuiPropTypes> = {}\n\n if (this.config.typeDocProps) {\n docPropSections =\n cached?.pageDocPropSections ||\n (this.docPropsIndexer.build(fileContents, toc) ?? [])\n docProps = cached?.pageDocProps || this.docPropsIndexer.getDocProps()\n }\n\n if (docPropSections.length) {\n this._pageDocProps[defaultSection.pathname] = docProps\n }\n\n if (!cached) {\n this.mdxFileReader.updateCache(filePath, fileContents, {\n frontmatter,\n page: indexedPage,\n pageDocProps: docProps,\n pageDocPropSections: docPropSections,\n })\n }\n\n // omit entries from pages that are explicitly omitted from the index.\n if (frontmatter.hideFromSearch) {\n return {metadata, pageSections: [defaultSection]}\n }\n\n if (!sections.length && !docPropSections.length) {\n return {metadata, pageSections: [defaultSection]}\n }\n\n const sectionReturn: PageSection[] = [\n ...this.formatContentSections(sections, defaultSection),\n ]\n\n if (this.config.typeDocPropsOptions?.includeInSearchIndex) {\n sectionReturn.push(\n ...this.formatDocPropSections(docPropSections, defaultSection),\n )\n }\n\n return {metadata, pageSections: sectionReturn}\n }\n\n private formatContentSections(\n sections: SectionEntry[],\n {toc: _toc, ...defaultSection}: PageSection,\n ): PageSection[] {\n return sections.map((section, index): PageSection => {\n const heading = section.headerPath.at(-1) ?? defaultSection.title\n return {\n ...defaultSection,\n content: section.content || undefined,\n heading,\n headingLevel: section.headingLevel,\n href: section.url ?? defaultSection.pathname,\n id: `${defaultSection.id}-${index}`,\n }\n })\n }\n\n private formatDocPropSections(\n sections: IndexedSection[],\n {toc: _toc, ...defaultSection}: PageSection,\n ): PageSection[] {\n return sections.map((section, index): PageSection => {\n const content = section.content.map((c) => c.text.join(\" \")).join(\" \")\n return {\n ...defaultSection,\n content: content || undefined,\n heading: section.heading?.textContent ?? defaultSection.title,\n headingLevel: section.heading?.headingLevel,\n href: section.heading\n ? `${defaultSection.pathname}#${section.heading.id}`\n : defaultSection.pathname,\n id: `${defaultSection.id}-${index}-prop`,\n isDocProp: true,\n }\n })\n }\n\n private compileTsxFile(filepath: string) {\n const entry = this.getPageEntry(filepath, {})\n\n const routeMeta = getRouteMeta(\n entry.pathSegments.length === 0 ? [\"_index\"] : entry.pathSegments,\n this.metaJson,\n )\n\n if (!routeMeta) {\n return null\n }\n\n if (!entry.hidden) {\n this.navBuilder.add(entry, {}, routeMeta)\n }\n\n this._pageMap[entry.pathname] = entry\n\n return entry\n }\n\n buildIndex(\n inputFileGlob: string[],\n logWarnings: boolean = true,\n ): CompiledMdxFile[] {\n this.logWarnings = logWarnings\n this.mdxFileReader.logWarnings = logWarnings\n // Windows path fix\n const fileGlob = inputFileGlob.map(fixPath)\n this.navBuilder.reset()\n this.reset()\n\n const mdxFileGlob = filterFileGlob(\n fileGlob,\n \"mdx\",\n this.config.srcDir,\n this.config.routingStrategy,\n )\n\n this._mdxFileCount = mdxFileGlob.length\n if (\n !this.mdxFileReader.enabled ||\n this.mdxFileReader.gitMetadataMap.size === 0\n ) {\n this.mdxFileReader.gitMetadataMap = buildGitMetadataMap(\n this.config.srcDir,\n this.mdxFileReader.pageTimestampMetadata,\n )\n }\n\n const compiledFiles = mdxFileGlob.map((file) => this.compileMdxFile(file))\n\n const mdxIndex = compiledFiles\n .map((fileData) => fileData.pageSections)\n .flat()\n\n filterFileGlob(\n fileGlob,\n \"tsx\",\n this.config.srcDir,\n this.config.routingStrategy,\n ).map((file) => this.compileTsxFile(file))\n\n this._searchIndex.push(...mdxIndex.filter((entry) => !entry.hideFromSearch))\n\n this.navBuilder.build()\n\n return compiledFiles\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {MdxJsxAttribute} from \"mdast-util-mdx-jsx\"\nimport remarkMdx from \"remark-mdx\"\nimport remarkParse from \"remark-parse\"\nimport remarkStringify from \"remark-stringify\"\nimport {type Plugin, unified} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nimport {\n type PageDocProps,\n type PageHeading,\n type PagePropType,\n UniqueIdService,\n} from \"@qualcomm-ui/mdx-common\"\nimport type {\n QuiPropDeclaration,\n QuiPropTypes,\n} from \"@qualcomm-ui/typedoc-common\"\n\nimport {extractNamesFromAttribute, type IndexedSection} from \"../markdown\"\n\nfunction extractPickPropsRecord(\n node: MdxJsxAttribute,\n): Record<string, string[]> | null {\n if (\n node.name !== \"unionWithPick\" ||\n !node.value ||\n typeof node.value === \"string\"\n ) {\n return null\n }\n\n const estree = node.value.data?.estree\n if (!estree?.body?.[0] || estree.body[0].type !== \"ExpressionStatement\") {\n return null\n }\n\n const expression = estree.body[0].expression\n if (expression.type !== \"ObjectExpression\") {\n return null\n }\n\n const result: Record<string, string[]> = {}\n\n for (const property of expression.properties) {\n if (property.type !== \"Property\" || property.key.type !== \"Identifier\") {\n continue\n }\n\n if (property.value.type !== \"ArrayExpression\") {\n continue\n }\n\n const key = property.key.name\n const values: string[] = []\n\n for (const element of property.value.elements) {\n if (element?.type === \"Literal\" && typeof element.value === \"string\") {\n values.push(element.value)\n }\n }\n\n result[key] = values\n }\n\n return result\n}\n\nconst targetMdxElements: string[] = [\n \"TypeDocProps\",\n \"TypeDocAttributes\",\n \"TypeDocAngularAttributes\",\n]\n\ninterface DocPropEntry {\n name: string\n omitFrom?: string[]\n}\n\nexport class DocPropsIndexer {\n docPropsEntries: DocPropEntry[] = []\n idService: UniqueIdService = new UniqueIdService()\n private readonly props: Record<string, QuiPropTypes>\n private pageDocProps: PageDocProps = {}\n\n constructor(props: Record<string, QuiPropTypes>) {\n this.props = props\n }\n\n reset(): void {\n this.idService.reset()\n this.docPropsEntries = []\n }\n\n /**\n * Finds all JSX `<TypeDocProps />` nodes on the current page and adds their names\n * to an array. Once all nodes have been collected, we process them into\n * `PageSection` entries for the search index.\n */\n getTypeDocPropsNodes: Plugin = () => {\n return (tree, _file, done) => {\n visit(tree, \"mdxJsxFlowElement\", (node: any) => {\n if (node && \"name\" in node && targetMdxElements.includes(node.name)) {\n const nameAttr = node.attributes?.find(\n (attr: MdxJsxAttribute) => attr.name === \"name\",\n )\n const omitFromAttr = node.attributes?.find(\n (attr: MdxJsxAttribute) => attr.name === \"omitFrom\",\n )\n const omitFrom = omitFromAttr\n ? extractNamesFromAttribute(omitFromAttr)\n : undefined\n\n if (nameAttr) {\n const names = extractNamesFromAttribute(nameAttr)\n for (const name of names) {\n this.docPropsEntries.push({name, omitFrom})\n if (name.endsWith(\"Props\")) {\n // also index the corresponding component for lookup on this page.\n this.docPropsEntries.push({name: name.slice(0, -5), omitFrom})\n }\n }\n }\n\n const unionWithPickAttr: MdxJsxAttribute = node.attributes?.find(\n (attr: MdxJsxAttribute) => attr.name === \"unionWithPick\",\n )\n if (unionWithPickAttr) {\n try {\n const unionWithPick = extractPickPropsRecord(unionWithPickAttr)\n if (unionWithPick) {\n this.docPropsEntries.push(\n ...Object.keys(unionWithPick).map((entry) => ({\n name: entry,\n omitFrom,\n })),\n )\n }\n } catch (e) {}\n }\n }\n })\n done()\n }\n }\n\n build(fileContents: string, toc: PageHeading[]): IndexedSection[] | null {\n // parse the Markdown into an AST\n unified()\n .use(remarkMdx)\n // find the TypeDocProp nodes\n .use(this.getTypeDocPropsNodes)\n .use(remarkParse)\n .use(remarkStringify)\n .processSync(fileContents)\n\n if (!this.docPropsEntries.length) {\n return null\n }\n\n for (const item of toc) {\n this.idService.add(item.id)\n }\n\n return this.docPropsEntries\n .map((entry): IndexedSection[] => {\n const propTypes = this.props[entry.name]\n if (!propTypes) {\n return []\n }\n\n const omittedProps = new Set<string>(\n (entry.omitFrom ?? [])\n .map((entry) => {\n const propTypes = this.props[entry]\n if (!propTypes) {\n return []\n }\n return [\n propTypes.props,\n propTypes.input,\n propTypes.output,\n propTypes.publicMethods,\n ].reduce((acc: string[], current) => {\n if (current) {\n acc.push(...current.map((prop) => prop.name))\n }\n return acc\n }, [])\n })\n .flat(1)\n .filter(Boolean),\n )\n\n const sections: IndexedSection[] = []\n\n const assembleProps = (\n propsInput: QuiPropDeclaration[] | undefined,\n ): PagePropType[] | undefined => {\n if (!propsInput) {\n return undefined\n }\n const props: PagePropType[] = []\n for (const prop of propsInput) {\n if (omittedProps.has(prop.name)) {\n continue\n }\n const id = this.idService.add(prop.name)\n props.push({...prop, id})\n sections.push(this.assembleProp(prop, id))\n }\n return props\n }\n\n this.pageDocProps[entry.name] = {\n ...this.props[entry.name],\n input: assembleProps(propTypes.input),\n output: assembleProps(propTypes.output),\n props: assembleProps(propTypes.props),\n publicMethods: assembleProps(propTypes.publicMethods),\n }\n return sections\n })\n .flat()\n }\n\n getDocProps(): PageDocProps {\n return this.docPropsEntries.reduce((acc: PageDocProps, entry) => {\n const propTypes = this.pageDocProps[entry.name]\n // TODO: convert code comments to HTML using rehype. Remove markdown-to-jsx\n // in @qualcomm-ui/react-mdx library.\n if (propTypes) {\n acc[entry.name] = propTypes\n }\n return acc\n }, {})\n }\n\n private assembleProp(prop: QuiPropDeclaration, id: string): IndexedSection {\n const name = prop.name\n\n const heading: PageHeading = {\n headingLevel: 4,\n id,\n tagName: \"a\",\n textContent: name,\n }\n\n const comment = prop.comment\n if (!comment) {\n return {content: [], heading}\n }\n\n const content = {\n tagName: \"p\",\n text: [\n comment.summary\n .map((entry) => entry.text.replaceAll(\"\\n\", \" \"))\n .join(\"\"),\n ],\n }\n return {content: [content], heading}\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport rehypeShiki, {type RehypeShikiOptions} from \"@shikijs/rehype\"\nimport {\n transformerNotationDiff,\n transformerNotationErrorLevel,\n transformerNotationFocus,\n transformerNotationHighlight,\n transformerNotationWordHighlight,\n transformerRemoveNotationEscape,\n transformerRenderIndentGuides,\n} from \"@shikijs/transformers\"\nimport {merge} from \"lodash-es\"\nimport type {ShikiTransformer} from \"shiki\"\nimport type {PluggableList} from \"unified\"\n\nimport {quiCustomDarkTheme} from \"@qualcomm-ui/mdx-common\"\n\nimport {\n rehypeMdxCodeProps,\n remarkFrontmatter,\n remarkGfm,\n remarkMdxFrontmatter,\n} from \"../exports\"\n\nimport {ConfigLoader, type ConfigLoaderOptions} from \"./config\"\nimport {rehypeSectionize, rehypeSlug, type RehypeSlugOptions} from \"./rehype\"\nimport {\n remarkAlerts,\n remarkCodeTabs,\n remarkFrontmatterDescription,\n remarkFrontmatterTitle,\n remarkSpoilers,\n remarkSteps,\n} from \"./remark\"\nimport {remarkExtractMeta} from \"./remark/remark-extract-meta\"\nimport {transformerCodeAttribute, transformerNotationHidden} from \"./shiki\"\n\nexport interface QuiRehypePluginOptions extends ConfigLoaderOptions {\n rehypeShikiOptions?: Partial<RehypeShikiOptions>\n}\n\nexport function getShikiTransformers(): ShikiTransformer[] {\n return [\n transformerNotationDiff(),\n transformerNotationFocus(),\n transformerNotationHighlight(),\n transformerNotationWordHighlight(),\n transformerNotationErrorLevel(),\n transformerNotationHidden(),\n transformerRenderIndentGuides(),\n transformerRemoveNotationEscape(),\n ]\n}\n\n/**\n * Used to retrieve all the rehype plugins required for QUI Docs MDX.\n * These should be passed to the `mdx` vite plugin from\n */\nexport function getRehypePlugins(\n options: QuiRehypePluginOptions = {},\n): PluggableList {\n const config = new ConfigLoader(options).loadConfig()\n return [\n [rehypeMdxCodeProps, {enforce: \"pre\"}],\n [\n rehypeSlug,\n {allowedHeadings: config.headings} satisfies RehypeSlugOptions,\n ],\n rehypeSectionize,\n [\n rehypeShiki,\n merge(\n {\n defaultColor: \"light-dark()\",\n fallbackLanguage: \"text\",\n themes: {\n dark: quiCustomDarkTheme,\n light: \"github-light-high-contrast\",\n },\n transformers: [...getShikiTransformers(), transformerCodeAttribute()],\n } satisfies RehypeShikiOptions,\n options.rehypeShikiOptions,\n ),\n ],\n ]\n}\n\n/**\n * @returns every remark plugin needed for QUI Docs MDX.\n *\n * @example\n * ```ts\n * // in your vite config\n * plugins: [\n * mdx({\n * providerImportSource: \"@mdx-js/react\",\n * rehypePlugins: [...getRehypePlugins()],\n * remarkPlugins: [...getRemarkPlugins()],\n * }),\n * quiDocsPlugin(),\n * // ... the rest of your plugins\n * ]\n * ```\n */\nexport function getRemarkPlugins(): PluggableList {\n return [\n remarkFrontmatter,\n remarkMdxFrontmatter,\n remarkGfm,\n remarkAlerts,\n remarkCodeTabs,\n remarkFrontmatterTitle,\n remarkFrontmatterDescription,\n remarkSpoilers,\n remarkSteps,\n remarkExtractMeta,\n ]\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport rehypeMdxCodeProps from \"rehype-mdx-code-props\"\nimport remarkFrontmatter from \"remark-frontmatter\"\nimport remarkGfm from \"remark-gfm\"\nimport remarkMdxFrontmatter from \"remark-mdx-frontmatter\"\n\nimport {rehypeSlug} from \"./docs-plugin/rehype/rehype-slug\"\n\n// Re-export these peerDependencies for more convenient imports.\n// Some of these are not included in the bundled JS, so the user must install them\n// separately.\nexport {\n remarkFrontmatter,\n remarkGfm,\n remarkMdxFrontmatter,\n rehypeMdxCodeProps,\n rehypeSlug,\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Root} from \"hast\"\nimport {headingRank} from \"hast-util-heading-rank\"\nimport {toString} from \"hast-util-to-string\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nimport {SlugGenerator} from \"../markdown/create-slug\"\n\nexport interface RehypeSlugOptions {\n /**\n * @default ['h2', 'h3', 'h4']\n */\n allowedHeadings?: string[]\n prefix?: string\n}\n\nconst emptyOptions: RehypeSlugOptions = {}\n\n/**\n * Converts heading text to URL-friendly slugs. Converts multi-word and PascalCase\n * text to kebab-case. Lowercases single sentence-case words. Appends counter for\n * duplicate slugs.\n */\nexport const rehypeSlug: Plugin<[RehypeSlugOptions?], Root> = (\n options: RehypeSlugOptions | null | undefined,\n) => {\n const settings = options || emptyOptions\n const prefix = settings.prefix || \"\"\n const allowedHeadings = new Set<string>(\n settings.allowedHeadings || [\"h2\", \"h3\", \"h4\"],\n )\n const slugGenerator = new SlugGenerator()\n\n return (tree) => {\n slugGenerator.reset()\n visit(tree, \"element\", function (node) {\n if (\n headingRank(node) &&\n !node.properties.id &&\n allowedHeadings.has(node.tagName)\n ) {\n node.properties.id = prefix + slugGenerator.createSlug(toString(node))\n }\n })\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Element, Root, RootContent} from \"hast\"\nimport {heading} from \"hast-util-heading\"\nimport {headingRank} from \"hast-util-heading-rank\"\nimport type {Properties} from \"hastscript\"\nimport type {Plugin} from \"unified\"\n\nexport type RehypeSectionizeOptions = {\n enableRootSection?: boolean | undefined\n idPropertyName?: string | undefined\n properties?: Properties | undefined\n rankPropertyName?: string | undefined\n}\n\nconst defaultOptions: Required<RehypeSectionizeOptions> = {\n enableRootSection: false,\n idPropertyName: \"ariaLabelledby\",\n properties: {},\n rankPropertyName: \"dataHeadingRank\",\n}\n\nconst wrappingRank = (\n rootContent: RootContent | undefined,\n rankPropertyName: RehypeSectionizeOptions[\"rankPropertyName\"],\n) => {\n if (\n rootContent == null ||\n rankPropertyName == null ||\n !(\"properties\" in rootContent)\n ) {\n throw new Error(\"rootContent and rankPropertyName must have value\")\n }\n\n const rank = rootContent.properties?.[rankPropertyName]\n if (typeof rank !== \"number\") {\n throw new Error(`rankPropertyName(${rankPropertyName}) must be number`)\n }\n\n return rank\n}\n\nconst createElement = (\n rank: number,\n options: Pick<\n RehypeSectionizeOptions,\n \"properties\" | \"rankPropertyName\" | \"idPropertyName\"\n >,\n children: Element[] = [],\n) => {\n const {idPropertyName, properties, rankPropertyName} = options\n\n if (\n properties != null &&\n rankPropertyName != null &&\n rankPropertyName in properties\n ) {\n throw new Error(\n `rankPropertyName(${rankPropertyName}) dataHeadingRank must exist`,\n )\n }\n\n const id = children.at(0)?.properties?.id\n const element: Element = {\n children,\n properties: {\n className: [\"heading\"],\n ...(rankPropertyName ? {[rankPropertyName]: rank} : {}),\n ...(idPropertyName && typeof id === \"string\"\n ? {[idPropertyName]: id}\n : {}),\n ...(properties ? properties : {}),\n },\n tagName: \"section\",\n type: \"element\",\n }\n\n return element\n}\n\nexport const rehypeSectionize: Plugin<[RehypeSectionizeOptions?], Root> = (\n options = defaultOptions,\n) => {\n const {enableRootSection, ...rest} = {\n enableRootSection:\n options.enableRootSection ?? defaultOptions.enableRootSection,\n idPropertyName: options.idPropertyName ?? defaultOptions.idPropertyName,\n properties: options.properties ?? defaultOptions.properties,\n rankPropertyName:\n options.rankPropertyName ?? defaultOptions.rankPropertyName,\n }\n\n return (root) => {\n const rootWrapper = createElement(0, rest)\n\n const wrapperStack: RootContent[] = []\n wrapperStack.push(rootWrapper)\n\n const lastStackItem = () => {\n const last = wrapperStack.at(-1)\n if (last == null || last.type !== \"element\") {\n throw new Error(\"lastStackItem must be Element\")\n }\n return wrapperStack.at(-1) as Element\n }\n\n for (const rootContent of root.children) {\n if (heading(rootContent)) {\n const rank = headingRank(rootContent)\n if (rank == null) {\n throw new Error(\"heading or headingRank is not working\")\n }\n\n if (rank > wrappingRank(lastStackItem(), rest.rankPropertyName)) {\n const childWrapper = createElement(rank, rest, [rootContent])\n lastStackItem().children.push(childWrapper)\n wrapperStack.push(childWrapper)\n } else if (\n rank <= wrappingRank(lastStackItem(), rest.rankPropertyName)\n ) {\n while (rank <= wrappingRank(lastStackItem(), rest.rankPropertyName)) {\n wrapperStack.pop()\n }\n const siblingWrapper = createElement(rank, rest, [rootContent])\n\n lastStackItem().children.push(siblingWrapper)\n wrapperStack.push(siblingWrapper)\n }\n } else {\n if (rootContent.type === \"doctype\") {\n throw new Error(\"must be used in a fragment\")\n }\n lastStackItem().children.push(rootContent as any)\n }\n }\n\n return {\n ...root,\n children: enableRootSection ? [rootWrapper] : rootWrapper.children,\n }\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nexport function removeCodeAnnotations(code: string): string {\n const hideAnnotationRegex = /\\/\\/\\s*\\[!code\\s+hide(?::\\d+)?\\]/\n const lineAnnotationRegex = /\\/\\/\\s*\\[!code\\s*(?:\\S.*)?\\]/\n const jsxBlockAnnotationRegex = /\\{\\s*\\/\\*\\s*\\[!code(?:\\s+\\S+)?\\]\\s*\\*\\/\\s*\\}/\n const htmlAnnotationRegex = /<!--\\s*\\[!code(?:\\s+\\S+)?\\]\\s*-->/\n const blockAnnotationRegex = /\\/\\*\\s*\\[!code(?:\\s+\\S+)?\\]\\s*\\*\\/\\s*/\n const inlineIncrementRegex = /(?:\\/\\/\\s*)?\\[!code \\+\\+\\]/\n\n function stripAnnotations(line: string): {\n hasHideAnnotation: boolean\n processed: string\n touched: boolean\n } {\n let processed = line\n let touched = false\n const hasHideAnnotation = hideAnnotationRegex.test(line)\n\n const patterns = [\n inlineIncrementRegex,\n jsxBlockAnnotationRegex,\n htmlAnnotationRegex,\n blockAnnotationRegex,\n lineAnnotationRegex,\n ]\n\n for (const pattern of patterns) {\n const next = processed.replace(pattern, \"\")\n if (next !== processed) {\n touched = true\n processed = next\n }\n }\n\n return {hasHideAnnotation, processed, touched}\n }\n\n return code\n .split(\"\\n\")\n .map(stripAnnotations)\n .filter(({hasHideAnnotation, processed, touched}) => {\n if (hasHideAnnotation) {\n return false\n }\n\n const processedIsBlank = !processed.trim()\n if (touched && processedIsBlank) {\n return false\n }\n\n return true\n })\n .map(({processed}) => processed)\n .join(\"\\n\")\n}\n\nexport function extractPreviewFromHighlightedHtml(\n highlightedHtml: string,\n): string | null {\n const preMatch = highlightedHtml.match(/<pre((?:\\s+[\\w-]+=\"[^\"]*\")*)>/)\n const codeMatch = highlightedHtml.match(/<code([^>]*)>(.*?)<\\/code>/s)\n\n if (!preMatch || !codeMatch) {\n return null\n }\n const codeContent = codeMatch[2]\n const parts = codeContent.split(/<span class=\"line/)\n const previewLineParts = parts\n .slice(1)\n .filter((part) => part.includes('data-preview-line=\"true\"'))\n\n // strip indentation\n const indents = previewLineParts.map((part) => {\n const indentMatches =\n part.match(/<span class=\"indent\">(.+?)<\\/span>/g) || []\n let total = 0\n for (const match of indentMatches) {\n const content = match.match(/<span class=\"indent\">(.+?)<\\/span>/)\n if (content) {\n total += content[1].length\n } else {\n break\n }\n }\n return total\n })\n\n const minIndent = Math.min(...indents.filter((n) => n > 0))\n const previewLines = previewLineParts.map((part) => {\n let processed = `<span class=\"line${part}`\n let remaining = minIndent\n while (remaining > 0 && processed.includes('<span class=\"indent\">')) {\n const before = processed\n processed = processed.replace(\n /<span class=\"indent\">(.+?)<\\/span>/,\n (match, spaces) => {\n if (spaces.length <= remaining) {\n remaining -= spaces.length\n return \"\"\n } else {\n const kept = spaces.substring(remaining)\n remaining = 0\n return `<span class=\"indent\">${kept}</span>`\n }\n },\n )\n if (before === processed) {\n break\n }\n }\n return processed\n })\n return `<pre${preMatch[1]}><code${codeMatch[1]}>${previewLines.join(\"\")}</code></pre>`\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {ShikiTransformer} from \"shiki\"\n\nimport {removeCodeAnnotations} from \"./utils\"\n\nexport interface TransformerCodeAttributeOptions {\n /**\n * The name of the attribute to add to the pre element. Supply as `null` to\n * disable.\n *\n * @default 'data-code'\n */\n attributeName?: string | null\n\n /**\n * Custom formatter for the source code.\n */\n formatter?: (code: string) => string\n\n /**\n * Callback fired when file processing is complete.\n */\n onComplete?: (codeWithoutSnippets: string) => void\n}\n\n/**\n * Adds a `data-code` attribute to the `<pre>` element with the code contents,\n * removing any code annotations and unused lines from transformers like\n * `transformerNotationDiff`.\n */\nexport function transformerCodeAttribute(\n opts: TransformerCodeAttributeOptions = {attributeName: \"data-code\"},\n): ShikiTransformer {\n return {\n enforce: \"post\",\n name: \"shiki-transformer-code-attribute\",\n pre(node) {\n const strippedSource = removeCodeAnnotations(this.source)\n const formattedSource = opts.formatter?.(strippedSource) ?? strippedSource\n if (opts.attributeName !== null) {\n node.properties[opts.attributeName ?? \"data-code\"] = formattedSource\n }\n opts.onComplete?.(formattedSource)\n },\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {ShikiTransformer} from \"shiki\"\n\n/**\n * Use `[!code hide]` notation in code to mark lines as hidden.\n */\nexport function transformerNotationHidden(): ShikiTransformer {\n return {\n name: \"shiki-transformer-notation-hidden\",\n preprocess(code) {\n const lines = code.split(\"\\n\")\n const resultLines: string[] = []\n let hideNextCount = 0\n\n for (const rawLine of lines) {\n const line = rawLine\n const match = line.match(/\\[!code\\s+hide(?::(\\d+))?\\]/)\n\n if (match) {\n const before = line.slice(0, match.index ?? 0)\n const after = line.slice((match.index ?? 0) + match[0].length)\n\n const count = match[1] ? Number(match[1]) : 1\n const validCount = Number.isFinite(count) && count > 0 ? count : 0\n\n const beforeIsOnlyCommentOrWhitespace =\n before.trim() === \"\" || /^[\\s/]*$/.test(before)\n const afterIsEmpty = after.trim() === \"\"\n\n const markerIsStandalone =\n beforeIsOnlyCommentOrWhitespace && afterIsEmpty\n\n if (markerIsStandalone) {\n hideNextCount += validCount\n continue\n }\n\n // inline marker \u2192 hide this line only\n continue\n }\n\n if (hideNextCount > 0) {\n hideNextCount -= 1\n continue\n }\n\n resultLines.push(line)\n }\n\n return resultLines.join(\"\\n\").trim()\n },\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {ShikiTransformer} from \"shiki\"\n\nimport {dedent} from \"@qualcomm-ui/utils/dedent\"\n\nimport {removeCodeAnnotations} from \"./utils\"\n\nexport type PreviewDisplayMode = \"only-preview\" | \"full-code\"\n\nexport interface PreviewBlockTransformerOptions {\n /**\n * The name of the attribute to add to the pre element. Supply as `null` to\n * disable.\n *\n * @default 'data-preview'\n */\n attributeName?: string | null\n\n /**\n * @option 'full-code': keep the full code (with preview markers removed) as the rendered snippet.\n * @option 'preview-only': render only the extracted preview block as the snippet\n *\n * In all cases the preview block is extracted and attached to `data-preview`.\n *\n * @default 'full-code'\n */\n displayMode?: PreviewDisplayMode\n\n /**\n * Callback fired when file processing is complete.\n */\n onComplete?: (extractedPreview: string | null) => void\n}\n\nexport function isPreviewLine(trimmedLine: string): boolean {\n return (\n trimmedLine === \"// preview\" ||\n /^\\{\\s*\\/\\*\\s*preview\\s*\\*\\/\\s*\\}$/.test(trimmedLine) ||\n /^<!--\\s*preview\\s*-->$/.test(trimmedLine)\n )\n}\n\nexport function transformerPreviewBlock(\n options: PreviewBlockTransformerOptions = {\n displayMode: \"full-code\",\n },\n): ShikiTransformer {\n let previewContent: string | null = null\n let previewStartLine = -1\n let previewEndLine = -1\n let currentLine = 0\n\n return {\n enforce: \"post\",\n line(node) {\n if (currentLine >= previewStartLine && currentLine <= previewEndLine) {\n node.properties[\"data-preview-line\"] = \"true\"\n }\n currentLine++\n },\n name: \"transformer-preview-block\",\n pre(node) {\n const content = previewContent\n ? removeCodeAnnotations(previewContent)\n : null\n if (content && options.attributeName != null) {\n node.properties[options.attributeName] = content\n }\n options.onComplete?.(content || null)\n },\n preprocess(code) {\n previewContent = null\n currentLine = 0\n previewStartLine = -1\n previewEndLine = -1\n\n const lines = code.split(\"\\n\")\n const resultLines: string[] = []\n const previewLines: string[] = []\n let inPreview = false\n let foundPreview = false\n let outputLineIndex = 0\n\n for (const line of lines) {\n const trimmed = line.trim()\n if (isPreviewLine(trimmed)) {\n if (!inPreview) {\n inPreview = true\n foundPreview = true\n previewStartLine = outputLineIndex\n } else {\n inPreview = false\n previewEndLine = outputLineIndex - 1\n }\n continue\n }\n resultLines.push(line)\n if (inPreview) {\n previewLines.push(line)\n }\n outputLineIndex++\n }\n\n if (foundPreview) {\n previewContent = dedent(previewLines.join(\"\\n\").trim())\n if (options.displayMode === \"only-preview\") {\n return previewContent\n }\n }\n return resultLines.join(\"\\n\").trim()\n },\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Element, Root, Text} from \"hast\"\nimport {fromHtml} from \"hast-util-from-html\"\nimport {toHtml} from \"hast-util-to-html\"\nimport {readFile} from \"node:fs/promises\"\nimport postcss, {type Rule} from \"postcss\"\nimport selectorParser from \"postcss-selector-parser\"\nimport type {ShikiTransformer} from \"shiki\"\nimport {compile} from \"tailwindcss\"\nimport {visit} from \"unist-util-visit\"\n\nimport {camelCase} from \"@qualcomm-ui/utils/change-case\"\n\ndeclare const createRequire: NodeRequire\n\nasync function loadStylesheetContent(id: string): Promise<string> {\n const resolveId = id === \"tailwindcss\" ? \"tailwindcss/index.css\" : id\n\n let resolvedPath: string\n if (typeof createRequire !== \"undefined\") {\n resolvedPath = createRequire(import.meta.url).resolve(resolveId)\n } else {\n const createRequire = await import(\"node:module\").then(\n (module) => module.createRequire,\n )\n resolvedPath = createRequire(import.meta.url).resolve(resolveId)\n }\n return readFile(resolvedPath, \"utf-8\")\n}\n\nfunction getClassValue(node: Element): string | null {\n const val = node.properties?.className ?? node.properties?.class\n if (!val) {\n return null\n }\n return Array.isArray(val) ? val.join(\" \") : String(val)\n}\n\n/**\n * Extract class names from the text content of a HAST tree.\n * Looks for string literals that could be Tailwind class names.\n */\nexport function extractClassesFromHast(tree: Root): string[] {\n const classes = new Set<string>()\n const stringLiteralPattern = /[\"'`]([^\"'`]+)[\"'`]/g\n\n visit(tree, \"text\", (node: Text) => {\n const text = node.value\n let match\n while ((match = stringLiteralPattern.exec(text)) !== null) {\n const content = match[1]\n const tokens = content.split(/\\s+/).filter(Boolean)\n for (const token of tokens) {\n classes.add(token)\n }\n }\n })\n\n return [...classes]\n}\n\nexport function extractClasses(source: string): string[] {\n const tree = fromHtml(source, {fragment: true})\n const classes = new Set<string>()\n\n visit(tree, \"element\", (node: Element) => {\n const value = getClassValue(node)\n if (value) {\n classes.add(value)\n }\n })\n\n return classes\n .values()\n .toArray()\n .map((value) => value.split(\" \"))\n .flat()\n}\n\n/**\n * Create a fresh Tailwind compiler for each transformation.\n * Note: Tailwind v4's compiler.build() is incremental and accumulates\n * all candidates across calls. We must create a fresh compiler each time\n * to avoid CSS from one demo leaking into another.\n */\nasync function createCompiler(styles: string) {\n return compile(styles, {\n loadStylesheet: async (id: string, base: string) => {\n const content = await loadStylesheetContent(id)\n return {\n base,\n content,\n path: `virtual:${id}`,\n }\n },\n })\n}\n\n/**\n * Extract CSS custom property definitions from compiled CSS.\n * Looks in :root and :host selectors within @layer theme.\n */\nfunction extractCssVariables(css: string): Map<string, string> {\n const variables = new Map<string, string>()\n const root = postcss.parse(css)\n\n root.walkAtRules(\"layer\", (atRule) => {\n if (atRule.params !== \"theme\") {\n return\n }\n\n atRule.walkRules(\":root, :host\", (rule) => {\n rule.walkDecls((decl) => {\n if (decl.prop.startsWith(\"--\")) {\n variables.set(decl.prop, decl.value)\n }\n })\n })\n })\n\n return variables\n}\n\n/**\n * Evaluate a calc() expression with resolved numeric values.\n * Handles expressions like \"0.25rem * 4\" -> \"1rem\" or \"1.25 / 0.875\" -> \"1.4286\"\n */\nfunction evaluateCalc(expression: string): string | null {\n const expr = expression.trim()\n\n // Pattern 1: number+unit operator number (e.g., \"0.25rem * 4\")\n const withUnitFirst = expr.match(\n /^([\\d.]+)(rem|px|em|%|vh|vw)\\s*([*/+-])\\s*([\\d.]+)$/,\n )\n if (withUnitFirst) {\n const [, num1, unit, op, num2] = withUnitFirst\n const result = evaluateOperation(parseFloat(num1), op, parseFloat(num2))\n if (!Number.isFinite(result)) {\n return null\n }\n return formatNumber(result) + unit\n }\n\n // Pattern 2: number operator number+unit (e.g., \"4 * 0.25rem\")\n const withUnitSecond = expr.match(\n /^([\\d.]+)\\s*([*/+-])\\s*([\\d.]+)(rem|px|em|%|vh|vw)$/,\n )\n if (withUnitSecond) {\n const [, num1, op, num2, unit] = withUnitSecond\n const result = evaluateOperation(parseFloat(num1), op, parseFloat(num2))\n if (!Number.isFinite(result)) {\n return null\n }\n return formatNumber(result) + unit\n }\n\n // Pattern 3: unitless (e.g., \"1.25 / 0.875\")\n const unitless = expr.match(/^([\\d.]+)\\s*([*/+-])\\s*([\\d.]+)$/)\n if (unitless) {\n const [, num1, op, num2] = unitless\n const result = evaluateOperation(parseFloat(num1), op, parseFloat(num2))\n if (!Number.isFinite(result)) {\n return null\n }\n return formatNumber(result)\n }\n\n return null\n}\n\nfunction evaluateOperation(a: number, op: string, b: number): number {\n switch (op) {\n case \"*\":\n return a * b\n case \"/\":\n return a / b\n case \"+\":\n return a + b\n case \"-\":\n return a - b\n default:\n return NaN\n }\n}\n\nfunction formatNumber(num: number): string {\n // Avoid floating point artifacts like 0.30000000000000004\n const rounded = Math.round(num * 10000) / 10000\n return String(rounded)\n}\n\n/**\n * Convert rem values to pixels (assuming 1rem = 16px).\n */\nfunction remToPx(value: string): string {\n return value.replace(/([\\d.]+)rem/g, (_, num) => {\n const px = parseFloat(num) * 16\n return `${formatNumber(px)}px`\n })\n}\n\n/**\n * Find the matching closing parenthesis for a var() call.\n * Handles nested parentheses in fallback values.\n */\nfunction findVarEnd(str: string, start: number): number {\n let depth = 0\n for (let i = start; i < str.length; i++) {\n if (str[i] === \"(\") {\n depth++\n } else if (str[i] === \")\") {\n depth--\n if (depth === 0) {\n return i\n }\n }\n }\n return -1\n}\n\n/**\n * Parse a var() expression and return its parts.\n */\nfunction parseVar(\n str: string,\n startIndex: number,\n): {end: number; fallback: string | null; varName: string} | null {\n // Find \"var(\" starting position\n const varStart = str.indexOf(\"var(\", startIndex)\n if (varStart === -1) {\n return null\n }\n\n const contentStart = varStart + 4 // After \"var(\"\n const end = findVarEnd(str, varStart)\n if (end === -1) {\n return null\n }\n\n const content = str.slice(contentStart, end)\n\n // Find comma separating variable name from fallback\n let commaIndex = -1\n let depth = 0\n for (let i = 0; i < content.length; i++) {\n if (content[i] === \"(\") {\n depth++\n } else if (content[i] === \")\") {\n depth--\n } else if (content[i] === \",\" && depth === 0) {\n commaIndex = i\n break\n }\n }\n\n if (commaIndex === -1) {\n return {\n end,\n fallback: null,\n varName: content.trim(),\n }\n }\n\n return {\n end,\n fallback: content.slice(commaIndex + 1).trim(),\n varName: content.slice(0, commaIndex).trim(),\n }\n}\n\n/**\n * Resolve CSS var() references and evaluate calc() expressions.\n * Recursively resolves nested var() calls.\n */\nfunction resolveCssValue(\n value: string,\n variables: Map<string, string>,\n depth = 0,\n): string {\n if (depth > 10) {\n return value // Prevent infinite recursion\n }\n\n let resolved = value\n let searchStart = 0\n\n // Process var() calls iteratively to handle nested var() in fallbacks\n while (true) {\n const parsed = parseVar(resolved, searchStart)\n if (!parsed) {\n break\n }\n\n const {end, fallback, varName} = parsed\n const varStart = resolved.indexOf(\"var(\", searchStart)\n\n let replacement: string\n const varValue = variables.get(varName)\n if (varValue !== undefined) {\n replacement = resolveCssValue(varValue, variables, depth + 1)\n } else if (fallback) {\n replacement = resolveCssValue(fallback, variables, depth + 1)\n } else {\n // Keep original if unresolved, move past it\n searchStart = end + 1\n continue\n }\n\n resolved =\n resolved.slice(0, varStart) + replacement + resolved.slice(end + 1)\n }\n\n // Evaluate calc() expressions after var() resolution\n resolved = resolved.replace(\n /calc\\(([^)]+)\\)/g,\n (match, expression: string) => {\n const evaluated = evaluateCalc(expression)\n return evaluated ?? match\n },\n )\n\n // Convert rem to px (1rem = 16px)\n resolved = remToPx(resolved)\n\n return resolved\n}\n\ninterface SelectorAnalysis {\n /** The class name if it's a simple class selector */\n className: string | null\n /** Whether this selector can be inlined (single class, no pseudo/combinators) */\n inlineable: boolean\n}\n\n/**\n * Analyze a CSS selector using postcss-selector-parser AST.\n * Returns whether it can be inlined and extracts the class name.\n */\nfunction analyzeSelector(selector: string): SelectorAnalysis {\n let inlineable = true\n let className: string | null = null\n\n const processor = selectorParser((selectors) => {\n if (selectors.nodes.length !== 1) {\n inlineable = false\n return\n }\n\n const selectorNode = selectors.nodes[0]\n if (selectorNode.nodes.length !== 1) {\n inlineable = false\n return\n }\n\n const node = selectorNode.nodes[0]\n if (node.type !== \"class\") {\n inlineable = false\n return\n }\n\n className = node.value\n\n selectorNode.walk((n) => {\n if (\n n.type === \"pseudo\" ||\n n.type === \"combinator\" ||\n n.type === \"nesting\" ||\n n.type === \"attribute\"\n ) {\n inlineable = false\n }\n })\n })\n\n processor.processSync(selector)\n\n return {className, inlineable}\n}\n\ninterface ParsedRule {\n className: string\n declarations: string\n inlineable: boolean\n originalRule: string\n}\n\n/**\n * Parse compiled CSS and extract rules with their inlineability status.\n * CSS variables are resolved and calc() expressions are evaluated.\n */\nfunction parseCompiledCss(css: string): ParsedRule[] {\n const rules: ParsedRule[] = []\n const root = postcss.parse(css)\n const variables = extractCssVariables(css)\n\n function processRule(rule: Rule, insideAtRule: boolean) {\n const {className, inlineable} = analyzeSelector(rule.selector)\n\n if (!className) {\n return\n }\n\n let hasNestedAtRule = false\n rule.walkAtRules(() => {\n hasNestedAtRule = true\n })\n\n const declarations: string[] = []\n rule.each((node) => {\n if (node.type === \"decl\") {\n const resolvedValue = resolveCssValue(node.value, variables)\n declarations.push(`${node.prop}: ${resolvedValue}`)\n }\n })\n\n if (declarations.length === 0 && !hasNestedAtRule) {\n return\n }\n\n rules.push({\n className,\n declarations: declarations.join(\"; \"),\n inlineable: inlineable && !insideAtRule && !hasNestedAtRule,\n originalRule: rule.toString(),\n })\n }\n\n root.walkAtRules(\"layer\", (atRule) => {\n atRule.walkRules((rule) => {\n const parent = rule.parent\n const insideNestedAtRule =\n parent?.type === \"atrule\" && (parent as postcss.AtRule).name !== \"layer\"\n processRule(rule, insideNestedAtRule)\n })\n\n atRule.walkAtRules((nested) => {\n if (nested.name !== \"layer\") {\n nested.walkRules((rule) => {\n processRule(rule, true)\n })\n }\n })\n })\n\n root.walkRules((rule) => {\n if (rule.parent?.type === \"root\") {\n processRule(rule, false)\n }\n })\n\n return rules\n}\n\n/**\n * Build residual CSS from non-inlineable rules, stripping @layer wrappers.\n */\nfunction buildResidualCss(css: string, inlineableClasses: Set<string>): string {\n const root = postcss.parse(css)\n const residualRules: string[] = []\n\n function shouldKeepRule(rule: Rule): boolean {\n const {className} = analyzeSelector(rule.selector)\n return className !== null && !inlineableClasses.has(className)\n }\n\n root.walkAtRules(\"layer\", (atRule) => {\n if (atRule.params !== \"utilities\") {\n return\n }\n\n atRule.each((node) => {\n if (node.type === \"rule\") {\n const rule = node\n if (shouldKeepRule(rule)) {\n residualRules.push(rule.toString())\n }\n }\n })\n })\n\n return residualRules.join(\"\\n\\n\")\n}\n\nexport interface TransformResult {\n /** CSS for non-inlineable rules without @layer wrappers */\n css: string\n /** HTML with inline styles applied */\n html: string\n}\n\n/**\n * Transform HTML by inlining Tailwind styles where possible.\n * Non-inlineable styles (pseudo-classes, media queries, etc.) are returned as CSS.\n */\nexport async function transformWithInlineStyles(\n html: string,\n styles: string,\n): Promise<TransformResult> {\n const compiler = await createCompiler(styles)\n const allClasses = extractClasses(html)\n const compiledCss = compiler.build(allClasses)\n const parsedRules = parseCompiledCss(compiledCss)\n\n const inlineableStyles = new Map<string, string>()\n const inlineableClasses = new Set<string>()\n\n for (const rule of parsedRules) {\n if (rule.inlineable) {\n inlineableStyles.set(rule.className, rule.declarations)\n inlineableClasses.add(rule.className)\n }\n }\n\n const residualCss = buildResidualCss(compiledCss, inlineableClasses)\n const tree = fromHtml(html, {fragment: true})\n\n visit(tree, \"element\", (node: Element) => {\n const classValue = getClassValue(node)\n if (!classValue) {\n return\n }\n\n const classes = classValue.split(/\\s+/)\n const inlineStyles: string[] = []\n const remainingClasses: string[] = []\n\n for (const cls of classes) {\n const style = inlineableStyles.get(cls)\n if (style) {\n inlineStyles.push(style)\n } else {\n remainingClasses.push(cls)\n }\n }\n\n if (inlineStyles.length > 0) {\n const existingStyle = node.properties?.style as string | undefined\n const newStyle = inlineStyles.join(\"; \")\n node.properties = node.properties ?? {}\n node.properties.style = existingStyle\n ? `${existingStyle}; ${newStyle}`\n : newStyle\n }\n\n if (remainingClasses.length > 0) {\n node.properties = node.properties ?? {}\n node.properties.className = remainingClasses\n } else if (node.properties) {\n delete node.properties.className\n delete node.properties.class\n }\n })\n\n return {\n css: residualCss,\n html: toHtml(tree),\n }\n}\n\nexport interface ShikiTailwindTransformerOptions {\n /**\n * Callback invoked after transformation indicating whether any className/class\n * attributes were detected in the code. Useful for conditionally applying\n * the transformation or showing/hiding UI elements.\n */\n onClassesDetected?: (detected: boolean) => void\n /**\n * Callback invoked with CSS rules for non-inlineable classes (hover:, sm:, etc.).\n * Receives a Map where keys are class names and values are the CSS rule strings.\n * This allows for deduplication when aggregating CSS from multiple files.\n */\n onResidualCss?: (rules: Map<string, string>) => void\n /**\n * Output format for inline styles.\n * - \"html\": `style=\"display: flex\"` (HTML string syntax)\n * - \"jsx\": `style={{ display: 'flex' }}` (JSX object syntax)\n * @default \"html\"\n */\n styleFormat?: \"html\" | \"jsx\"\n /** Tailwind CSS styles to compile against */\n styles: string\n}\n\ninterface CompileClassesResult {\n inlineStyles: string[]\n remainingClasses: string[]\n residualRules: Map<string, string>\n}\n\n/**\n * Compile classes and return inline styles, remaining classes, and residual CSS\n * rules.\n */\nfunction compileClasses(\n classes: string[],\n compiler: {build(candidates: string[]): string},\n): CompileClassesResult {\n const compiledCss = compiler.build(classes)\n const parsedRules = parseCompiledCss(compiledCss)\n\n const inlineableStyles = new Map<string, string>()\n const residualRules = new Map<string, string>()\n\n for (const rule of parsedRules) {\n if (rule.inlineable) {\n inlineableStyles.set(rule.className, rule.declarations)\n } else {\n residualRules.set(rule.className, rule.originalRule)\n }\n }\n\n const inlineStyles: string[] = []\n const remainingClasses: string[] = []\n\n for (const cls of classes) {\n const style = inlineableStyles.get(cls)\n if (style) {\n inlineStyles.push(style)\n } else {\n remainingClasses.push(cls)\n }\n }\n\n return {inlineStyles, remainingClasses, residualRules}\n}\n\n/**\n * Convert CSS declarations to JSX object syntax.\n * `\"display: flex; align-items: center\"` -> `\"{ display: 'flex', alignItems:\n * 'center'}\"`\n */\nfunction cssToJsxObject(cssDeclarations: string[]): string {\n const props = cssDeclarations\n .flatMap((decl) => {\n return decl\n .split(\";\")\n .map((d) => d.trim())\n .filter(Boolean)\n })\n .map((declaration) => {\n const colonIndex = declaration.indexOf(\":\")\n if (colonIndex === -1) {\n return null\n }\n const prop = declaration.slice(0, colonIndex).trim()\n const value = declaration.slice(colonIndex + 1).trim()\n const camelProp = camelCase(prop)\n return `${camelProp}: '${value}'`\n })\n .filter(Boolean)\n\n return `{ ${props.join(\", \")} }`\n}\n\ninterface LineReplacementsResult {\n replacements: Map<string, string>\n residualRules: Map<string, string>\n}\n\n/**\n * Transform className attributes to style attributes in a line's text.\n * Returns replacements and residual CSS rules for non-inlineable classes.\n */\nfunction computeLineReplacements(\n lineText: string,\n compiler: {build(candidates: string[]): string},\n styleFormat: \"html\" | \"jsx\" = \"html\",\n): LineReplacementsResult {\n const replacements = new Map<string, string>()\n const allResidualRules = new Map<string, string>()\n const classAttrPattern = /(className|class)=([\"'`])([^\"'`]*)\\2/g\n let match\n\n while ((match = classAttrPattern.exec(lineText)) !== null) {\n const fullMatch = match[0]\n const attrName = match[1]\n const quote = match[2]\n const classValue = match[3]\n\n const classes = classValue.split(/\\s+/).filter(Boolean)\n if (classes.length === 0) {\n continue\n }\n\n const {inlineStyles, remainingClasses, residualRules} = compileClasses(\n classes,\n compiler,\n )\n\n for (const [className, rule] of residualRules) {\n allResidualRules.set(className, rule)\n }\n\n if (inlineStyles.length === 0) {\n continue\n }\n\n let replacement: string\n if (styleFormat === \"jsx\") {\n const jsxStyleObj = cssToJsxObject(inlineStyles)\n replacement = `style={${jsxStyleObj}}`\n } else {\n replacement = `style=${quote}${inlineStyles.join(\"; \")}${quote}`\n }\n\n if (remainingClasses.length > 0) {\n replacement += ` ${attrName}=${quote}${remainingClasses.join(\" \")}${quote}`\n }\n\n replacements.set(fullMatch, replacement)\n }\n\n return {replacements, residualRules: allResidualRules}\n}\n\ninterface TransformSourceResult {\n /** Whether any className/class attributes were detected in the code */\n classesDetected: boolean\n /** CSS rules for non-inlineable classes */\n residualRules: Map<string, string>\n /** Transformed source code */\n source: string\n}\n\n/**\n * Transform className/class attributes to inline styles in source code.\n * This runs BEFORE Shiki tokenization to preserve proper syntax highlighting.\n */\nfunction transformSourceCode(\n source: string,\n compiler: {build(candidates: string[]): string},\n styleFormat: \"html\" | \"jsx\" = \"html\",\n): TransformSourceResult {\n const allResidualRules = new Map<string, string>()\n let classesDetected = false\n\n const {replacements, residualRules} = computeLineReplacements(\n source,\n compiler,\n styleFormat,\n )\n\n if (replacements.size > 0 || residualRules.size > 0) {\n classesDetected = true\n }\n\n for (const [cls, rule] of residualRules) {\n allResidualRules.set(cls, rule)\n }\n\n // Apply all replacements to the source\n let transformed = source\n for (const [original, replacement] of replacements) {\n transformed = transformed.replaceAll(original, replacement)\n }\n\n return {\n classesDetected,\n residualRules: allResidualRules,\n source: transformed,\n }\n}\n\n/**\n * Create a Shiki transformer that inlines Tailwind styles.\n * Uses preprocess to transform source code BEFORE tokenization,\n * ensuring proper syntax highlighting of the transformed output.\n * Must be called with `await` before using the transformer.\n */\nexport async function createShikiTailwindTransformer(\n options: ShikiTailwindTransformerOptions,\n): Promise<ShikiTransformer> {\n const {\n onClassesDetected,\n onResidualCss,\n styleFormat = \"html\",\n styles,\n } = options\n const compiler = await createCompiler(styles)\n\n return {\n name: \"shiki-transformer-tailwind-to-inline\",\n preprocess(code) {\n const {classesDetected, residualRules, source} = transformSourceCode(\n code,\n compiler,\n styleFormat,\n )\n\n onClassesDetected?.(classesDetected)\n\n if (onResidualCss && residualRules.size > 0) {\n onResidualCss(residualRules)\n }\n\n return source\n },\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nexport const VIRTUAL_MODULE_IDS = {\n AUTO: \"\\0virtual:qui-demo-scope/auto\",\n CONFIG: \"\\0virtual:qui-demo-scope/config\",\n PAGE_PREFIX: \"\\0virtual:qui-demo-scope/page:\",\n} as const\n\nexport const LOG_PREFIX = \"@qualcomm-ui/mdx-vite/react-demo-plugin:\"\n\nexport const REACT_IMPORTS: string[] = [\n \"useState\",\n \"useEffect\",\n \"useMemo\",\n \"useCallback\",\n \"useRef\",\n \"useContext\",\n \"createContext\",\n \"forwardRef\",\n \"memo\",\n \"lazy\",\n \"Suspense\",\n \"Fragment\",\n] as const\n\nexport const NODE_BUILTINS: string[] = [\n \"fs\",\n \"path\",\n \"url\",\n \"util\",\n \"os\",\n \"crypto\",\n \"events\",\n \"stream\",\n \"buffer\",\n] as const\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport chalk from \"chalk\"\nimport {existsSync, readFileSync} from \"node:fs\"\nimport {readFile} from \"node:fs/promises\"\nimport {dirname, join, relative, resolve, sep} from \"node:path\"\nimport * as ts from \"typescript\"\n\nimport {pascalCase} from \"@qualcomm-ui/utils/change-case\"\n\nimport {LOG_PREFIX, NODE_BUILTINS} from \"./demo-plugin-constants\"\n\ninterface PathAlias {\n pattern: RegExp\n replacement: string\n}\n\nexport interface ImportSpecifier {\n source: string\n specifiers: Array<{\n imported: string\n local: string\n }>\n type: \"thirdParty\"\n}\n\nexport interface RelativeImport {\n resolvedPath: string\n source: string\n specifiers: Array<{\n imported: string\n local: string\n }>\n type: \"relative\"\n}\n\n/**\n * Demo names are created using the PascalCase format of the file name without the\n * extension.\n */\nexport function createDemoName(filePath: string): string {\n const separatorChar = filePath.includes(\"/\") ? \"/\" : \"\\\\\"\n const fileName = filePath.substring(\n filePath.lastIndexOf(separatorChar),\n filePath.lastIndexOf(\".\"),\n )\n if (!fileName) {\n throw new Error(`Failed to create demo name for ${filePath}`)\n }\n return pascalCase(fileName)\n}\n\nexport async function extractFileImports(filePath: string): Promise<{\n relativeImports: RelativeImport[]\n thirdPartyImports: ImportSpecifier[]\n} | null> {\n try {\n const content = await readFile(filePath, \"utf-8\")\n return extractImports(content, filePath)\n } catch (error) {\n console.log(\n `${chalk.magenta.bold(LOG_PREFIX)} ${chalk.yellowBright(\"Failed to parse\")} ${chalk.blueBright.bold(filePath)}:`,\n error,\n )\n return null\n }\n}\n\nfunction extractImports(\n code: string,\n fileName: string,\n): {\n relativeImports: RelativeImport[]\n thirdPartyImports: ImportSpecifier[]\n} {\n const sourceFile = ts.createSourceFile(\n fileName,\n code,\n ts.ScriptTarget.Latest,\n true,\n getScriptKind(fileName),\n )\n const thirdPartyImports: ImportSpecifier[] = []\n const relativeImports: RelativeImport[] = []\n\n function visit(node: ts.Node) {\n if (ts.isImportDeclaration(node)) {\n const importSpec = parseImportDeclaration(node, fileName)\n if (importSpec) {\n if (importSpec.type === \"relative\") {\n relativeImports.push(importSpec)\n } else {\n thirdPartyImports.push(importSpec)\n }\n }\n }\n ts.forEachChild(node, visit)\n }\n\n visit(sourceFile)\n return {relativeImports, thirdPartyImports}\n}\n\nexport function getScriptKind(fileName: string): ts.ScriptKind {\n return fileName.endsWith(\".tsx\") || fileName.endsWith(\".jsx\")\n ? ts.ScriptKind.TSX\n : ts.ScriptKind.TS\n}\n\nfunction parseImportDeclaration(\n node: ts.ImportDeclaration,\n fileName: string,\n): ImportSpecifier | RelativeImport | null {\n const moduleSpecifier = node.moduleSpecifier\n if (!ts.isStringLiteral(moduleSpecifier)) {\n return null\n }\n\n const source = moduleSpecifier.text\n if (node.importClause?.isTypeOnly) {\n return null\n }\n\n const specifiers = extractSpecifiers(node.importClause)\n if (specifiers.length === 0) {\n return null\n }\n\n if (isRelativeImport(source)) {\n const resolvedPath = resolveRelativeImport(source, fileName)\n return {\n resolvedPath,\n source,\n specifiers,\n type: \"relative\",\n }\n }\n\n if (isNodeBuiltin(source)) {\n return null\n }\n\n const pathAliases = loadTsConfigPaths(fileName)\n if (isPathAliasImport(source, pathAliases)) {\n const resolvedPath = resolvePathAlias(source, pathAliases)\n if (resolvedPath) {\n return {\n resolvedPath,\n source,\n specifiers,\n type: \"relative\",\n }\n }\n }\n\n return {\n source,\n specifiers,\n type: \"thirdParty\",\n }\n}\n\nfunction extractSpecifiers(\n importClause: ts.ImportClause | undefined,\n): Array<{imported: string; local: string}> {\n if (!importClause) {\n return []\n }\n\n const specifiers: Array<{imported: string; local: string}> = []\n\n if (importClause.name) {\n specifiers.push({imported: \"default\", local: \"default\"})\n }\n\n if (importClause.namedBindings) {\n if (ts.isNamespaceImport(importClause.namedBindings)) {\n specifiers.push({imported: \"*\", local: \"*\"})\n } else if (ts.isNamedImports(importClause.namedBindings)) {\n importClause.namedBindings.elements.forEach((element) => {\n if (!element.isTypeOnly) {\n const imported = element.propertyName\n ? element.propertyName.text\n : element.name.text\n const local = element.name.text\n specifiers.push({imported, local})\n }\n })\n }\n }\n\n return specifiers\n}\n\nfunction resolveRelativeImport(source: string, fromFile: string): string {\n const fromDir = dirname(fromFile)\n const resolved = resolve(fromDir, source)\n\n const extensions = [\".ts\", \".tsx\", \".js\", \".jsx\"]\n for (const ext of extensions) {\n const withExt = resolved + ext\n if (existsSync(withExt)) {\n return withExt\n }\n }\n\n for (const ext of extensions) {\n const indexFile = join(resolved, `index${ext}`)\n if (existsSync(indexFile)) {\n return indexFile\n }\n }\n\n return resolved\n}\n\nfunction isRelativeImport(source: string): boolean {\n return source.startsWith(\"./\") || source.startsWith(\"../\")\n}\n\nfunction isNodeBuiltin(source: string): boolean {\n return source.startsWith(\"node:\") || NODE_BUILTINS.includes(source)\n}\n\nfunction loadTsConfigPaths(fromFile: string): PathAlias[] {\n let currentDir = dirname(fromFile)\n const pathAliases: PathAlias[] = []\n\n while (currentDir !== dirname(currentDir)) {\n const tsconfigPath = join(currentDir, \"tsconfig.json\")\n if (existsSync(tsconfigPath)) {\n try {\n const configContent = ts.sys.readFile(tsconfigPath)\n if (!configContent) {\n currentDir = dirname(currentDir)\n continue\n }\n\n const parseResult = ts.parseConfigFileTextToJson(\n tsconfigPath,\n configContent,\n )\n if (parseResult.error) {\n currentDir = dirname(currentDir)\n continue\n }\n\n const paths = parseResult.config?.compilerOptions?.paths\n const baseUrl = parseResult.config?.compilerOptions?.baseUrl || \"./\"\n const resolvedBaseUrl = resolve(currentDir, baseUrl)\n\n if (paths) {\n for (const [alias, targets] of Object.entries(paths)) {\n if (Array.isArray(targets) && targets.length > 0) {\n const target = targets[0]\n const pattern = new RegExp(\n `^${alias\n .replace(\"*\", \"(.*)\")\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(\"\\\\(\\\\*\\\\)\", \"(.*)\")}$`,\n )\n const replacement = resolve(\n resolvedBaseUrl,\n target.replace(\"*\", \"$1\"),\n )\n pathAliases.push({pattern, replacement})\n }\n }\n }\n\n const extendsPath = parseResult.config?.extends\n if (extendsPath) {\n const resolvedExtends = resolve(currentDir, extendsPath)\n const extendedAliases = loadTsConfigPathsFromFile(resolvedExtends)\n pathAliases.push(...extendedAliases)\n }\n\n return pathAliases\n } catch (error) {\n currentDir = dirname(currentDir)\n continue\n }\n }\n currentDir = dirname(currentDir)\n }\n\n return pathAliases\n}\n\nfunction loadTsConfigPathsFromFile(tsconfigPath: string): PathAlias[] {\n const pathAliases: PathAlias[] = []\n const configDir = dirname(tsconfigPath)\n\n try {\n const configContent = ts.sys.readFile(tsconfigPath)\n if (!configContent) {\n return pathAliases\n }\n\n const parseResult = ts.parseConfigFileTextToJson(\n tsconfigPath,\n configContent,\n )\n if (parseResult.error) {\n return pathAliases\n }\n\n const paths = parseResult.config?.compilerOptions?.paths\n const baseUrl = parseResult.config?.compilerOptions?.baseUrl || \"./\"\n const resolvedBaseUrl = resolve(configDir, baseUrl)\n\n if (paths) {\n for (const [alias, targets] of Object.entries(paths)) {\n if (Array.isArray(targets) && targets.length > 0) {\n const target = targets[0]\n const pattern = new RegExp(\n `^${alias\n .replace(\"*\", \"(.*)\")\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(\"\\\\(\\\\*\\\\)\", \"(.*)\")}$`,\n )\n const replacement = resolve(\n resolvedBaseUrl,\n target.replace(\"*\", \"$1\"),\n )\n pathAliases.push({pattern, replacement})\n }\n }\n }\n\n const extendsPath = parseResult.config?.extends\n if (extendsPath) {\n let resolvedExtends = resolve(configDir, extendsPath)\n if (!resolvedExtends.endsWith(\".json\")) {\n resolvedExtends += \".json\"\n }\n if (existsSync(resolvedExtends)) {\n const extendedAliases = loadTsConfigPathsFromFile(resolvedExtends)\n pathAliases.push(...extendedAliases)\n }\n }\n } catch (error) {\n return pathAliases\n }\n\n return pathAliases\n}\n\nfunction isPathAliasImport(source: string, pathAliases: PathAlias[]): boolean {\n return pathAliases.some((alias) => alias.pattern.test(source))\n}\n\nfunction resolvePathAlias(\n source: string,\n pathAliases: PathAlias[],\n): string | null {\n for (const alias of pathAliases) {\n if (alias.pattern.test(source)) {\n const resolvedPath = source.replace(alias.pattern, alias.replacement)\n const extensions = [\".ts\", \".tsx\", \".js\", \".jsx\"]\n\n for (const ext of extensions) {\n const withExt = resolvedPath + ext\n if (existsSync(withExt)) {\n return withExt\n }\n }\n\n for (const ext of extensions) {\n const indexFile = join(resolvedPath, `index${ext}`)\n if (existsSync(indexFile)) {\n return indexFile\n }\n }\n\n return resolvedPath\n }\n }\n return null\n}\n\nexport function extractPageId(filePath: string, routesDir: string): string {\n const relativePath = relative(routesDir, filePath)\n const pathParts = relativePath.split(sep)\n if (pathParts.includes(\"demos\")) {\n const demosIndex = pathParts.indexOf(\"demos\")\n return pathParts.slice(0, demosIndex).join(sep)\n }\n return dirname(relativePath)\n}\n\nexport function isCssAsset(filePath: string) {\n return filePath.endsWith(\".css\")\n}\n\nexport function isDemoFile(filePath: string): boolean {\n try {\n return (\n filePath.includes(\"/demos/\") &&\n filePath.endsWith(\".tsx\") &&\n !readFileSync(filePath).includes(\"export default\")\n )\n } catch (error) {\n return false\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport chalk from \"chalk\"\nimport {glob} from \"glob\"\nimport {readFile} from \"node:fs/promises\"\nimport {basename, resolve} from \"node:path\"\nimport {createHighlighter, type Highlighter, type ShikiTransformer} from \"shiki\"\nimport * as ts from \"typescript\"\nimport type {Plugin} from \"vite\"\n\nimport {\n quiCustomDarkTheme,\n type ReactDemoData,\n type SourceCodeData,\n} from \"@qualcomm-ui/mdx-common\"\nimport {dedent} from \"@qualcomm-ui/utils/dedent\"\n\nimport {getShikiTransformers} from \"../docs-plugin\"\nimport {\n extractPreviewFromHighlightedHtml,\n transformerCodeAttribute,\n transformerPreviewBlock,\n} from \"../docs-plugin/shiki\"\nimport {createShikiTailwindTransformer} from \"../docs-plugin/shiki/internal\"\n\nimport {LOG_PREFIX, VIRTUAL_MODULE_IDS} from \"./demo-plugin-constants\"\nimport type {QuiDemoPluginOptions} from \"./demo-plugin-types\"\nimport {\n createDemoName,\n extractFileImports,\n extractPageId,\n getScriptKind,\n isCssAsset,\n isDemoFile,\n} from \"./demo-plugin-utils\"\n\ninterface HandleUpdateOptions {\n demoName?: string\n filePath: string\n}\n\ninterface HighlightCodeResult {\n full: string\n preview?: string | null\n}\n\ninterface ExtractedSourceCode {\n residualRules?: Map<string, string>\n sourceCodeData: SourceCodeData\n}\n\nlet highlighter: Highlighter | null = null\nlet initializingHighlighter = false\n\nconst demoRegistry = new Map<string, ReactDemoData>()\nconst pageFiles = new Map<string, string[]>()\nconst relativeImportDependents = new Map<string, Set<string>>()\n\n/**\n * Generates virtual modules for React demo components. Virtual modules contain\n * highlighted source code and metadata about each demo.\n */\nexport function reactDemoPlugin({\n demoPattern = \"src/routes/**/demos/*.tsx\",\n routesDir = \"src/routes\",\n theme = {\n dark: quiCustomDarkTheme,\n light: \"github-light-high-contrast\",\n },\n transformers = [],\n transformLine,\n transformTailwindStyles,\n}: QuiDemoPluginOptions = {}): Plugin {\n const defaultShikiOptions = {\n defaultColor: \"light-dark()\",\n lang: \"tsx\",\n themes: {\n dark: theme.dark,\n light: theme.light,\n },\n }\n\n return {\n apply(config, env) {\n return (\n (env.mode === \"development\" && env.command === \"serve\") ||\n (env.mode === \"production\" && env.command === \"build\")\n )\n },\n async buildStart() {\n if (!highlighter && !initializingHighlighter) {\n initializingHighlighter = true\n try {\n highlighter = await createHighlighter({\n langs: [\"tsx\", \"typescript\", \"css\"],\n themes: [theme.dark, theme.light],\n })\n console.log(\n `${chalk.magenta.bold(LOG_PREFIX)} Shiki highlighter initialized`,\n )\n } catch (error) {\n console.warn(\n `${chalk.magenta.bold(LOG_PREFIX)} Failed to initialize highlighter:`,\n error,\n )\n } finally {\n initializingHighlighter = false\n }\n }\n\n await collectReactDemos()\n },\n\n async handleHotUpdate({file, modules, server}) {\n if (isCssAsset(file)) {\n return modules\n }\n\n if (file.endsWith(\".mdx\")) {\n return []\n }\n\n if (isDemoFile(file)) {\n await handleDemoAdditionOrUpdate({filePath: file})\n } else {\n const normalizedFile = resolve(file)\n const dependentDemos = relativeImportDependents.get(normalizedFile)\n if (!dependentDemos?.size) {\n return []\n }\n for (const demoName of Array.from(dependentDemos)) {\n const demo = demoRegistry.get(demoName)\n if (demo) {\n await handleDemoAdditionOrUpdate({\n filePath: demo.filePath,\n })\n }\n }\n }\n\n const autoModule = server.moduleGraph.getModuleById(\n VIRTUAL_MODULE_IDS.AUTO,\n )\n if (autoModule) {\n server.moduleGraph.invalidateModule(autoModule)\n await server.reloadModule(autoModule)\n }\n return []\n },\n\n load(id) {\n if (id === VIRTUAL_MODULE_IDS.AUTO) {\n return generateAutoScopeModule()\n }\n },\n\n name: \"auto-demo-scope\",\n\n resolveId(id) {\n if (id === \"virtual:qui-demo-scope/auto\") {\n return VIRTUAL_MODULE_IDS.AUTO\n }\n },\n\n writeBundle() {\n console.log(\n `${chalk.blue.bold(LOG_PREFIX)} Successfully integrated ${chalk.green(demoRegistry.size)} component demos`,\n )\n },\n }\n\n async function handleDemoAdditionOrUpdate({\n filePath,\n }: HandleUpdateOptions): Promise<void> {\n const pageId = extractPageId(filePath, routesDir)\n const demoName = createDemoName(filePath)\n\n const existingFiles = pageFiles.get(pageId) ?? []\n if (!existingFiles.includes(filePath)) {\n existingFiles.push(filePath)\n pageFiles.set(pageId, existingFiles)\n }\n\n const fileData = await extractFileData(filePath)\n if (fileData) {\n demoRegistry.set(demoName, {\n ...fileData,\n demoName,\n pageId,\n })\n\n const fileImports = await extractFileImports(filePath)\n if (fileImports) {\n for (const relativeImport of fileImports.relativeImports) {\n const dependents =\n relativeImportDependents.get(relativeImport.resolvedPath) ??\n new Set()\n dependents.add(demoName)\n relativeImportDependents.set(relativeImport.resolvedPath, dependents)\n }\n }\n }\n }\n\n async function highlightCode(\n code: string,\n options: {\n extraTransformers?: ShikiTransformer[]\n onClassesDetected?: (detected: boolean) => void\n onResidualCss?: (rules: Map<string, string>) => void\n } = {},\n ): Promise<HighlightCodeResult> {\n const {extraTransformers = [], onResidualCss} = options\n\n if (!highlighter) {\n return {full: code}\n }\n let previewCode: string | null = null\n\n const tailwindTransformers: ShikiTransformer[] = []\n if (transformTailwindStyles && onResidualCss) {\n const transformer = await createShikiTailwindTransformer({\n onClassesDetected: (detected) => {\n options.onClassesDetected?.(detected)\n },\n onResidualCss,\n styleFormat: \"jsx\",\n styles: dedent`\n @layer theme, base, components, utilities;\n @import \"tailwindcss/theme.css\" layer(theme);\n @import \"tailwindcss/utilities.css\" layer(utilities);\n @import \"@qualcomm-ui/tailwind-plugin/qui-strict.css\";\n `,\n })\n tailwindTransformers.push(transformer)\n } else if (extraTransformers.length > 0) {\n tailwindTransformers.push(...extraTransformers)\n }\n\n try {\n const highlightedCode = highlighter.codeToHtml(code, {\n ...defaultShikiOptions,\n transformers: [\n ...getShikiTransformers(),\n ...transformers,\n ...tailwindTransformers,\n transformerPreviewBlock({\n attributeName: \"data-preview\",\n onComplete: (extractedPreview) => {\n previewCode = extractedPreview\n },\n }),\n transformerCodeAttribute({\n attributeName: \"data-code\",\n }),\n {\n enforce: \"post\",\n name: \"shiki-transformer-trim\",\n preprocess(code) {\n return code.trim()\n },\n },\n ...transformers,\n ],\n })\n\n return {\n full: highlightedCode,\n preview: previewCode\n ? extractPreviewFromHighlightedHtml(highlightedCode)\n : null,\n }\n } catch (error) {\n console.warn(\n `${chalk.magenta.bold(LOG_PREFIX)} Failed to highlight code:`,\n error,\n )\n return {full: code}\n }\n }\n\n async function collectReactDemos() {\n if (demoRegistry.size) {\n return\n }\n\n const demoFiles = (await glob(demoPattern)).filter(isDemoFile)\n\n for (const filePath of demoFiles) {\n const pageId = extractPageId(filePath, routesDir)\n const existingFiles = pageFiles.get(pageId) ?? []\n existingFiles.push(filePath)\n pageFiles.set(pageId, existingFiles)\n\n const fileData = await extractFileData(filePath)\n if (fileData) {\n const demoName = createDemoName(filePath)\n demoRegistry.set(demoName, {\n ...fileData,\n pageId,\n })\n }\n\n const fileImports = await extractFileImports(filePath)\n if (fileImports) {\n for (const relativeImport of fileImports.relativeImports) {\n const demoName = createDemoName(filePath)\n const dependents =\n relativeImportDependents.get(relativeImport.resolvedPath) ??\n new Set()\n dependents.add(demoName)\n relativeImportDependents.set(relativeImport.resolvedPath, dependents)\n }\n }\n }\n }\n\n function generateAutoScopeModule(): string {\n const registryCode = generateDemoRegistry(demoRegistry)\n return [\n \"// Auto-generated demo scope resolver (PROD MODE)\",\n registryCode,\n generateExportedFunctions(),\n ].join(\"\\n\\n\")\n }\n\n function transformLines(code: string): string {\n if (!transformLine) {\n return code\n }\n const result: string[] = []\n for (const line of code.split(\"\\n\")) {\n if (line.trim()) {\n const transformed = transformLine(line)\n if (transformed) {\n result.push(transformed)\n }\n } else {\n // include all empty lines\n result.push(line)\n }\n }\n return result.join(\"\\n\")\n }\n\n async function extractHighlightedCode(\n filePath: string,\n code: string,\n ): Promise<ExtractedSourceCode | null> {\n try {\n const fileName = basename(filePath)\n\n const baseResult = await highlightCode(code)\n\n let inlineResult: HighlightCodeResult | undefined\n let classesDetected: boolean = false\n let residualRules: Map<string, string> | undefined\n\n if (transformTailwindStyles) {\n inlineResult = await highlightCode(code, {\n onClassesDetected: (detected) => {\n classesDetected = detected\n },\n onResidualCss: (rules) => {\n residualRules = rules\n },\n })\n }\n\n return {\n residualRules,\n sourceCodeData: {\n fileName,\n filePath,\n highlighted: {\n full: baseResult.full,\n preview: baseResult.preview,\n },\n highlightedInline:\n classesDetected && inlineResult\n ? {\n full: inlineResult.full,\n preview: inlineResult.preview,\n }\n : undefined,\n type: \"file\",\n },\n }\n } catch {\n return null\n }\n }\n\n async function extractFileData(\n filePath: string,\n ): Promise<Omit<ReactDemoData, \"pageId\"> | null> {\n try {\n const code = await readFile(filePath, \"utf-8\").then(transformLines)\n const imports = stripImports(code, filePath)\n\n const sourceCode: SourceCodeData[] = []\n // Use Map for deduplication across all files in this demo\n const aggregatedRules = new Map<string, string>()\n\n const extractedMain = await extractHighlightedCode(filePath, code)\n\n if (extractedMain) {\n sourceCode.push(extractedMain.sourceCodeData)\n if (extractedMain.residualRules) {\n for (const [className, rule] of extractedMain.residualRules) {\n aggregatedRules.set(className, rule)\n }\n }\n }\n\n const fileImports = await extractFileImports(filePath)\n if (fileImports) {\n for (const relativeImport of fileImports.relativeImports) {\n try {\n const importedCode = await readFile(\n relativeImport.resolvedPath,\n \"utf-8\",\n ).then(transformLines)\n\n const extracted = await extractHighlightedCode(\n relativeImport.resolvedPath,\n importedCode,\n )\n\n if (extracted) {\n sourceCode.push(extracted.sourceCodeData)\n if (extracted.residualRules) {\n for (const [className, rule] of extracted.residualRules) {\n aggregatedRules.set(className, rule)\n }\n }\n }\n } catch {\n console.debug(\"Failed to process file\", relativeImport.resolvedPath)\n }\n }\n }\n\n // Convert aggregated rules to CSS string\n const aggregatedResidualCss =\n aggregatedRules.size > 0\n ? [...aggregatedRules.values()].join(\"\\n\\n\")\n : undefined\n\n if (aggregatedResidualCss) {\n sourceCode.push({\n fileName: \"styles.css\",\n highlighted: await highlightCode(aggregatedResidualCss),\n type: \"residual-css\",\n })\n }\n\n return {\n demoName: createDemoName(filePath),\n fileName: extractedMain?.sourceCodeData.fileName || basename(filePath),\n filePath,\n imports,\n sourceCode,\n }\n } catch {\n return null\n }\n }\n\n function stripImports(code: string, fileName: string): string[] {\n try {\n const sourceFile = ts.createSourceFile(\n fileName,\n code,\n ts.ScriptTarget.Latest,\n true,\n getScriptKind(fileName),\n )\n\n const importRanges: Array<{end: number; start: number}> = []\n\n function visit(node: ts.Node) {\n if (ts.isImportDeclaration(node)) {\n importRanges.push({\n end: node.getEnd(),\n start: node.getFullStart(),\n })\n }\n ts.forEachChild(node, visit)\n }\n\n visit(sourceFile)\n\n return importRanges.map((range) => {\n let endPos = range.end\n if (code[endPos] === \"\\n\") {\n endPos++\n }\n return code.slice(range.start, endPos).trim()\n })\n } catch (error) {\n return []\n }\n }\n\n function generateDemoRegistry(registry: Map<string, ReactDemoData>): string {\n const entries = Array.from(registry.entries())\n .map(([demoName, {fileName, imports, pageId, sourceCode}]) => {\n return ` [\"${demoName}\", { fileName: \"${fileName}\", imports: ${JSON.stringify(imports)}, pageId: \"${pageId}\", sourceCode: ${JSON.stringify(sourceCode)}, demoName: \"${demoName}\" }]`\n })\n .join(\",\\n\")\n return `const demoRegistry = new Map([\\n${entries}\\n])`\n }\n\n function generateExportedFunctions(): string {\n return dedent`\n export function getDemo(demoName) {\n const demo = demoRegistry.get(demoName)\n if (!demo) {\n return {\n fileName: \"\",\n imports: [],\n errorMessage: \\`Demo \"\\${demoName}\" not found.\\`,\n pageId: \"\",\n sourceCode: [],\n }\n }\n return demo\n }\n `\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;AAEA,OAAOA,YAAW;AAClB,SAAwB,aAAY;AACpC,SAAQ,QAAAC,aAAW;AACnB,SAAQ,YAAY,gBAAe;AACnC,SAAQ,YAAAC,iBAAe;AACvB,SAAQ,YAAAC,WAAU,WAAAC,UAAS,QAAAC,OAAM,YAAAC,WAAU,WAAAC,gBAAc;AACzD;AAAA,EACE;AAAA,OAKK;AACP,YAAYC,SAAQ;AAGpB;AAAA,EAEE,sBAAAC;AAAA,OAEK;AACP,SAAQ,UAAAC,eAAa;;;ACpBrB,SAA6C,uBAAsB;;;ACG5D,SAAS,QAAQ,KAAqB;AAC3C,SAAO,IAAI,WAAW,MAAM,GAAG;AACjC;AAKO,SAAS,oBAAoB,KAAqB;AACvD,SAAO,IAAI,SAAS,GAAG,IAAI,IAAI,UAAU,GAAG,IAAI,SAAS,CAAC,IAAI;AAChE;;;ACZA,SAAQ,KAAAC,UAAwC;;;ACAhD,SAAQ,SAAQ;AAYT,SAAS,YAA2B;AACzC,SAAO;AAAA,IACL,MAAM,CAKJ,WACG,EAAE,OAAO,MAAM;AAAA,EACtB;AACF;;;ADPO,IAAM,gBAA+B,UAAmB,EAAE,KAAK;AAAA,EACpE,IAAIC,GAAE,MAAM,EAAE,SAAS;AAAA,EACvB,cAAcA,GAAE,OAAO,EAAE,SAAS;AAAA,EAClC,WAAWA,GAAE,QAAQ,EAAE,SAAS;AAClC,CAAC;AAEM,IAAM,kBACX,UAAqB,EAAE,KAAK;AAAA,EAC1B,UAAUA,GAAE,MAAMA,GAAE,KAAK,MAAM,eAAe,CAAC,EAAE,SAAS;AAAA,EAC1D,UAAUA,GAAE,QAAQ,EAAE,SAAS;AAAA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C,UAAU;AACjC,YAAI,SAAS,MAAM;AACnB,YAAI,KAAK,MAAM,MAAM,MAAM;AACzB;AAAA,QACF;AACA,eAAO,KAAK,MAAM,MAAM,OAAO,MAAM,EAAE,KAAK;AAAA,MAC9C,CAAC;AAAA,IACH,SAAS,OAAO;AACd,aAAO,CAAC;AAAA,IACV;AAAA,EACF;AAEA,WAAS,qBAAqB,UAA8C;AAC1E,UAAM,UAAU,MAAM,KAAK,SAAS,QAAQ,CAAC,EAC1C,IAAI,CAAC,CAAC,UAAU,EAAC,UAAU,SAAS,QAAQ,WAAU,CAAC,MAAM;AAC5D,aAAO,OAAO,QAAQ,mBAAmB,QAAQ,eAAe,KAAK,UAAU,OAAO,CAAC,cAAc,MAAM,kBAAkB,KAAK,UAAU,UAAU,CAAC,gBAAgB,QAAQ;AAAA,IACjL,CAAC,EACA,KAAK,KAAK;AACb,WAAO;AAAA,EAAmC,OAAO;AAAA;AAAA,EACnD;AAEA,WAAS,4BAAoC;AAC3C,WAAOL;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAeT;AACF;",
|
|
6
|
+
"names": ["chalk", "glob", "readFile", "basename", "dirname", "join", "relative", "resolve", "ts", "quiCustomDarkTheme", "dedent", "z", "z", "join", "chalk", "readFileSync", "join", "resolve", "z", "z", "remarkFrontmatter", "remarkParse", "remarkStringify", "unified", "item", "visit", "visit", "visit", "visit", "visit", "remove", "visit", "visit", "visit", "unified", "remarkParse", "remarkFrontmatter", "remarkStringify", "minimatch", "join", "visit", "capitalCase", "segment", "capitalCase", "state", "routeSegment", "readFile", "join", "visit", "createHash", "join", "resolve", "resolve", "join", "readFile", "visit", "join", "readFile", "dirname", "join", "resolve", "visit", "resolve", "join", "dirname", "readFile", "visit", "visit", "visit", "visit", "visit", "visit", "toString", "remarkGfm", "remarkStringify", "unified", "visit", "visit", "unified", "remarkGfm", "remarkStringify", "heading", "toString", "minimatch", "join", "visit", "chalk", "defined", "remarkMdx", "remarkParse", "remarkStringify", "unified", "visit", "visit", "unified", "remarkMdx", "remarkParse", "remarkStringify", "entry", "propTypes", "heading", "defined", "sections", "toc", "chalk", "heading", "readFileSync", "resolve", "chalk", "join", "isDev", "join", "config", "file", "remarkFrontmatter", "remarkGfm", "toString", "visit", "emptyOptions", "visit", "toString", "headingRank", "dedent", "isPreviewLine", "dedent", "remarkFrontmatter", "remarkGfm", "readFile", "visit", "createRequire", "quiCustomDarkTheme", "chalk", "isCssAsset", "readFile", "glob", "dedent", "extractRelativeImports", "visit", "isRelativeImport", "resolveRelativeImport", "isNodeBuiltin", "loadTsConfigPaths", "relative", "basename", "NODE_BUILTINS", "dirname", "resolve", "join", "LOG_PREFIX", "chalk", "existsSync", "readFileSync", "readFile", "dirname", "join", "relative", "resolve", "ts", "readFile", "chalk", "LOG_PREFIX", "visit", "isPathAliasImport", "resolvePathAlias", "dirname", "resolve", "existsSync", "join", "loadTsConfigPathsFromFile", "relative", "readFileSync", "chalk", "glob", "readFile", "basename", "resolve", "createHighlighter", "ts", "quiCustomDarkTheme", "dedent", "highlighter", "demoRegistry", "quiCustomDarkTheme", "createHighlighter", "chalk", "LOG_PREFIX", "resolve", "dedent", "code", "glob", "basename", "readFile", "visit"]
|
|
7
7
|
}
|