@qualcomm-ui/mdx-vite 2.6.4 → 2.8.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/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/angular-demo-plugin/angular-demo-plugin.ts", "../src/docs-plugin/docs-plugin.ts", "../src/docs-plugin/internal/config-loader.ts", "../src/docs-plugin/internal/config-schema.ts", "../src/docs-plugin/internal/zod.ts", "../src/docs-plugin/internal/utils.ts", "../src/docs-plugin/internal/search-indexer.ts", "../src/docs-plugin/internal/services/doc-props/doc-props-indexer.ts", "../src/docs-plugin/internal/services/mdx-utils.ts", "../src/docs-plugin/internal/services/markdown/markdown-file-reader.ts", "../src/docs-plugin/internal/services/markdown/markdown-indexer.ts", "../src/docs-plugin/rehype/rehype-slug.ts", "../src/docs-plugin/remark/remark-alerts.ts", "../src/docs-plugin/internal/services/markdown/remark-remove-code-blocks.ts", "../src/docs-plugin/internal/services/markdown/remark-remove-jsx.ts", "../src/docs-plugin/internal/services/nav-builder/get-route-meta.ts", "../src/docs-plugin/internal/services/nav-builder/nav-builder.ts", "../src/docs-plugin/internal/services/nav-builder/page-map.ts", "../src/docs-plugin/internal/transform-route-meta-array.ts", "../src/docs-plugin/mdx-plugins.ts", "../src/exports.ts", "../src/docs-plugin/rehype/rehype-sectionize.ts", "../src/docs-plugin/remark/remark-code-tabs.ts", "../src/docs-plugin/remark/remark-self-link-headings.ts", "../src/docs-plugin/remark/remark-spoilers.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} from \"node:fs\"\nimport {readFile, stat} 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 await 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 async 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 async 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\", async (filePath: string) => {\n const fileStats = await stat(filePath).catch(() => undefined)\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 await handleAngularDemoUpdate(filePath)\n triggerRegistryUpdate()\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 chalk from \"chalk\"\nimport chokidar from \"chokidar\"\nimport {glob} from \"glob\"\nimport {readFileSync} from \"node:fs\"\nimport {resolve} from \"node:path\"\nimport prettyMilliseconds from \"pretty-ms\"\nimport type {PluginOption, ViteDevServer} from \"vite\"\n\nimport type {PageDocProps, SiteData} from \"@qualcomm-ui/mdx-common\"\nimport type {QuiPropTypes} from \"@qualcomm-ui/typedoc-common\"\n\nimport {\n type CompiledMdxFile,\n ConfigLoader,\n fixPath,\n type ResolvedQuiDocsConfig,\n SearchIndexer,\n} from \"./internal\"\n\nconst isDev = process.env.NODE_ENV === \"development\"\n\ninterface ChangeOptions {\n onComplete?: () => void\n}\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 VIRTUAL_MODULE_ID = \"\\0@qualcomm-ui/mdx-vite-plugin\"\n\n/**\n * TODO: adjust when https://github.com/vitejs/vite/discussions/16358 lands.\n */\nclass PluginState {\n buildCount: number = 0\n configFilePath: string = \"\"\n docPropsFilePath: string = \"\"\n indexer!: SearchIndexer\n configLoader: ConfigLoader | null = null\n routesDir!: string\n servers: ViteDevServer[] = []\n timeout: ReturnType<typeof setTimeout> | undefined = undefined\n watching = false\n\n private cwd!: string\n\n init(cwd: string) {\n this.cwd = 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 return {\n navItems: state.indexer.navItems,\n pageDocProps: state.indexer.pageDocProps as unknown as PageDocProps,\n pageMap: state.indexer.pageMap,\n searchIndex: state.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.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.indexer = new SearchIndexer({\n ...config,\n srcDir: fixPath(resolve(this.cwd, config.appDirectory)),\n typeDocProps: this.resolveDocProps(),\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))}${state.indexer.cachedFileCount ? chalk.greenBright.bold(` (${state.indexer.cachedFileCount}/${state.indexer.mdxFileCount} files cached)`) : \"\"}`,\n )\n }\n\n return compiledMdxFiles\n }\n\n /**\n * When the user adds or removes mdx files, we re-index the site. This function\n * handles module invalidation so that virtual file imports are refreshed as\n * expected by the consumer's dev server.\n */\n sendUpdate() {\n for (const server of this.servers) {\n const virtualModule = server.moduleGraph.getModuleById(VIRTUAL_MODULE_ID)\n if (virtualModule) {\n server.moduleGraph.invalidateModule(virtualModule)\n server.reloadModule(virtualModule)\n }\n }\n }\n\n handleChange(opts: ChangeOptions = {}) {\n // the plugin is activating twice in dev mode. It's mostly harmless, but we\n // prevent logs from emitting twice by flipping a flag\n\n // debounce the change handler to prevent rapid updates from triggering rebuilds\n // in quick succession.\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\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 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 configureServer: (server) => {\n if (!isDev) {\n return\n }\n state.initWatchers(opts?.configFile)\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 },\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 },\n })\n }\n })\n state.servers.push(server)\n },\n handleHotUpdate: async ({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 // ignore watched files. We watch for these separately.\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 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 =\n server.moduleGraph.getModuleById(VIRTUAL_MODULE_ID)\n if (virtualModule) {\n // invalidate the module so that it gets re-evaluated on next refresh\n server.moduleGraph.invalidateModule(virtualModule)\n\n // Send the updated site data to the site so that it has the latest\n // state.\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 === VIRTUAL_MODULE_ID) {\n return `export const siteData = ${JSON.stringify(state.siteData)}`\n }\n return undefined\n },\n name: \"qui-mdx-vite-plugin\",\n resolveId: (id) => {\n if (id === \"@qualcomm-ui/mdx-vite-plugin\") {\n return 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 {type Config, type CosmiconfigResult, cosmiconfigSync} from \"cosmiconfig\"\n\nimport type {QuiDocsConfig} from \"../types\"\n\nimport {configSchema} from \"./config-schema\"\nimport {removeTrailingSlash} from \"./utils\"\n\ninterface LoadedCosmicConfig {\n config: Config\n filepath: string\n isEmpty?: boolean\n}\n\nexport interface ResolvedQuiDocsConfig extends QuiDocsConfig {\n appDirectory: string\n /**\n * full path to the cosmiconfig file.\n */\n filePath: string\n pageDirectory: string\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\nimport {z, type ZodObject, type ZodSchema} from \"zod\"\n\nimport type {\n NavMeta,\n QuiDocsConfig,\n QuiDocsTypeDocOptions,\n RouteMeta,\n} from \"../types\"\n\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\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 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\n .union([\n z.literal(\"vite-generouted\"),\n z.function(z.tuple([z.string()]), z.array(z.string())),\n ])\n .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.ZodNullableType<z.ZodOptionalType<z.ZodType<Model[key]>>>\n : z.ZodOptionalType<z.ZodType<Model[key]>>\n : null extends Model[key]\n ? z.ZodNullableType<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 {z, type ZodObject} from \"zod\"\n\nimport type {PageFrontmatter} from \"@qualcomm-ui/mdx-common\"\n\nimport {implement} from \"./zod\"\n\nexport const isDefined = (\n value: string | boolean | object | null | undefined | number,\n): boolean => typeof value !== \"undefined\" && value !== null\n\nexport function defined<T>(value: T | null | undefined): value is T {\n return typeof value !== \"undefined\" && value !== null\n}\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 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\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 chalk from \"chalk\"\n\nimport type {\n NavItem,\n PageFrontmatter,\n PageMap,\n PageSection,\n} from \"@qualcomm-ui/mdx-common\"\nimport type {QuiPropTypes} from \"@qualcomm-ui/typedoc-common\"\n\nimport type {\n RouteMetaInternal,\n RouteMetaNavInternal,\n SearchIndexerOptions,\n} from \"../types\"\n\nimport {\n type CompiledMdxFile,\n type CompiledMdxFileMetadata,\n DocPropsIndexer,\n filterFileGlob,\n getCategoriesFromPathSegments,\n getPathnameFromPathSegments,\n getPathSegmentsFromFileName,\n getRouteMeta,\n type IndexedPage,\n type IndexedSection,\n MarkdownFileReader,\n MarkdownIndexer,\n NavBuilder,\n} from \"./services\"\nimport {transformRouteMetaArray} from \"./transform-route-meta-array\"\nimport {defined, fixPath} from \"./utils\"\n\nexport class SearchIndexer {\n private readonly docPropsIndexer: DocPropsIndexer\n private readonly markdownIndexer: MarkdownIndexer\n private readonly navBuilder: NavBuilder\n private readonly fileCache: MarkdownFileReader\n private readonly allowedHeadings: Set<string>\n private readonly metaJson: RouteMetaInternal\n private readonly routeMetaNav: Record<string, RouteMetaNavInternal> = {}\n\n get cachedFileCount(): number {\n return this.fileCache.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.fileCache.reset()\n this._pageMap = {}\n this._searchIndex = []\n }\n\n constructor(\n public config: SearchIndexerOptions,\n public logWarnings = true,\n // enable composition by making these classes replaceable\n addons: {\n docPropsIndexer?: DocPropsIndexer\n fileCache?: MarkdownFileReader\n markdownIndexer?: MarkdownIndexer\n navBuilder?: NavBuilder\n } = {},\n ) {\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 this.markdownIndexer =\n addons.markdownIndexer || new MarkdownIndexer(this.allowedHeadings)\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.fileCache =\n addons.fileCache ||\n new MarkdownFileReader(\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 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.fileCache.readFile(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.fileCache.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 this.markdownIndexer.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 indexedPage = cached?.page\n ? cached.page\n : this.markdownIndexer.parseMarkdown(fileContents, frontmatter)\n } catch (error) {\n console.debug(\n `${chalk.yellowBright.bold(\n \"Failed to parse mdx page content.\",\n )} ${chalk.blueBright.bold(filePath)}`,\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.fileCache.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.formatSections(sections, defaultSection, false),\n ]\n\n if (this.config.typeDocPropsOptions?.includeInSearchIndex) {\n sectionReturn.push(\n ...this.formatSections(docPropSections, defaultSection, true),\n )\n }\n\n return {metadata, pageSections: sectionReturn}\n }\n\n private formatSections(\n sections: IndexedSection[],\n {toc: _toc, ...defaultSection}: PageSection,\n isDocProp: boolean,\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:\n section.heading &&\n (this.allowedHeadings.has(section.heading.tagName) || isDocProp)\n ? `${defaultSection.pathname}#${section.heading.id}`\n : defaultSection.pathname,\n id: `${defaultSection.id}-${index}${isDocProp ? \"-prop\" : \"\"}`,\n isDocProp: isDocProp || undefined,\n richContent: section.richContent,\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.fileCache.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 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 type {IndexedSection} from \"../markdown\"\nimport {extractNamesFromAttribute} from \"../mdx-utils\"\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, richContent: []}\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, richContent: []}\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\"\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 chalk from \"chalk\"\nimport {execSync} from \"node:child_process\"\nimport {createHash} from \"node:crypto\"\nimport {readFileSync} from \"node:fs\"\nimport {relative} 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 \"../../../types\"\nimport {frontmatterSchema} from \"../../utils\"\n\nimport type {IndexedPage, IndexedSection} from \"./markdown.types\"\n\nexport interface GitMetadata {\n updatedBy?: string\n updatedOn?: string\n}\n\nfunction getRepoRoot(): string {\n return execSync(\"git rev-parse --show-toplevel\", {\n encoding: \"utf-8\",\n }).trim()\n}\n\n/**\n * Gets the last git commit metadata for a file.\n * Returns undefined values if the file is not tracked by git or if git is\n * unavailable.\n */\nexport function getGitMetadata(\n filePath: string,\n mode: PageTimestampMetadataMode,\n): GitMetadata {\n if (mode === \"off\") {\n return {}\n }\n\n try {\n const repoRoot = getRepoRoot()\n const relativePath = relative(repoRoot, filePath)\n const format = mode === \"user-and-timestamp\" ? \"%cI%n%aN\" : \"%cI\"\n const result = execSync(\n `git log -1 --format=${format} -- \"${relativePath}\"`,\n {\n encoding: \"utf-8\",\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n },\n ).trim()\n\n if (!result) {\n return {}\n }\n\n if (mode === \"user-and-timestamp\") {\n const [updatedOn, updatedBy] = result.split(\"\\n\")\n return {updatedBy, updatedOn}\n }\n\n return {updatedOn: result}\n } catch {\n return {}\n }\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 MarkdownFileReader {\n cachedFileCount = 0\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 readFile(filepath: string): {\n cached: Omit<PageCache, \"md5\"> | undefined\n fileContents: string\n frontmatter: PageFrontmatter\n } {\n const fileContents = readFileSync(filepath, \"utf-8\")\n\n const cached = this.checkCache(filepath, fileContents)\n\n let file:\n | {data: {frontmatter: PageFrontmatter}}\n | ReturnType<typeof unified.processSync>\n if (cached?.frontmatter) {\n file = {data: {frontmatter: cached.frontmatter}}\n } else {\n // only parse the yaml section because we just need the frontmatter at this\n // 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 // 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 = getGitMetadata(filepath, this.pageTimestampMetadata)\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 // Dev mode cache miss (file updated) - reuse git metadata from previous cache\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 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 type {Element} from \"hast\"\nimport {fromHtml} from \"hast-util-from-html\"\nimport {toText} from \"hast-util-to-text\"\nimport {clone, size} from \"lodash-es\"\nimport rehypeParse from \"rehype-parse\"\nimport rehypeStringify from \"rehype-stringify\"\nimport remarkGfm from \"remark-gfm\"\nimport remarkMdx from \"remark-mdx\"\nimport remarkParse from \"remark-parse\"\nimport remarkRehype from \"remark-rehype\"\nimport {unified} from \"unified\"\n\nimport type {\n PageFrontmatter,\n PageHeading,\n RichContentNode,\n} from \"@qualcomm-ui/mdx-common\"\n\nimport {rehypeSlug} from \"../../../rehype/rehype-slug\"\nimport {remarkAlerts} from \"../../../remark/remark-alerts\"\n\nimport type {IndexedPage, IndexedSection} from \"./markdown.types\"\nimport {remarkRemoveMermaidCodeBlocks} from \"./remark-remove-code-blocks\"\nimport {remarkRemoveJsx} from \"./remark-remove-jsx\"\n\n/**\n * Parses an html string into an AST and builds the search index from the tree.\n */\nexport class MarkdownIndexer {\n private sections: IndexedSection[] = []\n private currentSection!: IndexedSection\n private readonly headingLevels: Set<string>\n\n reset(): void {\n this.sections = []\n this._toc = []\n this.resetSection()\n }\n\n resetSection(): void {\n this.currentSection = {\n content: [],\n heading: null,\n richContent: [],\n }\n }\n\n get toc(): PageHeading[] {\n return this._toc\n }\n private _toc: PageHeading[] = []\n\n constructor(headingLevels: Set<string>) {\n this.resetSection()\n this.headingLevels = headingLevels\n }\n\n private appendTocItem(heading: PageHeading) {\n this._toc.push(heading)\n }\n\n private warn(...data: any[]) {\n if (process.env.DEBUG) {\n console.warn(...data)\n }\n // TODO: remove\n console.warn(...data)\n }\n\n private isHeading(element: Element): boolean {\n return this.headingLevels.has(element.tagName)\n }\n\n private isRootHeading(element: Element) {\n return element.tagName === \"h1\"\n }\n\n /**\n * Parses a heading Element node into the indexed heading data structure.\n */\n private parseHeading(headingElement: Element): PageHeading {\n const id = headingElement.properties.id\n const text = toText(headingElement)\n\n return {\n headingLevel: parseInt(headingElement.tagName.charAt(1)),\n id: id ? `${id}` : \"\",\n tagName: headingElement.tagName,\n textContent: text,\n }\n }\n\n private parseElementNode(element: Element) {\n const isRootHeading = this.isRootHeading(element)\n if (this.isHeading(element) || isRootHeading) {\n const currentSection = this.currentSection\n if (currentSection.heading) {\n // the old section is now done, so we add it and start a new one.\n this.sections.push(clone(this.currentSection))\n this.resetSection()\n }\n const heading = this.parseHeading(element)\n if (!isRootHeading) {\n this.appendTocItem(heading)\n }\n this.currentSection.heading = heading\n return\n }\n\n this.currentSection.richContent.push(element as RichContentNode)\n\n const text = toText(element, {whitespace: \"pre-wrap\"})\n .replaceAll(\"\\n\", \"\\t\")\n .split(\"\\t\")\n .filter(size)\n\n if (text.length) {\n this.currentSection.content.push({\n tagName: element.tagName,\n text,\n })\n }\n }\n\n parseMarkdown(\n fileContents: string | Buffer,\n frontmatter: PageFrontmatter,\n ): IndexedPage {\n const file = unified()\n .use(remarkMdx)\n .use(remarkRemoveJsx)\n .use(remarkRemoveMermaidCodeBlocks)\n .use(remarkParse)\n .use(remarkGfm)\n .use(remarkAlerts)\n .use(remarkRehype)\n .use(rehypeStringify)\n .processSync(fileContents)\n\n let contents = file.toString()\n\n contents = contents.substring(contents.indexOf(\"<h1>\"))\n\n for (const [key, value] of Object.entries(frontmatter)) {\n if (typeof value === \"string\" || typeof value === \"number\") {\n contents = contents.replaceAll(`frontmatter.${key}`, `${value}`)\n }\n }\n\n const htmlAst = unified()\n .data(\"settings\", {fragment: true})\n .use(rehypeParse)\n .use(rehypeStringify)\n .use(rehypeSlug)\n .processSync(contents)\n\n contents = htmlAst.toString()\n\n return this.build(contents)\n }\n\n build(html: string): IndexedPage {\n const tree = fromHtml(html, {fragment: true})\n\n for (const child of tree.children) {\n if (child.type === \"element\") {\n this.parseElementNode(child)\n }\n }\n\n // The parser processes sections in order and only appends the content once a\n // new section is encountered. We manually account for the final section here.\n if (this.currentSection.heading?.textContent) {\n this.sections.push(clone(this.currentSection))\n }\n\n return {\n sections: this.sections,\n toc: this.toc,\n }\n }\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\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 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, \"element\", function (node) {\n if (\n headingRank(node) &&\n !node.properties.id &&\n allowedHeadings.has(node.tagName)\n ) {\n node.properties.id = prefix + 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 {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 {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 done()\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\"\n\nimport type {\n NavMeta,\n RouteMetaEntryInternal,\n RouteMetaInternal,\n} from \"../../../types\"\nimport {defined} from \"../../utils\"\n\nimport {getRouteMeta} from \"./get-route-meta\"\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 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 {RouteMetaInternal, RoutingStrategy} from \"../../../types\"\n\nimport {getRouteMeta} from \"./get-route-meta\"\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 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 \"./internal\"\nimport {rehypeSectionize, rehypeSlug, type RehypeSlugOptions} from \"./rehype\"\nimport {remarkAlerts, remarkCodeTabs, remarkSpoilers} from \"./remark\"\nimport {transformerCodeAttribute, transformerNotationHidden} from \"./shiki\"\n\n/**\n * @deprecated migrate to the {@link getRehypePlugins} function\n */\nexport const quiRehypePlugins: PluggableList = [rehypeSectionize, rehypeSlug]\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 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 * @deprecated migrate to the {@link getRemarkPlugins} function\n */\nexport const quiRemarkPlugins: PluggableList = [remarkAlerts, remarkCodeTabs]\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 remarkSpoilers,\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 {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\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 {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\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 = firstChild.value.match(/^:::\\s*spoiler\\s*(.*)$/)\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 (firstText?.type === \"text\" && firstText.value.trim() === \":::\") {\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\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 async 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,kBAAiB;AACzB,SAAQ,YAAAC,WAAU,YAAW;AAC7B,SAAQ,UAAU,SAAS,QAAAC,OAAM,YAAAC,WAAU,WAAAC,gBAAc;AACzD;AAAA,EACE;AAAA,OAKK;AACP,YAAY,QAAQ;AAGpB;AAAA,EAEE,sBAAAC;AAAA,OAEK;AACP,SAAQ,UAAAC,eAAa;;;ACpBrB,OAAOC,YAAW;AAClB,OAAO,cAAc;AACrB,SAAQ,YAAW;AACnB,SAAQ,gBAAAC,qBAAmB;AAC3B,SAAQ,eAAc;AACtB,OAAO,wBAAwB;;;ACL/B,SAA6C,uBAAsB;;;ACAnE,SAAQ,KAAAC,UAAwC;;;ACAhD,SAAQ,SAAQ;AAYT,SAAS,YAA2B;AACzC,SAAO;AAAA,IACL,MAAM,CAKJ,WACG,EAAE,OAAO,MAAM;AAAA,EACtB;AACF;;;ADXO,IAAM,gBAA+B,UAAmB,EAAE,KAAK;AAAA,EACpE,IAAIC,GAAE,MAAM,EAAE,SA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S,UAAAA;AAVT,YAAM,aAAgB;AAAA,QACpB;AAAA,QACA;AAAA,QACG,iBAAa;AAAA,QAChB;AAAA,QACA,cAAc,QAAQ;AAAA,MACxB;AAEA,YAAM,eAAoD,CAAC;AAY3D,MAAAA,OAAM,UAAU;AAEhB,aAAO,aAAa,IAAI,CAAC,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", "join", "relative", "resolve", "quiCustomDarkTheme", "dedent", "chalk", "readFileSync", "z", "z", "z", "z", "chalk", "entry", "propTypes", "heading", "remarkParse", "remarkStringify", "unified", "unified", "remarkParse", "remarkStringify", "remarkMdx", "remarkParse", "unified", "visit", "visit", "item", "remove", "heading", "unified", "remarkMdx", "remarkParse", "capitalCase", "segment", "capitalCase", "state", "routeSegment", "chalk", "readFileSync", "chalk", "config", "file", "remarkFrontmatter", "remarkGfm", "headingRank", "visit", "toString", "visit", "emptyOptions", "visit", "remarkFrontmatter", "remarkGfm", "fromHtml", "visit", "createRequire", "VIRTUAL_MODULE_ID", "quiCustomDarkTheme", "chalk", "isCssAsset", "readFile", "glob", "dedent", "visit", "isRelativeImport", "resolveRelativeImport", "isNodeBuiltin", "loadTsConfigPaths", "relative", "NODE_BUILTINS", "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"]
3
+ "sources": ["../src/angular-demo-plugin/angular-demo-plugin.ts", "../src/docs-plugin/docs-plugin.ts", "../src/docs-plugin/internal/config-loader.ts", "../src/docs-plugin/internal/config-schema.ts", "../src/docs-plugin/internal/zod.ts", "../src/docs-plugin/internal/utils.ts", "../src/docs-plugin/internal/search-indexer.ts", "../src/docs-plugin/internal/services/doc-props/doc-props-indexer.ts", "../src/docs-plugin/internal/services/mdx-utils.ts", "../src/docs-plugin/internal/services/markdown/markdown-file-reader.ts", "../src/docs-plugin/internal/services/markdown/markdown-indexer.ts", "../src/docs-plugin/rehype/rehype-slug.ts", "../src/docs-plugin/remark/remark-alerts.ts", "../src/docs-plugin/internal/services/markdown/remark-remove-code-blocks.ts", "../src/docs-plugin/internal/services/markdown/remark-remove-jsx.ts", "../src/docs-plugin/internal/services/nav-builder/get-route-meta.ts", "../src/docs-plugin/internal/services/nav-builder/nav-builder.ts", "../src/docs-plugin/internal/services/nav-builder/page-map.ts", "../src/docs-plugin/internal/transform-route-meta-array.ts", "../src/docs-plugin/mdx-plugins.ts", "../src/exports.ts", "../src/docs-plugin/rehype/rehype-sectionize.ts", "../src/docs-plugin/remark/remark-code-tabs.ts", "../src/docs-plugin/remark/remark-frontmatter-description.ts", "../src/docs-plugin/remark/remark-self-link-headings.ts", "../src/docs-plugin/remark/remark-spoilers.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} from \"node:fs\"\nimport {readFile, stat} 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 await 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 async 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 async 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\", async (filePath: string) => {\n const fileStats = await stat(filePath).catch(() => undefined)\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 await handleAngularDemoUpdate(filePath)\n triggerRegistryUpdate()\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 chalk from \"chalk\"\nimport chokidar from \"chokidar\"\nimport {glob} from \"glob\"\nimport {readFileSync} from \"node:fs\"\nimport {resolve} from \"node:path\"\nimport prettyMilliseconds from \"pretty-ms\"\nimport type {PluginOption, ViteDevServer} from \"vite\"\n\nimport type {PageDocProps, SiteData} from \"@qualcomm-ui/mdx-common\"\nimport type {QuiPropTypes} from \"@qualcomm-ui/typedoc-common\"\n\nimport {\n type CompiledMdxFile,\n ConfigLoader,\n fixPath,\n type ResolvedQuiDocsConfig,\n SearchIndexer,\n} from \"./internal\"\n\nconst isDev = process.env.NODE_ENV === \"development\"\n\ninterface ChangeOptions {\n onComplete?: () => void\n}\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 VIRTUAL_MODULE_ID = \"\\0@qualcomm-ui/mdx-vite-plugin\"\n\n/**\n * TODO: adjust when https://github.com/vitejs/vite/discussions/16358 lands.\n */\nclass PluginState {\n buildCount: number = 0\n configFilePath: string = \"\"\n docPropsFilePath: string = \"\"\n indexer!: SearchIndexer\n configLoader: ConfigLoader | null = null\n routesDir!: string\n servers: ViteDevServer[] = []\n timeout: ReturnType<typeof setTimeout> | undefined = undefined\n watching = false\n\n private cwd!: string\n\n init(cwd: string) {\n this.cwd = 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 return {\n navItems: state.indexer.navItems,\n pageDocProps: state.indexer.pageDocProps as unknown as PageDocProps,\n pageMap: state.indexer.pageMap,\n searchIndex: state.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.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.indexer = new SearchIndexer({\n ...config,\n srcDir: fixPath(resolve(this.cwd, config.appDirectory)),\n typeDocProps: this.resolveDocProps(),\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))}${state.indexer.cachedFileCount ? chalk.greenBright.bold(` (${state.indexer.cachedFileCount}/${state.indexer.mdxFileCount} files cached)`) : \"\"}`,\n )\n }\n\n return compiledMdxFiles\n }\n\n /**\n * When the user adds or removes mdx files, we re-index the site. This function\n * handles module invalidation so that virtual file imports are refreshed as\n * expected by the consumer's dev server.\n */\n sendUpdate() {\n for (const server of this.servers) {\n const virtualModule = server.moduleGraph.getModuleById(VIRTUAL_MODULE_ID)\n if (virtualModule) {\n server.moduleGraph.invalidateModule(virtualModule)\n server.reloadModule(virtualModule)\n }\n }\n }\n\n handleChange(opts: ChangeOptions = {}) {\n // the plugin is activating twice in dev mode. It's mostly harmless, but we\n // prevent logs from emitting twice by flipping a flag\n\n // debounce the change handler to prevent rapid updates from triggering rebuilds\n // in quick succession.\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\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 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 configureServer: (server) => {\n if (!isDev) {\n return\n }\n state.initWatchers(opts?.configFile)\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 },\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 },\n })\n }\n })\n state.servers.push(server)\n },\n handleHotUpdate: async ({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 // ignore watched files. We watch for these separately.\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 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 =\n server.moduleGraph.getModuleById(VIRTUAL_MODULE_ID)\n if (virtualModule) {\n // invalidate the module so that it gets re-evaluated on next refresh\n server.moduleGraph.invalidateModule(virtualModule)\n\n // Send the updated site data to the site so that it has the latest\n // state.\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 === VIRTUAL_MODULE_ID) {\n return `export const siteData = ${JSON.stringify(state.siteData)}`\n }\n return undefined\n },\n name: \"qui-mdx-vite-plugin\",\n resolveId: (id) => {\n if (id === \"@qualcomm-ui/mdx-vite-plugin\") {\n return 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 {type Config, type CosmiconfigResult, cosmiconfigSync} from \"cosmiconfig\"\n\nimport type {QuiDocsConfig} from \"../types\"\n\nimport {configSchema} from \"./config-schema\"\nimport {removeTrailingSlash} from \"./utils\"\n\ninterface LoadedCosmicConfig {\n config: Config\n filepath: string\n isEmpty?: boolean\n}\n\nexport interface ResolvedQuiDocsConfig extends QuiDocsConfig {\n appDirectory: string\n /**\n * full path to the cosmiconfig file.\n */\n filePath: string\n pageDirectory: string\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\nimport {z, type ZodObject, type ZodSchema} from \"zod\"\n\nimport type {\n KnowledgeConfig,\n KnowledgeExtraFile,\n KnowledgeIntegrationConfig,\n NavMeta,\n QuiDocsConfig,\n QuiDocsTypeDocOptions,\n RouteMeta,\n} from \"../types\"\n\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 title: z.string(),\n})\n\nconst knowledgeIntegrationSchema = implement<KnowledgeIntegrationConfig>().with(\n {\n baseUrl: z.string().optional(),\n description: z.string().optional(),\n exclude: z.array(z.string()).optional(),\n extraFiles: z.array(knowledgeExtraFileSchema).optional(),\n metadata: z.record(z.string(), z.string()).optional(),\n name: z.string().optional(),\n outputMode: z\n .union([z.literal(\"per-page\"), z.literal(\"aggregated\")])\n .optional(),\n outputPath: z.string().optional(),\n pageTitlePrefix: z.string().optional(),\n },\n)\n\nconst knowledgeConfigSchema = implement<KnowledgeConfig>().with({\n global: knowledgeIntegrationSchema.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 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 {z, type ZodObject} from \"zod\"\n\nimport type {PageFrontmatter} from \"@qualcomm-ui/mdx-common\"\n\nimport {implement} from \"./zod\"\n\nexport const isDefined = (\n value: string | boolean | object | null | undefined | number,\n): boolean => typeof value !== \"undefined\" && value !== null\n\nexport function defined<T>(value: T | null | undefined): value is T {\n return typeof value !== \"undefined\" && value !== null\n}\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\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 chalk from \"chalk\"\n\nimport type {\n NavItem,\n PageFrontmatter,\n PageMap,\n PageSection,\n} from \"@qualcomm-ui/mdx-common\"\nimport type {QuiPropTypes} from \"@qualcomm-ui/typedoc-common\"\n\nimport type {\n RouteMetaInternal,\n RouteMetaNavInternal,\n SearchIndexerOptions,\n} from \"../types\"\n\nimport {\n type CompiledMdxFile,\n type CompiledMdxFileMetadata,\n DocPropsIndexer,\n filterFileGlob,\n getCategoriesFromPathSegments,\n getPathnameFromPathSegments,\n getPathSegmentsFromFileName,\n getRouteMeta,\n type IndexedPage,\n type IndexedSection,\n MarkdownFileReader,\n MarkdownIndexer,\n NavBuilder,\n} from \"./services\"\nimport {transformRouteMetaArray} from \"./transform-route-meta-array\"\nimport {defined, fixPath} from \"./utils\"\n\nexport class SearchIndexer {\n private readonly docPropsIndexer: DocPropsIndexer\n private readonly markdownIndexer: MarkdownIndexer\n private readonly navBuilder: NavBuilder\n private readonly fileCache: MarkdownFileReader\n private readonly allowedHeadings: Set<string>\n private readonly metaJson: RouteMetaInternal\n private readonly routeMetaNav: Record<string, RouteMetaNavInternal> = {}\n\n get cachedFileCount(): number {\n return this.fileCache.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.fileCache.reset()\n this._pageMap = {}\n this._searchIndex = []\n }\n\n constructor(\n public config: SearchIndexerOptions,\n public logWarnings = true,\n // enable composition by making these classes replaceable\n addons: {\n docPropsIndexer?: DocPropsIndexer\n fileCache?: MarkdownFileReader\n markdownIndexer?: MarkdownIndexer\n navBuilder?: NavBuilder\n } = {},\n ) {\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 this.markdownIndexer =\n addons.markdownIndexer || new MarkdownIndexer(this.allowedHeadings)\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.fileCache =\n addons.fileCache ||\n new MarkdownFileReader(\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.fileCache.readFile(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.fileCache.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 this.markdownIndexer.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 indexedPage = cached?.page\n ? cached.page\n : this.markdownIndexer.parseMarkdown(fileContents, frontmatter)\n } catch (error) {\n console.debug(\n `${chalk.yellowBright.bold(\n \"Failed to parse mdx page content.\",\n )} ${chalk.blueBright.bold(filePath)}`,\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.fileCache.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.formatSections(sections, defaultSection, false),\n ]\n\n if (this.config.typeDocPropsOptions?.includeInSearchIndex) {\n sectionReturn.push(\n ...this.formatSections(docPropSections, defaultSection, true),\n )\n }\n\n return {metadata, pageSections: sectionReturn}\n }\n\n private formatSections(\n sections: IndexedSection[],\n {toc: _toc, ...defaultSection}: PageSection,\n isDocProp: boolean,\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:\n section.heading &&\n (this.allowedHeadings.has(section.heading.tagName) || isDocProp)\n ? `${defaultSection.pathname}#${section.heading.id}`\n : defaultSection.pathname,\n id: `${defaultSection.id}-${index}${isDocProp ? \"-prop\" : \"\"}`,\n isDocProp: isDocProp || undefined,\n richContent: section.richContent,\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.fileCache.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 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 type {IndexedSection} from \"../markdown\"\nimport {extractNamesFromAttribute} from \"../mdx-utils\"\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, richContent: []}\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, richContent: []}\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\"\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 chalk from \"chalk\"\nimport {execSync} from \"node:child_process\"\nimport {createHash} from \"node:crypto\"\nimport {readFileSync} from \"node:fs\"\nimport {relative} 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 \"../../../types\"\nimport {frontmatterSchema} from \"../../utils\"\n\nimport type {IndexedPage, IndexedSection} from \"./markdown.types\"\n\nexport interface GitMetadata {\n updatedBy?: string\n updatedOn?: string\n}\n\nfunction getRepoRoot(): string {\n return execSync(\"git rev-parse --show-toplevel\", {\n encoding: \"utf-8\",\n }).trim()\n}\n\n/**\n * Gets the last git commit metadata for a file.\n * Returns undefined values if the file is not tracked by git or if git is\n * unavailable.\n */\nexport function getGitMetadata(\n filePath: string,\n mode: PageTimestampMetadataMode,\n): GitMetadata {\n if (mode === \"off\") {\n return {}\n }\n\n try {\n const repoRoot = getRepoRoot()\n const relativePath = relative(repoRoot, filePath)\n const format = mode === \"user-and-timestamp\" ? \"%cI%n%aN\" : \"%cI\"\n const result = execSync(\n `git log -1 --format=${format} -- \"${relativePath}\"`,\n {\n encoding: \"utf-8\",\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n },\n ).trim()\n\n if (!result) {\n return {}\n }\n\n if (mode === \"user-and-timestamp\") {\n const [updatedOn, updatedBy] = result.split(\"\\n\")\n return {updatedBy, updatedOn}\n }\n\n return {updatedOn: result}\n } catch {\n return {}\n }\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 MarkdownFileReader {\n cachedFileCount = 0\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 readFile(filepath: string): {\n cached: Omit<PageCache, \"md5\"> | undefined\n fileContents: string\n frontmatter: PageFrontmatter\n } {\n const fileContents = readFileSync(filepath, \"utf-8\")\n\n const cached = this.checkCache(filepath, fileContents)\n\n let file:\n | {data: {frontmatter: PageFrontmatter}}\n | ReturnType<typeof unified.processSync>\n if (cached?.frontmatter) {\n file = {data: {frontmatter: cached.frontmatter}}\n } else {\n // only parse the yaml section because we just need the frontmatter at this\n // 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 // 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 = getGitMetadata(filepath, this.pageTimestampMetadata)\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 // Dev mode cache miss (file updated) - reuse git metadata from previous cache\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 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 type {Element} from \"hast\"\nimport {fromHtml} from \"hast-util-from-html\"\nimport {toText} from \"hast-util-to-text\"\nimport {clone, size} from \"lodash-es\"\nimport rehypeParse from \"rehype-parse\"\nimport rehypeStringify from \"rehype-stringify\"\nimport remarkGfm from \"remark-gfm\"\nimport remarkMdx from \"remark-mdx\"\nimport remarkParse from \"remark-parse\"\nimport remarkRehype from \"remark-rehype\"\nimport {unified} from \"unified\"\n\nimport type {\n PageFrontmatter,\n PageHeading,\n RichContentNode,\n} from \"@qualcomm-ui/mdx-common\"\n\nimport {rehypeSlug} from \"../../../rehype/rehype-slug\"\nimport {remarkAlerts} from \"../../../remark/remark-alerts\"\n\nimport type {IndexedPage, IndexedSection} from \"./markdown.types\"\nimport {remarkRemoveMermaidCodeBlocks} from \"./remark-remove-code-blocks\"\nimport {remarkRemoveJsx} from \"./remark-remove-jsx\"\n\n/**\n * Parses an html string into an AST and builds the search index from the tree.\n */\nexport class MarkdownIndexer {\n private sections: IndexedSection[] = []\n private currentSection!: IndexedSection\n private readonly headingLevels: Set<string>\n\n reset(): void {\n this.sections = []\n this._toc = []\n this.resetSection()\n }\n\n resetSection(): void {\n this.currentSection = {\n content: [],\n heading: null,\n richContent: [],\n }\n }\n\n get toc(): PageHeading[] {\n return this._toc\n }\n private _toc: PageHeading[] = []\n\n constructor(headingLevels: Set<string>) {\n this.resetSection()\n this.headingLevels = headingLevels\n }\n\n private appendTocItem(heading: PageHeading) {\n this._toc.push(heading)\n }\n\n private warn(...data: any[]) {\n if (process.env.DEBUG) {\n console.warn(...data)\n }\n // TODO: remove\n console.warn(...data)\n }\n\n private isHeading(element: Element): boolean {\n return this.headingLevels.has(element.tagName)\n }\n\n private isRootHeading(element: Element) {\n return element.tagName === \"h1\"\n }\n\n /**\n * Parses a heading Element node into the indexed heading data structure.\n */\n private parseHeading(headingElement: Element): PageHeading {\n const id = headingElement.properties.id\n const text = toText(headingElement)\n\n return {\n headingLevel: parseInt(headingElement.tagName.charAt(1)),\n id: id ? `${id}` : \"\",\n tagName: headingElement.tagName,\n textContent: text,\n }\n }\n\n private parseElementNode(element: Element) {\n const isRootHeading = this.isRootHeading(element)\n if (this.isHeading(element) || isRootHeading) {\n const currentSection = this.currentSection\n if (currentSection.heading) {\n // the old section is now done, so we add it and start a new one.\n this.sections.push(clone(this.currentSection))\n this.resetSection()\n }\n const heading = this.parseHeading(element)\n if (!isRootHeading) {\n this.appendTocItem(heading)\n }\n this.currentSection.heading = heading\n return\n }\n\n this.currentSection.richContent.push(element as RichContentNode)\n\n const text = toText(element, {whitespace: \"pre-wrap\"})\n .replaceAll(\"\\n\", \"\\t\")\n .split(\"\\t\")\n .filter(size)\n\n if (text.length) {\n this.currentSection.content.push({\n tagName: element.tagName,\n text,\n })\n }\n }\n\n parseMarkdown(\n fileContents: string | Buffer,\n frontmatter: PageFrontmatter,\n ): IndexedPage {\n const file = unified()\n .use(remarkMdx)\n .use(remarkRemoveJsx)\n .use(remarkRemoveMermaidCodeBlocks)\n .use(remarkParse)\n .use(remarkGfm)\n .use(remarkAlerts)\n .use(remarkRehype)\n .use(rehypeStringify)\n .processSync(fileContents)\n\n let contents = file.toString()\n\n contents = contents.substring(contents.indexOf(\"<h1>\"))\n\n for (const [key, value] of Object.entries(frontmatter)) {\n if (typeof value === \"string\" || typeof value === \"number\") {\n contents = contents.replaceAll(`frontmatter.${key}`, `${value}`)\n }\n }\n\n const htmlAst = unified()\n .data(\"settings\", {fragment: true})\n .use(rehypeParse)\n .use(rehypeStringify)\n .use(rehypeSlug)\n .processSync(contents)\n\n contents = htmlAst.toString()\n\n return this.build(contents)\n }\n\n build(html: string): IndexedPage {\n const tree = fromHtml(html, {fragment: true})\n\n for (const child of tree.children) {\n if (child.type === \"element\") {\n this.parseElementNode(child)\n }\n }\n\n // The parser processes sections in order and only appends the content once a\n // new section is encountered. We manually account for the final section here.\n if (this.currentSection.heading?.textContent) {\n this.sections.push(clone(this.currentSection))\n }\n\n return {\n sections: this.sections,\n toc: this.toc,\n }\n }\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\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 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, \"element\", function (node) {\n if (\n headingRank(node) &&\n !node.properties.id &&\n allowedHeadings.has(node.tagName)\n ) {\n node.properties.id = prefix + 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 {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 {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 done()\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\"\n\nimport type {\n NavMeta,\n RouteMetaEntryInternal,\n RouteMetaInternal,\n} from \"../../../types\"\nimport {defined} from \"../../utils\"\n\nimport {getRouteMeta} from \"./get-route-meta\"\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 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 {RouteMetaInternal, RoutingStrategy} from \"../../../types\"\n\nimport {getRouteMeta} from \"./get-route-meta\"\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 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 \"./internal\"\nimport {rehypeSectionize, rehypeSlug, type RehypeSlugOptions} from \"./rehype\"\nimport {\n remarkAlerts,\n remarkCodeTabs,\n remarkFrontmatterDescription,\n remarkSpoilers,\n} from \"./remark\"\nimport {transformerCodeAttribute, transformerNotationHidden} from \"./shiki\"\n\n/**\n * @deprecated migrate to the {@link getRehypePlugins} function\n */\nexport const quiRehypePlugins: PluggableList = [rehypeSectionize, rehypeSlug]\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 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 * @deprecated migrate to the {@link getRemarkPlugins} function\n */\nexport const quiRemarkPlugins: PluggableList = [remarkAlerts, remarkCodeTabs]\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 remarkFrontmatterDescription,\n remarkSpoilers,\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 {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\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 {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\",\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 {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\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 = firstChild.value.match(/^:::\\s*spoiler\\s*(.*)$/)\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 (firstText?.type === \"text\" && firstText.value.trim() === \":::\") {\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\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 async 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,kBAAiB;AACzB,SAAQ,YAAAC,WAAU,YAAW;AAC7B,SAAQ,UAAU,SAAS,QAAAC,OAAM,YAAAC,WAAU,WAAAC,gBAAc;AACzD;AAAA,EACE;AAAA,OAKK;AACP,YAAY,QAAQ;AAGpB;AAAA,EAEE,sBAAAC;AAAA,OAEK;AACP,SAAQ,UAAAC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,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", "join", "relative", "resolve", "quiCustomDarkTheme", "dedent", "chalk", "readFileSync", "z", "z", "z", "z", "chalk", "entry", "propTypes", "heading", "remarkParse", "remarkStringify", "unified", "unified", "remarkParse", "remarkStringify", "remarkMdx", "remarkParse", "unified", "visit", "visit", "item", "remove", "heading", "unified", "remarkMdx", "remarkParse", "capitalCase", "segment", "capitalCase", "state", "routeSegment", "chalk", "readFileSync", "chalk", "config", "file", "remarkFrontmatter", "remarkGfm", "headingRank", "visit", "visit", "toString", "visit", "emptyOptions", "visit", "remarkFrontmatter", "remarkGfm", "fromHtml", "visit", "createRequire", "VIRTUAL_MODULE_ID", "quiCustomDarkTheme", "chalk", "isCssAsset", "readFile", "glob", "dedent", "visit", "isRelativeImport", "resolveRelativeImport", "isNodeBuiltin", "loadTsConfigPaths", "relative", "NODE_BUILTINS", "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
  }